diff --git a/Cargo.lock b/Cargo.lock index fee7ebc..aeb583b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9062,6 +9062,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", + "tsclientlib", "voelin-core", "voelin-media", "voelin-model", diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt index 64a199a..75be7f3 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt @@ -30,12 +30,23 @@ object Bridge { } /** - * Run the voice service with this notification text (`muted`: the action - * offers Unmute); null stops it. + * Run the voice service with this notification (`muted`, `deafened`: the + * actions offer Unmute, Undeafen; `sinceMs`: in voice since, Unix ms, 0 + * while connecting); a null title stops it. */ @JvmStatic - fun setVoiceNotification(text: String?, muted: Boolean) { - if (text == null) VoiceService.stop(app) else VoiceService.start(app, text, muted) + fun setVoiceNotification(title: String?, text: String?, muted: Boolean, deafened: Boolean, sinceMs: Long) { + if (title == null) { + VoiceService.stop(app) + } else { + VoiceService.start(app, VoiceService.Notice(title, text ?: "", muted, deafened, sinceMs)) + } + } + + /** What the screen-sharing notification says while our stream is live; null: the default. */ + @JvmStatic + fun setScreenNotification(title: String?, text: String?) { + ScreenCaptureService.setNotice(title, text) } /** Ask the user to share the screen; the answer goes to Native.onScreenCaptureResult. */ diff --git a/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt b/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt index 98c995c..16bb883 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/MainActivity.kt @@ -9,7 +9,7 @@ import java.lang.ref.WeakReference /** * The window: a NativeActivity running `android_main` of libvoelin_android.so * (the Slint UI). Kotlin only handles what needs an Activity: permission - * prompts and the screen-capture consent dialog. + * prompts, the screen-capture consent dialog and a tapped notification. */ class MainActivity : NativeActivity() { private var captureFps = 30 @@ -18,6 +18,14 @@ class MainActivity : NativeActivity() { override fun onCreate(savedInstanceState: Bundle?) { current = WeakReference(this) super.onCreate(savedInstanceState) + // Not again when the activity is recreated with the same intent. + if (savedInstanceState == null) handle(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handle(intent) } override fun onDestroy() { @@ -34,6 +42,13 @@ class MainActivity : NativeActivity() { moveTaskToBack(true) } + /** A tapped voice notification. */ + private fun handle(intent: Intent?) { + when (intent?.action) { + VoiceService.ACTION_OPEN_VOICE -> Native.onOpenVoice() + } + } + /** Show the system's "start recording or casting?" dialog. */ fun requestScreenCapture(fps: Int, maxSize: Int) { captureFps = fps diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt index 7aacd8e..cc3ac44 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Native.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Native.kt @@ -49,4 +49,12 @@ object Native { /** "Mute" / "Unmute" in the voice notification. */ @JvmStatic external fun onToggleMute() + + /** "Deafen" / "Undeafen" in the voice notification. */ + @JvmStatic + external fun onToggleDeafen() + + /** The voice notification was tapped: show the voice channel. */ + @JvmStatic + external fun onOpenVoice() } diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt b/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt index f537eee..07fedbb 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Notifications.kt @@ -12,6 +12,9 @@ object Notifications { const val CHANNEL_VOICE = "voice" const val CHANNEL_SCREEN = "screen" + /** The app's accent (Theme.accent of the UI). */ + private const val ACCENT = 0xFF2D6BFF.toInt() + fun createChannels(context: Context) { val manager = context.getSystemService(NotificationManager::class.java) manager.createNotificationChannel( @@ -30,31 +33,45 @@ object Notifications { ) } - /** Tapping a notification brings the app back. */ - private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity( + /** Tapping a notification brings the app back, with `action` for MainActivity. */ + fun openApp(context: Context, action: String? = null): PendingIntent = PendingIntent.getActivity( context, - 0, - Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), + action.hashCode(), + Intent(context, MainActivity::class.java) + .setAction(action) + .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), PendingIntent.FLAG_IMMUTABLE, ) - /** An ongoing notification with `actions` (title, intent). */ + /** + * An ongoing notification: `title` and `text`, a chronometer from + * `sinceMs` (Unix ms; 0: none), `actions` (title, intent). + */ fun ongoing( context: Context, channel: String, + title: String, text: String, + open: PendingIntent, + sinceMs: Long, vararg actions: Pair, ): Notification { val builder = Notification.Builder(context, channel) .setSmallIcon(R.drawable.ic_notification) - .setContentTitle(context.getString(R.string.app_name)) + .setColor(ACCENT) + .setContentTitle(title) .setContentText(text) - .setContentIntent(openApp(context)) + .setContentIntent(open) .setOngoing(true) .setOnlyAlertOnce(true) .setCategory(Notification.CATEGORY_CALL) - for ((title, intent) in actions) { - builder.addAction(Notification.Action.Builder(null, title, intent).build()) + if (sinceMs > 0) { + builder.setWhen(sinceMs).setShowWhen(true).setUsesChronometer(true) + } else { + builder.setShowWhen(false) + } + for ((label, intent) in actions) { + builder.addAction(Notification.Action.Builder(null, label, intent).build()) } return builder.build() } diff --git a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt index 0daf999..814a6f5 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt @@ -1,6 +1,8 @@ package io.github.faumaray.voelin import android.Manifest +import android.app.Notification +import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context @@ -66,21 +68,9 @@ class ScreenCaptureService : Service() { return START_NOT_STICKY } if (projection != null) return START_NOT_STICKY - val stop = PendingIntent.getService( - this, - 0, - Intent(this, ScreenCaptureService::class.java).setAction(ACTION_STOP), - PendingIntent.FLAG_IMMUTABLE, - ) - val notification = Notifications.ongoing( - this, - Notifications.CHANNEL_SCREEN, - getString(R.string.screen_sharing), - getString(R.string.stop_sharing) to stop, - ) try { // Must be in the foreground before getMediaProjection (Android 14). - startForeground(ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) + startForeground(ID, notification(this), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) val data = if (Build.VERSION.SDK_INT >= 33) { intent.getParcelableExtra(EXTRA_DATA, Intent::class.java) } else { @@ -259,6 +249,36 @@ class ScreenCaptureService : Service() { @Volatile private var instance: ScreenCaptureService? = null + /** Where our stream is live and who watches ("Live in Chill Zone"), or null. */ + @Volatile + private var notice: Pair? = null + + private fun notification(context: Context): Notification { + val stop = PendingIntent.getService( + context, + 0, + Intent(context, ScreenCaptureService::class.java).setAction(ACTION_STOP), + PendingIntent.FLAG_IMMUTABLE, + ) + val (title, text) = notice ?: (context.getString(R.string.screen_sharing) to context.getString(R.string.screen_sharing_text)) + return Notifications.ongoing( + context, + Notifications.CHANNEL_SCREEN, + title, + text, + Notifications.openApp(context), + 0, + context.getString(R.string.stop_sharing) to stop, + ) + } + + /** What the notification says while our stream is live (null: the default). */ + fun setNotice(title: String?, text: String?) { + notice = if (title != null) title to (text ?: "") else null + val service = instance ?: return + service.getSystemService(NotificationManager::class.java).notify(ID, notification(service)) + } + /** Start capturing with the consent the user just gave. */ fun start(context: Context, resultCode: Int, data: Intent, fps: Int, maxSize: Int) { val intent = Intent(context, ScreenCaptureService::class.java) diff --git a/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt b/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt index b0e15d2..0f43e0f 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/VoiceService.kt @@ -15,8 +15,19 @@ import android.util.Log * Foreground service while a voice connection exists: Android keeps the * process, the network and (type microphone) the microphone of an app in * the background only this way. The Rust side starts, updates and stops it. + * Its notification is the voice bar of the app: the channel, the server and + * how many are there, the time in voice, and Mute, Deafen and Leave. */ class VoiceService : Service() { + /** What the notification shows (crates/voelin-android/src/foreground.rs). */ + data class Notice( + val title: String, + val text: String, + val muted: Boolean, + val deafened: Boolean, + val sinceMs: Long, + ) + override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { @@ -29,14 +40,17 @@ class VoiceService : Service() { Native.onToggleMute() return START_NOT_STICKY } + ACTION_TOGGLE_DEAFEN -> { + Native.onToggleDeafen() + return START_NOT_STICKY + } } - val text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected) - val muted = intent?.getBooleanExtra(EXTRA_MUTED, false) ?: false + val notice = notice ?: Notice(getString(R.string.voice_connected), "", false, false, 0) try { if (Build.VERSION.SDK_INT >= 30) { - startForeground(ID, notification(this, text, muted), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) + startForeground(ID, notification(this, notice), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE) } else { - startForeground(ID, notification(this, text, muted)) + startForeground(ID, notification(this, notice)) } running = this } catch (e: RuntimeException) { @@ -56,14 +70,20 @@ class VoiceService : Service() { companion object { private const val TAG = "VoiceService" private const val ID = 1 - private const val EXTRA_TEXT = "text" - private const val EXTRA_MUTED = "muted" private const val ACTION_DISCONNECT = "io.github.faumaray.voelin.DISCONNECT" private const val ACTION_TOGGLE_MUTE = "io.github.faumaray.voelin.TOGGLE_MUTE" + private const val ACTION_TOGGLE_DEAFEN = "io.github.faumaray.voelin.TOGGLE_DEAFEN" + + /** MainActivity shows the voice channel for this action. */ + const val ACTION_OPEN_VOICE = "io.github.faumaray.voelin.OPEN_VOICE" @Volatile private var running: VoiceService? = null + /** The latest notice, for a service that is still starting. */ + @Volatile + private var notice: Notice? = null + private fun action(context: Context, action: String, request: Int): PendingIntent = PendingIntent.getService( context, @@ -72,30 +92,32 @@ class VoiceService : Service() { PendingIntent.FLAG_IMMUTABLE, ) - private fun notification(context: Context, text: String, muted: Boolean): Notification = + private fun notification(context: Context, notice: Notice): Notification = Notifications.ongoing( context, Notifications.CHANNEL_VOICE, - text, - context.getString(if (muted) R.string.unmute else R.string.mute) to + notice.title, + notice.text, + Notifications.openApp(context, ACTION_OPEN_VOICE), + notice.sinceMs, + context.getString(if (notice.muted) R.string.unmute else R.string.mute) to action(context, ACTION_TOGGLE_MUTE, 1), - context.getString(R.string.disconnect) to action(context, ACTION_DISCONNECT, 0), + context.getString(if (notice.deafened) R.string.undeafen else R.string.deafen) to + action(context, ACTION_TOGGLE_DEAFEN, 2), + context.getString(R.string.leave) to action(context, ACTION_DISCONNECT, 0), ) /** Start the service, or update its notification when it runs. */ - fun start(context: Context, text: String, muted: Boolean) { + fun start(context: Context, notice: Notice) { + this.notice = notice val service = running if (service != null) { service.getSystemService(NotificationManager::class.java) - .notify(ID, notification(service, text, muted)) + .notify(ID, notification(service, notice)) return } try { - context.startForegroundService( - Intent(context, VoiceService::class.java) - .putExtra(EXTRA_TEXT, text) - .putExtra(EXTRA_MUTED, muted), - ) + context.startForegroundService(Intent(context, VoiceService::class.java)) } catch (e: RuntimeException) { // Not allowed from the background (Android 12+). Voice is // connected from the UI, so this should not happen. @@ -104,6 +126,7 @@ class VoiceService : Service() { } fun stop(context: Context) { + notice = null context.stopService(Intent(context, VoiceService::class.java)) } } diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 864bada..fa92f27 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -4,9 +4,12 @@ Voice connection Screen sharing Connected to voice - Disconnect + Leave Mute Unmute + Deafen + Undeafen Sharing your screen + Starting the stream Stop sharing diff --git a/crates/voelin-android/Cargo.toml b/crates/voelin-android/Cargo.toml index 4bca1ef..7ba4c75 100644 --- a/crates/voelin-android/Cargo.toml +++ b/crates/voelin-android/Cargo.toml @@ -18,6 +18,8 @@ crate-type = ["cdylib", "rlib"] tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "time"] } tracing = "0.1.44" voelin-core = { path = "../voelin-core" } +# Channels and people for the voice notification. +voelin-model = { path = "../voelin-model" } [target.'cfg(target_os = "android")'.dependencies] anyhow = "1.0.104" @@ -31,7 +33,8 @@ voelin-store = { path = "../voelin-store" } voelin-ui = { path = "../voelin-ui" } [dev-dependencies] -voelin-model = { path = "../voelin-model" } +# Client ids of stream viewers in the tests. +tsclientlib = { path = "../proto/tsclientlib" } [lints] workspace = true diff --git a/crates/voelin-android/src/app.rs b/crates/voelin-android/src/app.rs index 4290811..19d5695 100644 --- a/crates/voelin-android/src/app.rs +++ b/crates/voelin-android/src/app.rs @@ -108,18 +108,25 @@ fn install_crash_reports(data_dir: &Path) { voelin_platform::crash::install(data_dir.join(voelin_platform::crash::DIR_NAME), enabled); } -/// Keep the voice foreground service in step with the voice connections. +/// Keep the voice foreground service, and the screen-sharing service's +/// notification, in step with the voice connections and our stream. fn watch_voice(host: &'static EngineHost) { let mut events = host.engine().subscribe(); host.runtime().spawn(async move { loop { match events.recv().await { Ok(event) => { - if let Some(notice) = with_foreground(|f| f.update(&event)) + let changes = with_foreground(|f| f.update(&event)); + if let Some(notice) = changes.voice && let Err(e) = bridge::set_voice_notification(notice.as_ref()) { warn!("voice service: {e}"); } + if let Some(notice) = changes.screen + && let Err(e) = bridge::set_screen_notification(notice.as_ref()) + { + warn!("screen sharing notification: {e}"); + } } Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, Err(tokio::sync::broadcast::error::RecvError::Closed) => break, @@ -150,3 +157,15 @@ pub fn toggle_mute() { host.engine().send(Command::SetInputMuted { session, muted: !muted }); } } + +/// "Deafen" / "Undeafen" in the voice notification, as Mute does. +pub fn toggle_deafen() { + let Some(host) = HOST.get() else { + return; + }; + let (sessions, deafened) = + with_foreground(|f| (f.voice_sessions(), f.notice().is_some_and(|n| n.deafened))); + for session in sessions { + host.engine().send(Command::SetOutputMuted { session, muted: !deafened }); + } +} diff --git a/crates/voelin-android/src/bridge.rs b/crates/voelin-android/src/bridge.rs index 9bee6f3..d33e2ed 100644 --- a/crates/voelin-android/src/bridge.rs +++ b/crates/voelin-android/src/bridge.rs @@ -15,7 +15,7 @@ use jni::refs::{Global, Reference as _}; use jni::sys::{jboolean, jint, jlong}; use jni::{Env, JavaVM, jni_sig, jni_str, native_method}; -use crate::foreground::VoiceNotice; +use crate::foreground::{ScreenNotice, VoiceNotice}; static BRIDGE: OnceLock>> = OnceLock::new(); @@ -58,18 +58,56 @@ pub fn request_permissions() -> Result<()> { }) } +/// A Java string, or `null` for `None`. +fn string_or_null<'local>(env: &mut Env<'local>, text: Option<&str>) -> Result> { + Ok(match text { + Some(text) => JObject::from(env.new_string(text)?), + None => JObject::null(), + }) +} + /// Show or update the voice service's notification; `None` stops the service. pub fn set_voice_notification(notice: Option<&VoiceNotice>) -> Result<()> { with_bridge(|env, class| { - let (text, muted) = match notice { - Some(n) => (JObject::from(env.new_string(&n.text)?), n.muted), - None => (JObject::null(), false), - }; + let title = string_or_null(env, notice.map(|n| n.title.as_str()))?; + let text = string_or_null(env, notice.map(|n| n.text.as_str()))?; + let (muted, deafened, since) = + notice.map_or((false, false, 0), |n| (n.muted, n.deafened, n.since_ms)); env.call_static_method( class, jni_str!("setVoiceNotification"), - jni_sig!((text: java.lang.String, muted: jboolean) -> void), - &[JValue::Object(&text), JValue::Bool(muted)], + jni_sig!( + ( + title: java.lang.String, + text: java.lang.String, + muted: jboolean, + deafened: jboolean, + since_ms: jlong, + ) -> void + ), + &[ + JValue::Object(&title), + JValue::Object(&text), + JValue::Bool(muted), + JValue::Bool(deafened), + JValue::Long(since as jlong), + ], + )?; + Ok(()) + }) +} + +/// What the screen-sharing notification says while our stream is live; +/// `None` puts back the plain "sharing your screen". +pub fn set_screen_notification(notice: Option<&ScreenNotice>) -> Result<()> { + with_bridge(|env, class| { + let title = string_or_null(env, notice.map(|n| n.title.as_str()))?; + let text = string_or_null(env, notice.map(|n| n.text.as_str()))?; + env.call_static_method( + class, + jni_str!("setScreenNotification"), + jni_sig!((title: java.lang.String, text: java.lang.String) -> void), + &[JValue::Object(&title), JValue::Object(&text)], )?; Ok(()) }) @@ -368,3 +406,25 @@ fn on_toggle_mute<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Res crate::app::toggle_mute(); Ok(()) } + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_toggle_deafen(), +}; + +/// "Deafen" / "Undeafen" in the voice notification. +fn on_toggle_deafen<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::app::toggle_deafen(); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.voelin.Native", + static extern fn on_open_voice(), +}; + +/// The voice notification was tapped: show the voice channel. +fn on_open_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + voelin_ui::request(voelin_ui::Request::ShowVoice); + Ok(()) +} diff --git a/crates/voelin-android/src/foreground.rs b/crates/voelin-android/src/foreground.rs index bd6bc1f..e48434e 100644 --- a/crates/voelin-android/src/foreground.rs +++ b/crates/voelin-android/src/foreground.rs @@ -1,20 +1,49 @@ -//! When the app needs its voice foreground service. +//! What the app's foreground services show. //! //! Android keeps the microphone and the process of a backgrounded app only -//! while a foreground service with a visible notification runs. The service -//! runs while any session has a voice connection (connecting or connected); -//! its notification names the servers and offers Mute and Disconnect. +//! while a foreground service with a visible notification runs. The voice +//! service runs while any session has a voice connection (connecting or +//! connected); its notification names the channel and the server, counts +//! the people there and offers Mute, Deafen and Leave. While our stream is +//! live, the screen-sharing service's notification says where it goes and +//! how many watch. use std::collections::BTreeMap; +use std::sync::Arc; +use voelin_core::stream::{StreamState, ViewerInfo, ViewerState}; use voelin_core::{Event, SessionId, VoiceState}; +use voelin_model::Presence; /// What the voice notification shows. #[derive(Clone, Debug, PartialEq, Eq)] pub struct VoiceNotice { + /// The channel we are in ("Chill Zone"), or what is going on. + pub title: String, + /// The server and how many are in the channel. pub text: String, /// The microphone is muted in every voice session (the action unmutes). pub muted: bool, + /// The sound is off in every voice session (the action turns it on). + pub deafened: bool, + /// When the first voice session connected (Unix ms), for the elapsed + /// time; 0 while connecting. + pub since_ms: u64, +} + +/// What the screen-sharing notification shows while our stream is live. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScreenNotice { + pub title: String, + pub text: String, +} + +/// The notifications that changed with an event: `Some(None)` stops the +/// voice service, or puts the screen notification back to its default. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Changes { + pub voice: Option>, + pub screen: Option>, } #[derive(Default)] @@ -27,26 +56,81 @@ struct Session { name: Option, voice: VoiceState, muted: bool, + deafened: bool, + own_channel: Option, + presence: Arc, + /// When voice connected (Unix ms). + since_ms: Option, + /// Our stream is live. + live: bool, + /// Viewers connected to our stream. + watching: usize, +} + +impl Session { + fn name(&self) -> &str { + self.name.as_deref().unwrap_or("a server") + } + + /// Our channel's name and how many are in it. + fn channel(&self) -> Option<(&str, usize)> { + let id = self.own_channel?; + let channel = self.presence.channels.get(&id)?; + let people = + self.presence.clients.values().filter(|c| c.channel == id && !c.is_query).count(); + Some((channel.name.as_str(), people)) + } +} + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as u64) } impl Foreground { - /// Apply `event`. Returns the new notification when it changed: - /// `Some(None)` means the service should stop. - pub fn update(&mut self, event: &Event) -> Option> { - let before = self.notice(); + /// Apply `event`; the notifications it changed. + pub fn update(&mut self, event: &Event) -> Changes { + self.update_at(event, now_ms()) + } + + fn update_at(&mut self, event: &Event, now_ms: u64) -> Changes { + let (voice, screen) = (self.notice(), self.screen()); match event { Event::State { session, state } => { let s = self.sessions.entry(*session).or_default(); + s.since_ms = match state.voice { + VoiceState::Connected => s.since_ms.or(Some(now_ms)), + _ => None, + }; s.voice = state.voice; s.muted = state.input_muted; + s.deafened = state.output_muted; + s.own_channel = state.own_channel; } Event::ServerInfo { session, name, .. } => { self.sessions.entry(*session).or_default().name = Some(name.clone()); } - _ => return None, + Event::Presence { session, presence } => { + self.sessions.entry(*session).or_default().presence = presence.clone(); + } + Event::StreamState { session, state } => { + let s = self.sessions.entry(*session).or_default(); + s.live = matches!(state, StreamState::Live { .. }); + if !s.live { + s.watching = 0; + } + } + Event::StreamViewers { session, viewers } => { + self.sessions.entry(*session).or_default().watching = connected(viewers); + } + _ => return Changes::default(), + } + let (voice_after, screen_after) = (self.notice(), self.screen()); + Changes { + voice: (voice_after != voice).then_some(voice_after), + screen: (screen_after != screen).then_some(screen_after), } - let after = self.notice(); - (after != before).then_some(after) } fn active(&self) -> impl Iterator { @@ -58,49 +142,101 @@ impl Foreground { self.active().map(|(id, _)| *id).collect() } - /// The notification, `None` without voice. + /// The voice notification, `None` without voice. pub fn notice(&self) -> Option { let active: Vec<&Session> = self.active().map(|(_, s)| s).collect(); - if active.is_empty() { - return None; - } - let names: Vec<&str> = - active.iter().map(|s| s.name.as_deref().unwrap_or("a server")).collect(); - let names = names.join(", "); - let text = if active.iter().all(|s| s.voice == VoiceState::Connecting) { - format!("Connecting to {names}") - } else { - format!("In voice on {names}") + let connecting = active.iter().all(|s| s.voice == VoiceState::Connecting); + let (title, text) = match active.as_slice() { + [] => return None, + [one] if connecting => ("Connecting…".to_owned(), one.name().to_owned()), + [one] => match one.channel() { + Some((channel, 1)) => (channel.to_owned(), format!("{} · just you", one.name())), + Some((channel, n)) => { + (channel.to_owned(), format!("{} · {n} in voice", one.name())) + } + None => ("In voice".to_owned(), one.name().to_owned()), + }, + several => ( + format!("In voice on {} servers", several.len()), + several.iter().map(|s| s.name()).collect::>().join(", "), + ), }; - Some(VoiceNotice { text, muted: active.iter().all(|s| s.muted) }) + Some(VoiceNotice { + title, + text, + muted: active.iter().all(|s| s.muted), + deafened: active.iter().all(|s| s.deafened), + since_ms: active.iter().filter_map(|s| s.since_ms).min().unwrap_or(0), + }) } + + /// The screen-sharing notification while our stream is live. + pub fn screen(&self) -> Option { + let s = self.sessions.values().find(|s| s.live)?; + let title = match s.channel() { + Some((channel, _)) => format!("Live in {channel}"), + None => "Live".to_owned(), + }; + let text = match s.watching { + 0 => s.name().to_owned(), + 1 => format!("{} · 1 watching", s.name()), + n => format!("{} · {n} watching", s.name()), + }; + Some(ScreenNotice { title, text }) + } +} + +fn connected(viewers: &[ViewerInfo]) -> usize { + viewers.iter().filter(|v| v.state == ViewerState::Connected).count() } #[cfg(test)] mod tests { use voelin_core::SessionState; - use voelin_model::{Capabilities, ServerFlavor}; + use voelin_core::stream::EndReason; + use voelin_model::{Capabilities, ChannelInfo, ClientInfo, ServerFlavor}; use super::*; fn voice(session: SessionId, voice: VoiceState, input_muted: bool) -> Event { Event::State { session, - state: SessionState { voice, input_muted, ..SessionState::default() }, + state: SessionState { + voice, + input_muted, + own_channel: Some(2), + ..SessionState::default() + }, } } - fn notice(text: &str, muted: bool) -> Option> { - Some(Some(VoiceNotice { text: text.into(), muted })) + fn notice(title: &str, text: &str, muted: bool, since_ms: u64) -> Option> { + Some(Some(VoiceNotice { + title: title.into(), + text: text.into(), + muted, + deafened: false, + since_ms, + })) + } + + fn presence(people: u16) -> Event { + let mut p = Presence::default(); + p.channels + .insert(2, ChannelInfo { id: 2, name: "Chill Zone".into(), ..Default::default() }); + for id in 1..=people { + p.clients.insert(id, ClientInfo { id, channel: 2, ..Default::default() }); + } + Event::Presence { session: 1, presence: Arc::new(p) } } #[test] - fn service_follows_voice_connections() { + fn the_voice_service_follows_voice_connections() { let mut fg = Foreground::default(); - assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, false)), None); + assert_eq!(fg.update_at(&voice(1, VoiceState::Disconnected, false), 5).voice, None); assert_eq!( - fg.update(&voice(1, VoiceState::Connecting, false)), - notice("Connecting to a server", false) + fg.update_at(&voice(1, VoiceState::Connecting, false), 5).voice, + notice("Connecting…", "a server", false, 0) ); let info = Event::ServerInfo { session: 1, @@ -108,25 +244,93 @@ mod tests { flavor: ServerFlavor::Unknown(String::new()), capabilities: Capabilities::default(), }; - assert_eq!(fg.update(&info), notice("Connecting to Home", false)); + assert_eq!(fg.update_at(&info, 6).voice, notice("Connecting…", "Home", false, 0)); assert_eq!( - fg.update(&voice(1, VoiceState::Connected, false)), - notice("In voice on Home", false) + fg.update_at(&voice(1, VoiceState::Connected, false), 7).voice, + notice("In voice", "Home", false, 7) ); - assert_eq!(fg.update(&voice(1, VoiceState::Connected, false)), None, "no change"); + // The channel and its people, once presence knows them. assert_eq!( - fg.update(&voice(1, VoiceState::Connected, true)), - notice("In voice on Home", true) + fg.update_at(&presence(3), 8).voice, + notice("Chill Zone", "Home · 3 in voice", false, 7) ); - // A second session that is not muted: the action mutes both. assert_eq!( - fg.update(&voice(2, VoiceState::Connecting, false)), - notice("In voice on Home, a server", false) + fg.update_at(&presence(1), 8).voice, + notice("Chill Zone", "Home · just you", false, 7) + ); + assert_eq!( + fg.update_at(&voice(1, VoiceState::Connected, false), 9).voice, + None, + "no change" + ); + assert_eq!( + fg.update_at(&voice(1, VoiceState::Connected, true), 9).voice, + notice("Chill Zone", "Home · just you", true, 7) + ); + // A second session that is not muted: the action mutes both, and + // the time counts from the first connection. + assert_eq!( + fg.update_at(&voice(2, VoiceState::Connected, false), 20).voice, + notice("In voice on 2 servers", "Home, a server", false, 7) ); assert_eq!(fg.voice_sessions(), [1, 2]); - assert_eq!(fg.update(&Event::Error { session: 1, message: "x".into() }), None); - fg.update(&voice(2, VoiceState::Disconnected, false)); - assert_eq!(fg.update(&voice(1, VoiceState::Disconnected, true)), Some(None)); + assert_eq!( + fg.update(&Event::Error { session: 1, message: "x".into() }), + Changes::default() + ); + fg.update_at(&voice(2, VoiceState::Disconnected, false), 30); + assert_eq!(fg.update_at(&voice(1, VoiceState::Disconnected, true), 30).voice, Some(None)); assert!(fg.voice_sessions().is_empty()); } + + #[test] + fn deafen_needs_every_session_deafened() { + let mut fg = Foreground::default(); + let deaf = |session, output_muted| Event::State { + session, + state: SessionState { + voice: VoiceState::Connected, + output_muted, + ..Default::default() + }, + }; + fg.update_at(&deaf(1, true), 1); + assert!(fg.notice().unwrap().deafened); + fg.update_at(&deaf(2, false), 1); + assert!(!fg.notice().unwrap().deafened); + } + + #[test] + fn the_screen_notice_says_where_we_are_live() { + let mut fg = Foreground::default(); + fg.update_at(&voice(1, VoiceState::Connected, false), 1); + fg.update_at(&presence(2), 1); + assert_eq!(fg.screen(), None); + // `StreamState::Live` carries a sink only the engine makes. + fg.sessions.get_mut(&1).unwrap().live = true; + let screen = |title: &str, text: &str| { + Some(Some(ScreenNotice { title: title.into(), text: text.into() })) + }; + assert_eq!(fg.screen(), screen("Live in Chill Zone", "a server").flatten()); + let viewer = |client, state| ViewerInfo { + client: tsclientlib::ClientId(client), + state, + message: String::new(), + layer: None, + estimate: None, + srtp_profile: None, + codec: None, + }; + let viewers = Event::StreamViewers { + session: 1, + viewers: vec![viewer(2, ViewerState::Connected), viewer(3, ViewerState::Requested)], + }; + assert_eq!( + fg.update_at(&viewers, 3).screen, + screen("Live in Chill Zone", "a server · 1 watching") + ); + let ended = + Event::StreamState { session: 1, state: StreamState::Ended(EndReason::Stopped) }; + assert_eq!(fg.update_at(&ended, 4).screen, Some(None)); + } } diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 07a07a6..70a2d05 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -621,6 +621,8 @@ pub fn run(options: RunOptions) -> Result<()> { }); let _dev = crate::dev::start(&ui, &switches); + // What the platform asked for before the window ran. + crate::inbox::take(); ui.run()?; // With our own engine, leave servers properly, so no ghost client stays diff --git a/crates/voelin-ui/src/inbox.rs b/crates/voelin-ui/src/inbox.rs new file mode 100644 index 0000000..b4deb32 --- /dev/null +++ b/crates/voelin-ui/src/inbox.rs @@ -0,0 +1,43 @@ +//! Requests from the platform around the window: on Android a tapped +//! notification. They can come from any thread and before the window runs; +//! [`request`] keeps them until the window takes them on its thread. + +use std::sync::{Mutex, PoisonError}; + +use slint::ComponentHandle; + +use crate::app::{Nav, Page, with_app}; + +/// What the platform asks the window to do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Request { + /// Show the voice channel we are in (the phone's voice screen). + ShowVoice, +} + +static PENDING: Mutex> = Mutex::new(Vec::new()); + +/// Hand `request` to the window: at once if it runs, else when it starts. +pub fn request(request: Request) { + PENDING.lock().unwrap_or_else(PoisonError::into_inner).push(request); + // Fails without an event loop yet; `run` takes them then. + let _ = slint::invoke_from_event_loop(take); +} + +/// Handle what is pending, on the window's thread; kept while there is no +/// window. +pub(crate) fn take() { + let Some(ui) = with_app(|app| app.ui.upgrade()).flatten() else { return }; + let requests = std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)); + // Not inside `with_app`: navigating calls back into Rust, which borrows + // the app again. + let nav = ui.global::