diff --git a/Cargo.lock b/Cargo.lock index 20a99ec..e8ebbac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8767,13 +8767,17 @@ dependencies = [ "chrono", "dirs", "png", + "serde", + "serde_json", "slint", "slint-build", "tokio", "tracing", "tracing-subscriber", + "tsc-audio", "tsc-core", "tsc-model", + "tsc-platform", "tsc-query", "tsc-store", "tsclientlib", diff --git a/crates/tsc-core/src/lib.rs b/crates/tsc-core/src/lib.rs index 2a9ba08..74daa13 100644 --- a/crates/tsc-core/src/lib.rs +++ b/crates/tsc-core/src/lib.rs @@ -209,6 +209,8 @@ pub struct SessionState { pub presence_source: Option, /// Our own channel while voice-connected. pub own_channel: Option, + /// Our own client id while voice-connected. + pub own_client: Option, pub input_muted: bool, pub output_muted: bool, pub transmitting: bool, diff --git a/crates/tsc-core/src/session.rs b/crates/tsc-core/src/session.rs index 4e4afd7..0702bb9 100644 --- a/crates/tsc-core/src/session.rs +++ b/crates/tsc-core/src/session.rs @@ -433,6 +433,7 @@ impl Session { match e { VoiceEvent::Connected { name, flavor, own_client } => { self.state.voice = VoiceState::Connected; + self.state.own_client = Some(own_client); self.emit_state(); let capabilities = flavor.capabilities(); if capabilities.streams @@ -501,6 +502,7 @@ impl Session { self.audio = None; self.state.voice = VoiceState::Disconnected; self.state.own_channel = None; + self.state.own_client = None; self.emit_state(); if let Some(reason) = reason { self.error(format!("voice: {reason}")); diff --git a/crates/tsc-ui/Cargo.toml b/crates/tsc-ui/Cargo.toml index d053477..449be11 100644 --- a/crates/tsc-ui/Cargo.toml +++ b/crates/tsc-ui/Cargo.toml @@ -16,21 +16,33 @@ path = "src/lib.rs" name = "tsc-desktop" path = "src/main.rs" +[features] +default = ["media"] +# Sharing the screen and decoding watched streams (tsc-core's media +# pipeline: libvpx, X11 / PipeWire capture). Stream audio works without it. +media = ["tsc-core/media"] + [dependencies] anyhow = "1.0.104" chrono = { version = "0.4.45", default-features = false, features = ["clock"] } dirs = "6" png = "0.18" +serde = { version = "1", features = ["derive"] } slint = { version = "1.18", features = ["renderer-software"] } tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "time", "sync"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } -tsc-core = { path = "../tsc-core" } +tsc-audio = { path = "../tsc-audio" } +tsc-core = { path = "../tsc-core", default-features = false, features = ["audio-device"] } tsc-model = { path = "../tsc-model" } +tsc-platform = { path = "../tsc-platform" } tsc-query = { path = "../tsc-query" } tsc-store = { path = "../tsc-store", features = ["keyring"] } tsclientlib = { path = "../proto/tsclientlib" } +[dev-dependencies] +serde_json = "1" + [build-dependencies] slint-build = "1.18" diff --git a/crates/tsc-ui/src/app.rs b/crates/tsc-ui/src/app.rs index 1a10ac8..a0d90f0 100644 --- a/crates/tsc-ui/src/app.rs +++ b/crates/tsc-ui/src/app.rs @@ -1,20 +1,36 @@ //! Application state on the UI thread, wired to the engine. +//! +//! Streams (the streams panel, sharing, the viewer) are in `streams.rs`, +//! the settings page's data in `settings.rs`. use std::cell::RefCell; use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; use std::rc::Rc; use std::sync::Arc; +use std::time::Duration; use anyhow::{Context, Result}; use slint::{ComponentHandle, ModelRc, SharedString, VecModel}; use tokio::runtime::Runtime; use tracing::warn; +use tsc_core::stream::StreamInfo; use tsc_core::{ - Command, Engine, Event, ObserveState, SessionState, Source, VoiceOptions, VoiceState, + AudioSettings, Command, Engine, Event, ObserveState, SessionState, Source, VoiceOptions, + VoiceState, }; -use tsc_model::{ChannelId, ChatMessage, ChatTarget, Presence, TreeRow, tree_rows}; +use tsc_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence, TreeRow, tree_rows}; +use tsc_platform::{crash, notices}; use tsc_store::{Bookmark, MemorySecrets, QueryConfig, QueryTransport, Secrets, Store}; +use crate::hotkey::GlobalPtt; +use crate::settings::{ + self, AUDIO_KEY, CLIENT_PLAYBACK_KEY, ClientPlayback, ClientPlaybackMap, DeviceChoices, UI_KEY, + UiSettings, +}; +use crate::streams::{Share, Watch}; +use crate::video::Video; + slint::include_modules!(); /// Secrets in the OS keyring, or in memory when there is none (headless @@ -54,21 +70,27 @@ struct Tab { } /// What we know about one server session. -struct SessionView { - state: SessionState, - presence: Arc, +pub(crate) struct SessionView { + pub state: SessionState, + pub capabilities: Capabilities, + pub presence: Arc, collapsed: HashSet, talking: HashSet, tabs: Vec, current_tab: usize, /// The own channel's tab was focused for this voice connection. focused_own_channel: bool, + /// The streams in our channel (TeamSpeak 6). + pub streams: Vec, + /// Clients whose stored volume was sent for this voice connection. + applied_playback: HashSet, } impl Default for SessionView { fn default() -> Self { Self { state: SessionState::default(), + capabilities: Capabilities::default(), presence: Arc::default(), collapsed: HashSet::new(), talking: HashSet::new(), @@ -80,30 +102,79 @@ impl Default for SessionView { }], current_tab: 0, focused_own_channel: false, + streams: Vec::new(), + applied_playback: HashSet::new(), } } } -struct App { - ui: slint::Weak, +impl SessionView { + /// Streams can be watched and shared: TeamSpeak 6, connected with voice. + pub fn streams_available(&self) -> bool { + self.capabilities.streams && self.state.voice == VoiceState::Connected + } + + /// A client's nickname, or its id. + pub fn nickname(&self, client: u16) -> String { + self.presence + .clients + .get(&client) + .map_or_else(|| format!("client {client}"), |c| c.nickname.clone()) + } +} + +pub(crate) struct App { + pub ui: slint::Weak, store: Store, secrets: Box, - engine: Engine, + pub engine: Engine, identity: tsclientlib::Identity, bookmarks: Vec, - current: Option, - sessions: HashMap, + pub current: Option, + pub sessions: HashMap, status: String, + pub settings: UiSettings, + audio: AudioSettings, + /// Audio settings changed since they were last stored. + audio_dirty: bool, + inputs: DeviceChoices, + outputs: DeviceChoices, + playback: ClientPlaybackMap, + /// The client in the volume dialog: session, client id, unique id. + playback_dialog: Option<(i64, u16, Option)>, + mic_test: bool, + ptt: GlobalPtt, + pub video: Video, + /// Our stream. + pub share: Option, + /// The capture for a share is being started. + pub share_busy: bool, + pub share_error: String, + /// The stream in the viewer. + pub watch: Option, + /// Stream volume in percent, kept between streams. + pub stream_volume: f32, + /// `TSC_DEMO_STREAM`: the viewer shows a local test stream. + pub demo: bool, + /// The notices are in the About page's model. + notices_loaded: bool, } thread_local! { static APP: RefCell> = const { RefCell::new(None) }; } -fn with_app(f: impl FnOnce(&mut App) -> R) -> Option { +pub(crate) fn with_app(f: impl FnOnce(&mut App) -> R) -> Option { APP.with(|app| app.borrow_mut().as_mut().map(f)) } +/// Run `f` on the app from another thread, on the UI thread. +pub(crate) fn later(f: impl FnOnce(&mut App) + Send + 'static) { + let _ = slint::invoke_from_event_loop(move || { + with_app(f); + }); +} + /// Start options for [`run`]. #[derive(Clone, Debug, Default)] pub struct RunOptions { @@ -115,13 +186,19 @@ pub struct RunOptions { /// Run the app on the current thread until the window closes. The Slint /// platform must be set up before (the default backend on desktop). pub fn run(options: RunOptions) -> Result<()> { + // Crash reports: the hook first, recording once the setting is known. + crash::set_app_version(env!("CARGO_PKG_VERSION")); + crash::install(crash::default_dir(), false); let runtime = Runtime::new()?; let engine = runtime.block_on(async { Engine::start() }); // Development switches: TSC_DATA_DIR isolates the database, // TSC_AUTOCONNECT=voice|observe connects the first bookmark on start, - // TSC_SCREENSHOT= saves the window after TSC_SCREENSHOT_DELAY seconds and exits. - let dir = match (options.data_dir, std::env::var_os("TSC_DATA_DIR")) { + // TSC_SCREENSHOT= saves the window after TSC_SCREENSHOT_DELAY seconds and exits, + // TSC_DEMO_STREAM=1 shows a local test stream in the viewer, + // TSC_OPEN=share|settings opens that dialog on start, TSC_AUTOWATCH=1 watches the + // first stream that shows up. + let dir: PathBuf = match (options.data_dir, std::env::var_os("TSC_DATA_DIR")) { (Some(dir), _) => dir, (None, Some(dir)) => dir.into(), (None, None) => dirs::data_dir().unwrap_or_else(|| ".".into()).join("tsc"), @@ -137,9 +214,31 @@ pub fn run(options: RunOptions) -> Result<()> { identity } }; + let settings: UiSettings = store.setting(UI_KEY).ok().flatten().unwrap_or_default(); + crash::set_enabled(settings.crash_reports); + crash::test_crash_if_requested(); + let audio: AudioSettings = store.setting(AUDIO_KEY).ok().flatten().unwrap_or_default(); + let playback: ClientPlaybackMap = + store.setting(CLIENT_PLAYBACK_KEY).ok().flatten().unwrap_or_default(); + engine.send(Command::SetAudioSettings(Box::new(audio.clone()))); let ui = MainWindow::new()?; + // Wayland and X11 find the desktop file (and icon) by this id. + #[cfg(not(target_os = "android"))] + if let Err(e) = slint::set_xdg_app_id(tsc_platform::APP_ID) { + warn!("cannot set the app id: {e}"); + } let bookmarks = store.bookmarks()?; + let ptt = GlobalPtt::start( + &runtime, + |status| later(move |app| app.set_ptt_status(status)), + |on| later(move |app| app.command(|session| Command::SetTransmitting { session, on })), + ); + if settings.global_ptt { + ptt.set(Some(settings.ptt_key.clone())); + } + let video = Video::new(&dir, settings.openh264); + let demo = std::env::var("TSC_DEMO_STREAM").is_ok_and(|v| v == "1"); let app = App { ui: ui.as_weak(), store, @@ -153,26 +252,51 @@ pub fn run(options: RunOptions) -> Result<()> { bookmarks, sessions: HashMap::new(), status: "Ready".into(), + settings, + audio, + audio_dirty: false, + inputs: DeviceChoices::default(), + outputs: DeviceChoices::default(), + playback, + playback_dialog: None, + mic_test: false, + ptt, + video, + share: None, + share_busy: false, + share_error: String::new(), + watch: None, + stream_volume: 100.0, + demo, + notices_loaded: false, }; APP.with(|a| *a.borrow_mut() = Some(app)); wire_callbacks(&ui); - with_app(|app| app.refresh_all()); + with_app(|app| { + app.refresh_all(); + app.refresh_settings_flags(); + app.refresh_crash_notice(); + if app.demo { + app.start_demo(); + } + }); // Engine events -> UI thread. let mut events = engine.subscribe(); runtime.spawn(async move { loop { match events.recv().await { - Ok(event) => { - let _ = slint::invoke_from_event_loop(move || { - with_app(|app| app.handle_event(event)); - }); - } + Ok(event) => later(move |app| app.handle_event(event)), Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, Err(_) => break, } } }); + // Once a second: stream statistics, stored settings. + let ticker = slint::Timer::default(); + ticker.start(slint::TimerMode::Repeated, Duration::from_secs(1), || { + with_app(|app| app.tick()); + }); match std::env::var("TSC_AUTOCONNECT").as_deref() { Ok("voice") => { @@ -183,29 +307,46 @@ pub fn run(options: RunOptions) -> Result<()> { } _ => {} } + match std::env::var("TSC_OPEN").as_deref() { + Ok("share") => ui.invoke_open_share_dialog(), + Ok("settings") => { + with_app(|app| app.open_settings()); + ui.set_settings_open(true); + } + _ => {} + } let _screenshot_timer = std::env::var_os("TSC_SCREENSHOT").map(|path| { let delay = std::env::var("TSC_SCREENSHOT_DELAY").ok().and_then(|d| d.parse().ok()).unwrap_or(4); let weak = ui.as_weak(); let timer = slint::Timer::default(); - timer.start( - slint::TimerMode::SingleShot, - std::time::Duration::from_secs(delay), - move || { - if let Some(ui) = weak.upgrade() { - if let Err(e) = save_screenshot(&ui, std::path::Path::new(&path)) { - eprintln!("screenshot failed: {e}"); - } - let _ = ui.hide(); + timer.start(slint::TimerMode::SingleShot, Duration::from_secs(delay), move || { + if let Some(ui) = weak.upgrade() { + if let Err(e) = save_screenshot(&ui, std::path::Path::new(&path)) { + eprintln!("screenshot failed: {e}"); } - }, - ); + let _ = ui.hide(); + } + }); timer }); ui.run()?; + // Leave servers properly, so no ghost client stays behind until it times out. + let open = with_app(|app| { + app.save_audio(); + app.watch = None; + app.share = None; + for id in app.sessions.keys() { + app.engine.send(Command::CloseSession { session: *id as u64 }); + } + !app.sessions.is_empty() + }); APP.with(|a| a.borrow_mut().take()); - runtime.shutdown_timeout(std::time::Duration::from_secs(2)); + if open == Some(true) { + runtime.block_on(async { tokio::time::sleep(Duration::from_millis(500)).await }); + } + runtime.shutdown_timeout(Duration::from_secs(2)); Ok(()) } @@ -282,6 +423,112 @@ fn wire_callbacks(ui: &MainWindow) { bridge.on_delete_bookmark(|id| { with_app(|app| app.delete_bookmark(id as i64)); }); + + // Streams. + bridge.on_open_share(|| with_app(|app| app.open_share()).unwrap_or_default()); + bridge.on_start_share(|form| { + with_app(|app| app.start_share(form)); + }); + bridge.on_stop_share(|| { + with_app(|app| app.stop_share()); + }); + bridge.on_respond_viewer(|viewer, accept| { + with_app(|app| app.respond_viewer(viewer as u16, accept)); + }); + bridge.on_kick_viewer(|viewer| { + with_app(|app| app.kick_viewer(viewer as u16)); + }); + bridge.on_watch_stream(|id| { + with_app(|app| app.watch_stream(id.to_string())); + }); + bridge.on_show_viewer(|| { + with_app(|app| app.show_viewer(true)); + }); + bridge.on_hide_viewer(|| { + with_app(|app| app.show_viewer(false)); + }); + bridge.on_leave_stream(|| { + with_app(|app| app.leave_stream()); + }); + bridge.on_set_stream_volume(|volume| { + with_app(|app| app.set_stream_volume(volume)); + }); + bridge.on_toggle_fullscreen(|| { + with_app(|app| app.toggle_fullscreen()); + }); + + // Settings. + bridge.on_open_settings(|| { + with_app(|app| app.open_settings()); + }); + bridge.on_close_settings(|| { + with_app(|app| app.close_settings()); + }); + bridge.on_audio_changed(|form| { + with_app(|app| app.audio_changed(&form)); + }); + bridge.on_toggle_mic_test(|| { + with_app(|app| app.set_mic_test(!app.mic_test)); + }); + bridge.on_apply_ptt(|enabled, key| { + with_app(|app| app.apply_ptt(enabled, key.to_string())); + }); + bridge.on_set_h264(|enabled| { + with_app(|app| app.set_h264(enabled)); + }); + bridge.on_download_h264(|| { + with_app(|app| app.download_h264()); + }); + bridge.on_open_client(|id| with_app(|app| app.open_client(id as u16)).unwrap_or(false)); + bridge.on_client_audio_changed(|form| { + with_app(|app| app.client_playback_changed(&form)); + }); + + // Crash reports and notices. + bridge.on_set_crash_reports(|enabled| { + with_app(|app| app.set_crash_reports(enabled)); + }); + bridge.on_open_crash_folder(|| { + with_app(|app| { + let result = crash::dir().ok_or_else(|| "no crash report folder".to_owned()); + if let Err(e) = result.and_then(|dir| open_path(&dir).map_err(|e| e.to_string())) { + app.set_status(format!("Cannot open the crash report folder: {e}")); + } + }); + }); + bridge.on_delete_crash_reports(|| { + with_app(|app| { + match crash::clear() { + Ok(n) => app.set_status(format!("Deleted {n} crash reports")), + Err(e) => app.set_status(format!("Cannot delete the crash reports: {e}")), + } + app.refresh_crash_notice(); + }); + }); + bridge.on_dismiss_crash_notice(|| { + with_app(|app| { + if let Some(ui) = app.ui.upgrade() { + ui.global::().set_crash_notice(SharedString::new()); + } + }); + }); + bridge.on_open_about(|| { + with_app(|app| app.load_notices()); + }); +} + +/// Open a file or folder with the desktop's default application. +fn open_path(path: &Path) -> std::io::Result<()> { + #[cfg(windows)] + let mut command = std::process::Command::new("explorer"); + #[cfg(target_os = "macos")] + let mut command = std::process::Command::new("open"); + #[cfg(not(any(windows, target_os = "macos")))] + let mut command = std::process::Command::new("xdg-open"); + let mut child = command.arg(path).spawn()?; + // Reap it without blocking the UI. + std::thread::spawn(move || child.wait()); + Ok(()) } fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> { @@ -300,7 +547,7 @@ fn time_of(ts_ms: i64) -> String { .unwrap_or_default() } -fn model(items: Vec) -> ModelRc { +pub(crate) fn model(items: Vec) -> ModelRc { ModelRc::from(Rc::new(VecModel::from(items))) } @@ -310,23 +557,33 @@ impl App { Some(self.sessions.entry(id).or_default()) } - fn bookmark(&self, id: i64) -> Option<&Bookmark> { + pub fn view(&self) -> Option<&SessionView> { + self.current.and_then(|id| self.sessions.get(&id)) + } + + pub fn bookmark(&self, id: i64) -> Option<&Bookmark> { self.bookmarks.iter().find(|b| b.id == id) } - fn command(&self, f: impl FnOnce(u64) -> Command) { + pub fn command(&self, f: impl FnOnce(u64) -> Command) { if let Some(id) = self.current { self.engine.send(f(id as u64)); } } - fn set_status(&mut self, text: impl Into) { + pub fn set_status(&mut self, text: impl Into) { self.status = text.into(); if let Some(ui) = self.ui.upgrade() { ui.global::().set_status_text(self.status.clone().into()); } } + pub fn store_settings(&self) { + if let Err(e) = self.store.set_setting(UI_KEY, &self.settings) { + warn!(%e, "could not store settings"); + } + } + fn connect_voice(&mut self) { let Some(b) = self.current.and_then(|id| self.bookmark(id)).cloned() else { return }; let mut options = VoiceOptions::new(&b.address, &b.nickname); @@ -334,6 +591,7 @@ impl App { options.server_password = self.secrets.get(&b.server_password_key()).ok().flatten(); options.channel = b.default_channel.clone(); options.audio = true; + options.stream_peer = self.video.peer_config(options.stream_peer); self.engine .send(Command::ConnectVoice { session: b.id as u64, options: Box::new(options) }); self.set_status(format!("Connecting to {}…", b.address)); @@ -556,6 +814,10 @@ impl App { if state.voice != VoiceState::Connected { view.focused_own_channel = false; } + if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected { + // A new connection: volumes are sent again. + view.applied_playback.clear(); + } let focus = !view.focused_own_channel; if state.voice == VoiceState::Connected && was_voice != VoiceState::Connected { self.set_status("Connected"); @@ -570,8 +832,10 @@ impl App { } self.refresh_servers(); self.refresh_toolbar(); + self.refresh_streams(); } - Event::ServerInfo { session, name, flavor, .. } => { + Event::ServerInfo { session, name, flavor, capabilities } => { + self.sessions.entry(session as i64).or_default().capabilities = capabilities; if self.current == Some(session as i64) { let kind = match flavor { tsc_model::ServerFlavor::Ts3(v) => format!("TeamSpeak 3 {v}"), @@ -580,12 +844,15 @@ impl App { }; self.set_status(format!("Connected to {name} ({kind})")); } + self.refresh_streams(); } Event::Presence { session, presence } => { self.sessions.entry(session as i64).or_default().presence = presence; + self.apply_client_playback(session as i64); if self.current == Some(session as i64) { self.refresh_tree(); self.refresh_chat(); + self.refresh_streams(); } } Event::Talking { session, client, talking } => { @@ -599,10 +866,23 @@ impl App { self.refresh_tree(); } } + Event::InputLevel { session, level_db, sending } => { + let shown = match session { + Some(s) => self.current == Some(s as i64), + None => self.mic_test, + }; + if shown && let Some(ui) = self.ui.upgrade() { + let bridge = ui.global::(); + bridge.set_input_level(level_db); + bridge.set_input_sending(sending); + } + } + Event::MicrophoneTestError { message } => { + self.set_status(format!("Microphone test: {message}")) + } Event::Chat { session, message } => self.add_message(session as i64, message), Event::Error { message, .. } => self.set_status(message), - // Stream events: the streams panel is not wired yet. - _ => {} + event => self.stream_event(event), } } @@ -648,11 +928,20 @@ impl App { } } + /// Once a second. + fn tick(&mut self) { + self.tick_streams(); + if self.audio_dirty { + self.save_audio(); + } + } + fn refresh_all(&mut self) { self.refresh_servers(); self.refresh_toolbar(); self.refresh_tree(); self.refresh_chat(); + self.refresh_streams(); } fn refresh_servers(&self) { @@ -685,11 +974,7 @@ impl App { let Some(ui) = self.ui.upgrade() else { return }; let bridge = ui.global::(); let bookmark = self.current.and_then(|id| self.bookmark(id)); - let state = self - .current - .and_then(|id| self.sessions.get(&id)) - .map(|v| v.state.clone()) - .unwrap_or_default(); + let state = self.view().map(|v| v.state.clone()).unwrap_or_default(); bridge.set_server_title( bookmark.map_or("No server selected".into(), |b| b.name.clone()).into(), ); @@ -712,11 +997,15 @@ impl App { .into(), ); bridge.set_status_text(self.status.clone().into()); + if state.voice != VoiceState::Connected { + bridge.set_input_level(-100.0); + bridge.set_input_sending(false); + } } fn refresh_tree(&self) { let Some(ui) = self.ui.upgrade() else { return }; - let Some(view) = self.current.and_then(|id| self.sessions.get(&id)) else { + let Some(view) = self.view() else { ui.global::().set_tree(model(Vec::new())); return; }; @@ -732,21 +1021,33 @@ impl App { own: own_channel == Some(channel.id), locked: channel.has_password, collapsed: view.collapsed.contains(&channel.id), + local_volume: 100, ..Default::default() }, - TreeRow::Client { depth, client } => TreeItem { - is_channel: false, - depth: depth as i32, - id: client.id as i32, - name: client.nickname.clone().into(), - own: false, - talking: view.talking.contains(&client.id) || client.talking == Some(true), - muted: client.input_muted, - sound_off: client.output_muted, - away: client.away.is_some(), - streaming: client.streaming == Some(true), - ..Default::default() - }, + TreeRow::Client { depth, client } => { + let playback = client + .uid + .as_ref() + .and_then(|uid| self.playback.get(uid)) + .copied() + .unwrap_or_default(); + TreeItem { + is_channel: false, + depth: depth as i32, + id: client.id as i32, + name: client.nickname.clone().into(), + own: false, + talking: view.talking.contains(&client.id) || client.talking == Some(true), + muted: client.input_muted, + sound_off: client.output_muted, + away: client.away.is_some(), + streaming: client.streaming == Some(true), + local_muted: playback.muted, + local_volume: (playback.volume * 100.0).round() as i32, + myself: view.state.own_client == Some(client.id), + ..Default::default() + } + } }) .collect(); ui.global::().set_tree(model(rows)); @@ -755,7 +1056,7 @@ impl App { fn refresh_chat(&self) { let Some(ui) = self.ui.upgrade() else { return }; let bridge = ui.global::(); - let Some(view) = self.current.and_then(|id| self.sessions.get(&id)) else { + let Some(view) = self.view() else { bridge.set_tabs(model(vec![ChatTab { title: "Server".into(), ..Default::default() }])); bridge.set_messages(model(Vec::new())); return; @@ -777,4 +1078,228 @@ impl App { bridge.set_current_tab(view.current_tab as i32); bridge.set_messages(model(view.tabs[view.current_tab].lines.clone())); } + + // Settings page. + + fn open_settings(&mut self) { + let list = |devices: tsc_audio::Result>, input: bool| { + let devices = devices.unwrap_or_else(|e| { + warn!("cannot list audio devices: {e}"); + Vec::new() + }); + devices + .into_iter() + .map(|d| { + let default = if input { d.default_input } else { d.default_output }; + (d.id, d.name, default) + }) + .collect::>() + }; + let inputs = list(tsc_audio::device::input_devices(), true); + let outputs = list(tsc_audio::device::output_devices(), false); + self.inputs = DeviceChoices::new(&inputs, self.audio.input_device.as_deref()); + self.outputs = DeviceChoices::new(&outputs, self.audio.output_device.as_deref()); + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let names = |c: &DeviceChoices| model(c.names.iter().map(SharedString::from).collect()); + bridge.set_input_devices(names(&self.inputs)); + bridge.set_output_devices(names(&self.outputs)); + bridge.set_audio(settings::audio_form(&self.audio, &self.inputs, &self.outputs)); + bridge.set_global_ptt(self.settings.global_ptt); + bridge.set_ptt_key(self.settings.ptt_key.clone().into()); + bridge.set_h264_enabled(self.settings.openh264); + self.refresh_h264(); + } + + fn close_settings(&mut self) { + self.set_mic_test(false); + self.save_audio(); + } + + fn audio_changed(&mut self, form: &AudioForm) { + let audio = settings::apply_audio_form(form, &self.audio, &self.inputs, &self.outputs); + if audio == self.audio { + return; + } + self.audio = audio; + self.audio_dirty = true; + self.engine.send(Command::SetAudioSettings(Box::new(self.audio.clone()))); + } + + fn save_audio(&mut self) { + if !self.audio_dirty { + return; + } + self.audio_dirty = false; + if let Err(e) = self.store.set_setting(AUDIO_KEY, &self.audio) { + warn!(%e, "could not store audio settings"); + } + } + + fn set_mic_test(&mut self, on: bool) { + if self.mic_test == on { + return; + } + self.mic_test = on; + self.engine.send(Command::TestMicrophone { on }); + if let Some(ui) = self.ui.upgrade() { + let bridge = ui.global::(); + bridge.set_mic_test(on); + if !on { + bridge.set_input_level(-100.0); + } + } + } + + fn apply_ptt(&mut self, enabled: bool, key: String) { + let key = key.trim().to_owned(); + self.settings.global_ptt = enabled; + if !key.is_empty() { + self.settings.ptt_key = key.clone(); + } + self.store_settings(); + self.ptt.set((enabled && !key.is_empty()).then_some(key)); + } + + fn set_ptt_status(&mut self, status: String) { + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_ptt_status(status.into()); + } + } + + fn set_h264(&mut self, enabled: bool) { + self.settings.openh264 = enabled; + self.store_settings(); + self.video.set_h264(enabled); + self.refresh_h264(); + } + + fn download_h264(&mut self) { + let runtime = self.engine.runtime().clone(); + self.video.download_h264(&runtime, |download| { + later(move |app| { + app.video.downloaded(download, app.settings.openh264); + app.refresh_h264(); + }); + }); + self.refresh_h264(); + } + + fn refresh_h264(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let (loaded, status) = self.video.h264_status(); + bridge.set_h264_loaded(loaded); + bridge.set_h264_busy(status.starts_with("Downloading")); + bridge.set_h264_status(status.into()); + } + + /// Switches the About page and the settings show. + fn refresh_settings_flags(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + bridge.set_h264_enabled(self.settings.openh264); + bridge.set_h264_attribution(notices::OPENH264_ATTRIBUTION.into()); + bridge.set_crash_reports(self.settings.crash_reports); + } + + fn set_crash_reports(&mut self, enabled: bool) { + self.settings.crash_reports = enabled; + self.store_settings(); + crash::set_enabled(enabled); + } + + /// A notice while crash reports are on disk. + fn refresh_crash_notice(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let text = match crash::pending_reports() { + Ok(reports) if !reports.is_empty() => { + let newest = &reports[reports.len() - 1]; + let saved = match reports.len() { + 1 => "1 crash report is saved".to_owned(), + n => format!("{n} crash reports are saved"), + }; + format!("The app crashed earlier ({}). {saved} on this device.", newest.summary) + } + _ => String::new(), + }; + ui.global::().set_crash_notice(text.into()); + } + + /// The third-party notices, one model entry per line. + fn load_notices(&mut self) { + if self.notices_loaded { + return; + } + let Some(ui) = self.ui.upgrade() else { return }; + let lines: Vec = notices::text().lines().map(SharedString::from).collect(); + ui.global::().set_notices(model(lines)); + self.notices_loaded = true; + } + + // Local volume and mute of clients. + + /// Fill the volume dialog for `client` of the current session. + fn open_client(&mut self, client: u16) -> bool { + let Some(id) = self.current else { return false }; + let Some(info) = self.view().and_then(|v| v.presence.clients.get(&client)).cloned() else { + return false; + }; + let playback = + info.uid.as_ref().and_then(|uid| self.playback.get(uid)).copied().unwrap_or_default(); + self.playback_dialog = Some((id, client, info.uid.clone())); + if let Some(ui) = self.ui.upgrade() { + ui.global::().set_client_audio(ClientAudio { + id: client as i32, + name: info.nickname.into(), + volume: playback.volume * 100.0, + muted: playback.muted, + }); + } + true + } + + fn client_playback_changed(&mut self, form: &ClientAudio) { + let Some((session, client, uid)) = self.playback_dialog.clone() else { return }; + let playback = + ClientPlayback { volume: (form.volume / 100.0).clamp(0.0, 4.0), muted: form.muted }; + let session = session as u64; + self.engine.send(Command::SetClientVolume { session, client, volume: playback.volume }); + self.engine.send(Command::SetClientMuted { session, client, muted: playback.muted }); + // Kept by unique id; clients without one only for this connection. + if let Some(uid) = uid { + if playback.is_default() { + self.playback.remove(&uid); + } else { + self.playback.insert(uid, playback); + } + if let Err(e) = self.store.set_setting(CLIENT_PLAYBACK_KEY, &self.playback) { + warn!(%e, "could not store client volumes"); + } + } + self.refresh_tree(); + } + + /// Send the stored volumes of clients that appeared in a voice session. + fn apply_client_playback(&mut self, session: i64) { + let Some(view) = self.sessions.get_mut(&session) else { return }; + if view.state.voice != VoiceState::Connected || view.state.presence_source != Some(Source::Voice) + { + return; + } + let presence = view.presence.clone(); + view.applied_playback.retain(|id| presence.clients.contains_key(id)); + for client in presence.clients.values() { + if !view.applied_playback.insert(client.id) { + continue; + } + let stored = client.uid.as_ref().and_then(|uid| self.playback.get(uid)); + let Some(playback) = stored else { continue }; + let (s, c) = (session as u64, client.id); + self.engine.send(Command::SetClientVolume { session: s, client: c, volume: playback.volume }); + if playback.muted { + self.engine.send(Command::SetClientMuted { session: s, client: c, muted: true }); + } + } + } } diff --git a/crates/tsc-ui/src/hotkey.rs b/crates/tsc-ui/src/hotkey.rs new file mode 100644 index 0000000..539a465 --- /dev/null +++ b/crates/tsc-ui/src/hotkey.rs @@ -0,0 +1,123 @@ +//! Global push-to-talk: a task owns the `tsc_platform::HotkeyManager` +//! (portal on Wayland, XInput2 on X11, a hook on Windows) and reports +//! presses and releases. + +use tokio::runtime::Runtime; +use tokio::sync::mpsc; + +/// Id of the push-to-talk registration (the portal remembers it). +#[cfg(not(target_os = "android"))] +const PTT_ID: &str = "push-to-talk"; + +/// Handle to the hotkey task. +pub(crate) struct GlobalPtt { + tx: mpsc::UnboundedSender>, +} + +impl GlobalPtt { + /// Start the task. `status` gets a line for the settings page, + /// `transmit` the key's state; both are called on the runtime. + pub fn start( + runtime: &Runtime, + status: impl Fn(String) + Send + 'static, + transmit: impl Fn(bool) + Send + 'static, + ) -> Self { + let (tx, rx) = mpsc::unbounded_channel(); + runtime.spawn(run(rx, status, transmit)); + Self { tx } + } + + /// Register `key` (e.g. `Ctrl+Shift+T`) instead of the current one, or + /// nothing. + pub fn set(&self, key: Option) { + let _ = self.tx.send(key); + } +} + +#[cfg(target_os = "android")] +async fn run( + mut rx: mpsc::UnboundedReceiver>, + status: impl Fn(String), + _transmit: impl Fn(bool), +) { + while let Some(key) = rx.recv().await { + if key.is_some() { + status("Global hotkeys are not available on this platform.".into()); + } + } +} + +#[cfg(not(target_os = "android"))] +async fn run( + mut rx: mpsc::UnboundedReceiver>, + status: impl Fn(String), + transmit: impl Fn(bool), +) { + use tsc_platform::{BackendKind, Hotkey, HotkeyEvent, HotkeyEvents, HotkeyManager}; + + async fn next(events: &mut Option) -> Option { + match events { + Some(events) => events.recv().await, + None => std::future::pending().await, + } + } + + let mut manager: Option = None; + let mut events: Option = None; + loop { + tokio::select! { + key = rx.recv() => { + let Some(key) = key else { break }; + events = None; + // Released: whatever was held no longer counts. + transmit(false); + if let Some(m) = &mut manager { + let _ = m.unregister(PTT_ID).await; + } + let Some(key) = key else { + status("Off.".into()); + continue; + }; + let hotkey: Hotkey = match key.parse() { + Ok(h) => h, + Err(e) => { + status(format!("{e}")); + continue; + } + }; + if manager.is_none() { + match HotkeyManager::new().await { + Ok(m) => manager = Some(m), + Err(e) => { + status(format!("Global hotkeys are not available: {e}")); + continue; + } + } + } + let Some(m) = &mut manager else { continue }; + match m.register(PTT_ID, "Push to talk", hotkey).await { + Ok(registered) => { + events = Some(registered); + status(match m.backend() { + BackendKind::Portal => format!( + "Registered with the desktop: {}", + m.trigger_description(PTT_ID).unwrap_or(key) + ), + BackendKind::X11 => format!("Active: {hotkey} (X11)"), + BackendKind::WindowsHook => format!("Active: {hotkey}"), + }); + } + Err(e) => status(format!("Could not register {key}: {e}")), + } + } + event = next(&mut events) => match event { + Some(HotkeyEvent::Pressed) => transmit(true), + Some(HotkeyEvent::Released) => transmit(false), + None => { + events = None; + status("The hotkey was removed by the desktop.".into()); + } + }, + } + } +} diff --git a/crates/tsc-ui/src/lib.rs b/crates/tsc-ui/src/lib.rs index f65782f..7edcd72 100644 --- a/crates/tsc-ui/src/lib.rs +++ b/crates/tsc-ui/src/lib.rs @@ -1,5 +1,9 @@ //! Slint user interface shared by the desktop binary and the mobile apps. mod app; +mod hotkey; +mod settings; +mod streams; +mod video; pub use app::{RunOptions, run}; diff --git a/crates/tsc-ui/src/main.rs b/crates/tsc-ui/src/main.rs index ededc93..19a9ac3 100644 --- a/crates/tsc-ui/src/main.rs +++ b/crates/tsc-ui/src/main.rs @@ -1,5 +1,9 @@ //! Desktop client. +// Release builds on Windows are GUI programs (no console window); debug +// builds keep the console for logs. +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + use anyhow::Result; use tracing_subscriber::EnvFilter; diff --git a/crates/tsc-ui/src/settings.rs b/crates/tsc-ui/src/settings.rs new file mode 100644 index 0000000..9dfb755 --- /dev/null +++ b/crates/tsc-ui/src/settings.rs @@ -0,0 +1,262 @@ +//! Settings kept in the store (besides bookmarks and identities), and their +//! conversion to and from the forms of the settings page. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use tsc_audio::process::NoiseLevel; +use tsc_core::{AudioSettings, TransmitMode}; + +use crate::app::AudioForm; + +/// Store keys. +pub const AUDIO_KEY: &str = "audio"; +pub const UI_KEY: &str = "ui"; +pub const CLIENT_PLAYBACK_KEY: &str = "client_playback"; + +/// Frame rates and bitrates (kbit/s) of the share dialog. +pub const FPS_CHOICES: [u32; 3] = [15, 30, 60]; +pub const BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000]; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct UiSettings { + /// Global push-to-talk hotkey (besides the button in the window). + pub global_ptt: bool, + /// E.g. `Ctrl+Shift+T` (`tsc_platform::Hotkey` syntax). + pub ptt_key: String, + /// H.264 through Cisco's OpenH264, downloaded on request. + pub openh264: bool, + /// The ScreenCast portal's token for the last shared screen. + pub portal_restore_token: Option, + pub share: ShareDefaults, + /// Write crash reports to disk (opt-in; never uploaded). + pub crash_reports: bool, +} + +impl Default for UiSettings { + fn default() -> Self { + Self { + global_ptt: true, + ptt_key: "Ctrl+Shift+T".into(), + openh264: false, + portal_restore_token: None, + share: ShareDefaults::default(), + crash_reports: false, + } + } +} + +/// The last choices in the share dialog. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct ShareDefaults { + pub fps_index: usize, + pub bitrate_index: usize, + pub audio: bool, + pub auto_accept: bool, +} + +impl Default for ShareDefaults { + fn default() -> Self { + Self { fps_index: 1, bitrate_index: 1, audio: true, auto_accept: false } + } +} + +/// Local playback of one client, kept by its unique id. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct ClientPlayback { + /// Linear, 1 = unchanged. + pub volume: f32, + pub muted: bool, +} + +impl Default for ClientPlayback { + fn default() -> Self { + Self { volume: 1.0, muted: false } + } +} + +impl ClientPlayback { + pub fn is_default(&self) -> bool { + *self == Self::default() + } +} + +pub type ClientPlaybackMap = BTreeMap; + +/// Audio devices as listed in the settings: the system default first. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DeviceChoices { + pub names: Vec, + /// Device ids by index; `None` for the system default. + pub ids: Vec>, +} + +impl DeviceChoices { + /// `devices` as `(id, name, is_default)`. A selected device that is not + /// connected stays in the list, so the choice survives. + pub fn new(devices: &[(String, String, bool)], selected: Option<&str>) -> Self { + let default_name = devices.iter().find(|d| d.2).map(|d| d.1.as_str()); + let mut choices = Self { + names: vec![match default_name { + Some(name) => format!("System default ({name})"), + None => "System default".into(), + }], + ids: vec![None], + }; + for (id, name, _) in devices { + choices.names.push(name.clone()); + choices.ids.push(Some(id.clone())); + } + if let Some(id) = selected + && !choices.ids.iter().any(|i| i.as_deref() == Some(id)) + { + choices.names.push(format!("{id} (not connected)")); + choices.ids.push(Some(id.to_owned())); + } + choices + } + + pub fn index_of(&self, id: Option<&str>) -> usize { + self.ids.iter().position(|i| i.as_deref() == id).unwrap_or(0) + } + + pub fn id_at(&self, index: i32) -> Option { + usize::try_from(index).ok().and_then(|i| self.ids.get(i).cloned()).flatten() + } +} + +fn noise_index(level: NoiseLevel) -> i32 { + match level { + NoiseLevel::Low => 0, + NoiseLevel::Moderate => 1, + NoiseLevel::High => 2, + NoiseLevel::VeryHigh => 3, + } +} + +fn noise_level(index: i32) -> NoiseLevel { + match index { + 0 => NoiseLevel::Low, + 2 => NoiseLevel::High, + 3 => NoiseLevel::VeryHigh, + _ => NoiseLevel::Moderate, + } +} + +/// The settings page's form for `settings`. +pub fn audio_form( + settings: &AudioSettings, + inputs: &DeviceChoices, + outputs: &DeviceChoices, +) -> AudioForm { + let p = &settings.processing; + AudioForm { + input_index: inputs.index_of(settings.input_device.as_deref()) as i32, + output_index: outputs.index_of(settings.output_device.as_deref()) as i32, + transmit: match settings.transmit { + TransmitMode::PushToTalk => 0, + TransmitMode::VoiceActivation => 1, + TransmitMode::Continuous => 2, + }, + vad_threshold: settings.vad.threshold_db, + echo_cancellation: p.echo_cancellation, + noise_suppression: p.noise_suppression, + noise_level: noise_index(p.noise_level), + auto_gain: p.auto_gain, + input_gain: p.input_gain_db, + output_volume: settings.output_volume * 100.0, + playback_buffer: settings.playback_buffer_ms as f32, + } +} + +/// `settings` changed as the form says; what the form does not show stays. +pub fn apply_audio_form( + form: &AudioForm, + settings: &AudioSettings, + inputs: &DeviceChoices, + outputs: &DeviceChoices, +) -> AudioSettings { + let mut s = settings.clone(); + s.input_device = inputs.id_at(form.input_index); + s.output_device = outputs.id_at(form.output_index); + s.transmit = match form.transmit { + 1 => TransmitMode::VoiceActivation, + 2 => TransmitMode::Continuous, + _ => TransmitMode::PushToTalk, + }; + s.vad.threshold_db = form.vad_threshold; + s.processing.echo_cancellation = form.echo_cancellation; + s.processing.noise_suppression = form.noise_suppression; + s.processing.noise_level = noise_level(form.noise_level); + s.processing.auto_gain = form.auto_gain; + s.processing.input_gain_db = form.input_gain; + s.output_volume = (form.output_volume / 100.0).clamp(0.0, 4.0); + s.playback_buffer_ms = form.playback_buffer.round().clamp(20.0, 180.0) as u32; + s +} + +#[cfg(test)] +mod tests { + use super::*; + + fn devices() -> Vec<(String, String, bool)> { + vec![ + ("alsa:hw:0,0".into(), "Built-in".into(), true), + ("alsa:hw:1,0".into(), "Headset".into(), false), + ] + } + + #[test] + fn device_choices() { + let choices = DeviceChoices::new(&devices(), None); + assert_eq!(choices.names, ["System default (Built-in)", "Built-in", "Headset"]); + assert_eq!(choices.index_of(Some("alsa:hw:1,0")), 2); + assert_eq!(choices.id_at(0), None); + assert_eq!(choices.id_at(2).as_deref(), Some("alsa:hw:1,0")); + assert_eq!(choices.id_at(9), None); + // An unplugged device stays selectable. + let choices = DeviceChoices::new(&devices(), Some("usb:mic")); + assert_eq!(choices.names.last().unwrap(), "usb:mic (not connected)"); + assert_eq!(choices.index_of(Some("usb:mic")), 3); + } + + #[test] + fn audio_form_roundtrip() { + let inputs = DeviceChoices::new(&devices(), None); + let outputs = DeviceChoices::new(&devices(), None); + let mut settings = AudioSettings { + transmit: TransmitMode::VoiceActivation, + input_device: Some("alsa:hw:1,0".into()), + output_volume: 0.5, + playback_buffer_ms: 80, + ..Default::default() + }; + settings.vad.threshold_db = -35.0; + settings.processing.noise_level = NoiseLevel::High; + settings.processing.input_gain_db = 6.0; + let form = audio_form(&settings, &inputs, &outputs); + assert_eq!((form.input_index, form.output_index, form.transmit), (2, 0, 1)); + assert_eq!(form.output_volume, 50.0); + assert_eq!(apply_audio_form(&form, &settings, &inputs, &outputs), settings); + + let form = AudioForm { transmit: 2, echo_cancellation: false, playback_buffer: 500.0, ..form }; + let changed = apply_audio_form(&form, &settings, &inputs, &outputs); + assert_eq!(changed.transmit, TransmitMode::Continuous); + assert!(!changed.processing.echo_cancellation); + assert_eq!(changed.playback_buffer_ms, 180); + } + + #[test] + fn ui_settings_defaults() { + let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap(); + assert!(parsed.openh264); + assert!(!parsed.crash_reports, "crash reports are opt-in"); + assert_eq!(parsed.ptt_key, "Ctrl+Shift+T"); + assert_eq!(parsed.share, ShareDefaults::default()); + let map: ClientPlaybackMap = + serde_json::from_str(r#"{"uid=":{"volume":0.5,"muted":false}}"#).unwrap(); + assert_eq!(map["uid="].volume, 0.5); + } +} diff --git a/crates/tsc-ui/src/streams.rs b/crates/tsc-ui/src/streams.rs new file mode 100644 index 0000000..b577692 --- /dev/null +++ b/crates/tsc-ui/src/streams.rs @@ -0,0 +1,582 @@ +//! Streams (TeamSpeak 6): the streams panel, sharing our screen and the +//! viewer. The engine runs the stream sessions; `video.rs` captures, +//! encodes and decodes. + +use slint::ComponentHandle; +use tsc_core::stream::{EndReason, LeaveReason, StreamSetup, ViewerInfo, ViewerState}; +use tsc_core::{Command, Event, StreamState, WatchState}; + +use crate::app::{ + App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model, +}; +use crate::settings::{BITRATE_CHOICES, FPS_CHOICES, ShareDefaults}; +use crate::video::{self, Capture, CaptureRequest, Decoder}; + +/// Our stream. +pub(crate) struct Share { + pub session: i64, + /// Stops capturing when dropped. + capture: Capture, + /// The server confirmed the stream. + live: bool, + viewers: Vec, + /// The capture ended by itself and the stream is being stopped. + stopping: bool, +} + +/// The stream in the viewer. +pub(crate) struct Watch { + /// `None` for the local demo stream. + session: Option, + stream_id: String, + title: String, + streamer: String, + /// Shown over the picture; empty while it plays. + status: String, + connected: bool, + ended: bool, + has_frame: bool, + /// Shown instead of the chat. + shown: bool, + decoder: Option, +} + +fn end_text(reason: &EndReason, streamer: &str) -> String { + match reason { + EndReason::Local => "You left the stream.".into(), + EndReason::Denied => format!("{streamer} did not let you watch."), + EndReason::Stopped => "The stream has ended.".into(), + EndReason::Removed(Some(LeaveReason::Kicked | LeaveReason::Banned)) => { + format!("{streamer} removed you from the stream.") + } + EndReason::Removed(_) => "You were removed from the stream.".into(), + EndReason::Failed(e) => format!("The stream failed: {e}"), + } +} + +fn share_end_text(reason: &EndReason) -> String { + match reason { + EndReason::Failed(e) => format!("Sharing failed: {e}"), + _ => "Sharing ended.".into(), + } +} + +impl App { + pub(crate) fn stream_event(&mut self, event: Event) { + match event { + Event::StreamsChanged { session, streams } => { + let view = self.sessions.entry(session as i64).or_default(); + // Development switch: watch the first stream that shows up. + let autowatch = std::env::var("TSC_AUTOWATCH").is_ok_and(|v| v == "1") + && self.watch.is_none() + && self.current == Some(session as i64); + let first = streams + .iter() + .find(|s| view.state.own_client != Some(s.streamer.0)) + .map(|s| s.id.clone()); + view.streams = streams; + self.refresh_streams(); + if autowatch && let Some(id) = first { + self.watch_stream(id); + } + } + Event::StreamState { session, state } => self.share_state(session as i64, state), + Event::StreamViewerRequest { session, viewer, .. } => { + let name = self.sessions.entry(session as i64).or_default().nickname(viewer); + self.set_status(format!("{name} wants to watch your stream")); + } + Event::StreamViewers { session, viewers } => { + if let Some(share) = self.share.as_mut().filter(|s| s.session == session as i64) { + share.viewers = viewers; + self.refresh_streams(); + } + } + Event::WatchState { session, stream_id, state } => { + self.watch_state(session as i64, &stream_id, state); + } + // Also flagged on the sink, which the encoder reads. + Event::StreamKeyframeRequest { .. } => {} + _ => {} + } + } + + fn share_state(&mut self, session: i64, state: StreamState) { + let Some(share) = self.share.as_mut().filter(|s| s.session == session) else { return }; + match state { + StreamState::Starting => {} + StreamState::Live { sink, .. } => { + share.live = true; + share.capture.attach(sink); + self.set_status("You are sharing your screen"); + } + StreamState::Ended(reason) => { + let local = reason == EndReason::Local || share.stopping; + self.share = None; + self.share_error = if local { String::new() } else { share_end_text(&reason) }; + self.set_status(if local { "You stopped sharing".into() } else { share_end_text(&reason) }); + } + } + self.refresh_streams(); + } + + fn watch_state(&mut self, session: i64, stream_id: &str, state: WatchState) { + let Some(watch) = self + .watch + .as_mut() + .filter(|w| w.session == Some(session) && w.stream_id == stream_id && !w.ended) + else { + return; + }; + match state { + WatchState::Requested => { + watch.status = format!("Waiting for {} to let you watch…", watch.streamer); + } + WatchState::Connecting => { + watch.status = format!("Connecting to {}…", watch.streamer); + } + WatchState::Connected => { + watch.connected = true; + if !watch.has_frame { + watch.status = "Waiting for the picture…".into(); + } + } + WatchState::Ended(reason) => { + watch.ended = true; + watch.decoder = None; + watch.status = end_text(&reason, &watch.streamer); + } + } + self.refresh_viewer(); + self.refresh_streams(); + } + + /// The streams panel, the share dialog's live part and the toolbar. + pub(crate) fn refresh_streams(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let view = self.view(); + let current = self.current; + let mut items: Vec = Vec::new(); + if let Some(view) = view.filter(|v| v.streams_available()) { + for s in &view.streams { + let watching = self.watch.as_ref().is_some_and(|w| { + w.session == current && w.stream_id == s.id && !w.ended + }); + items.push(StreamItem { + id: s.id.clone().into(), + name: s.name.clone().into(), + streamer: view.nickname(s.streamer.0).into(), + audio: s.audio, + watching, + own: view.state.own_client == Some(s.streamer.0), + }); + } + // Streams that started before we joined are only known by the + // streaming flag: the server does not tell their ids. + let channel = view.state.own_channel; + for c in view.presence.clients.values() { + let announced = view.streams.iter().any(|s| s.streamer.0 == c.id); + if c.streaming == Some(true) + && Some(c.channel) == channel + && !announced + && view.state.own_client != Some(c.id) + { + items.push(StreamItem { + name: c.nickname.clone().into(), + streamer: c.nickname.clone().into(), + ..StreamItem::default() + }); + } + } + } + if self.demo { + items.push(StreamItem { + id: "demo".into(), + name: "Test pattern".into(), + streamer: "local preview".into(), + audio: false, + watching: self.watch.as_ref().is_some_and(|w| w.session.is_none() && !w.ended), + own: false, + }); + } + bridge.set_streams_available(self.demo || view.is_some_and(|v| v.streams_available())); + bridge.set_streams(model(items)); + bridge.set_can_share(video::AVAILABLE); + + let share = self.share.as_ref().filter(|s| Some(s.session) == current); + let state = match share { + Some(s) if s.live => "live", + Some(_) => "starting", + None if self.share_busy => "starting", + None => "", + }; + bridge.set_share_state(state.into()); + bridge.set_share_busy(self.share_busy); + bridge.set_share_error(self.share_error.clone().into()); + let viewers: Vec = share + .map(|s| { + s.viewers + .iter() + .map(|v| ViewerItem { + client: i32::from(v.client.0), + name: view.map_or_else(String::new, |view| view.nickname(v.client.0)).into(), + state: match v.state { + ViewerState::Requested => "requested", + ViewerState::Connecting => "connecting", + ViewerState::Connected => "connected", + } + .into(), + message: v.message.clone().into(), + }) + .collect() + }) + .unwrap_or_default(); + let requests = viewers.iter().filter(|v| v.state == "requested").count(); + bridge.set_share_requests(requests as i32); + bridge.set_share_viewers(model(viewers)); + let status = match share { + Some(s) if s.live => s.capture.status(), + Some(s) => format!("Starting the stream of {}…", s.capture.source_name()), + None if self.share_busy => "Starting the capture…".into(), + None => String::new(), + }; + bridge.set_share_status(status.into()); + } + + fn refresh_viewer(&self) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + let Some(watch) = &self.watch else { + bridge.set_viewer_open(false); + bridge.set_viewer_has_frame(false); + bridge.set_viewer_frame(slint::Image::default()); + return; + }; + bridge.set_viewer_open(watch.shown && (watch.session.is_none() || watch.session == self.current)); + bridge.set_viewer_title(watch.title.clone().into()); + bridge.set_viewer_status(watch.status.clone().into()); + bridge.set_viewer_ended(watch.ended); + bridge.set_viewer_has_frame(watch.has_frame); + bridge.set_viewer_volume(self.stream_volume); + let info = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default(); + let info = [format!("by {}", watch.streamer), info] + .into_iter() + .filter(|s| !s.is_empty()) + .collect::>() + .join(" · "); + bridge.set_viewer_info(info.into()); + } + + /// Once a second: statistics, a capture that ended, decoder problems. + pub(crate) fn tick_streams(&mut self) { + if let Some(share) = &mut self.share + && share.live + && !share.stopping + && share.capture.ended() + { + share.stopping = true; + self.engine.send(Command::StopStream { session: share.session as u64 }); + } + if let Some(watch) = &mut self.watch + && watch.connected + && !watch.has_frame + && let Some(error) = watch.decoder.as_ref().and_then(Decoder::error) + { + watch.status = if error.contains("H264") || error.contains("OpenH264") { + format!("{error}. Enable H.264 in Settings → Streaming to watch this stream.") + } else { + format!("Cannot show the picture: {error}") + }; + } + if self.share.is_some() { + self.refresh_streams(); + } + if self.watch.is_some() { + self.refresh_viewer(); + } + } + + // Sharing. + + /// Fill the share dialog: sources and the last choices. + pub(crate) fn open_share(&mut self) -> ShareForm { + let test_pattern = cfg!(debug_assertions) + || self.demo + || std::env::var("TSC_TEST_PATTERN").is_ok_and(|v| v == "1"); + let sources = match self.video.sources(test_pattern) { + Ok(sources) => { + if self.share.is_none() { + self.share_error.clear(); + } + sources + } + Err(e) => { + self.share_error = e; + Vec::new() + } + }; + if let Some(ui) = self.ui.upgrade() { + let items: Vec = sources + .into_iter() + .map(|(name, detail)| SourceItem { name: name.into(), detail: detail.into() }) + .collect(); + ui.global::().set_share_sources(model(items)); + } + self.refresh_streams(); + let defaults = &self.settings.share; + let nickname = self.current.and_then(|id| self.bookmark(id)).map(|b| b.nickname.clone()); + ShareForm { + source: 0, + name: match nickname { + Some(nick) if !nick.is_empty() => format!("{nick}'s screen").into(), + _ => "Screen".into(), + }, + fps_index: defaults.fps_index.min(FPS_CHOICES.len() - 1) as i32, + bitrate_index: defaults.bitrate_index.min(BITRATE_CHOICES.len() - 1) as i32, + audio: defaults.audio, + auto_accept: defaults.auto_accept, + } + } + + pub(crate) fn start_share(&mut self, form: ShareForm) { + let Some(session) = self.current else { return }; + if self.share_busy || self.share.is_some() { + return; + } + let index = |i: i32, len: usize| usize::try_from(i).unwrap_or(0).min(len - 1); + let defaults = ShareDefaults { + fps_index: index(form.fps_index, FPS_CHOICES.len()), + bitrate_index: index(form.bitrate_index, BITRATE_CHOICES.len()), + audio: form.audio, + auto_accept: form.auto_accept, + }; + let request = CaptureRequest { + fps: FPS_CHOICES[defaults.fps_index], + bitrate_kbps: BITRATE_CHOICES[defaults.bitrate_index], + audio: form.audio, + restore_token: self.settings.portal_restore_token.clone(), + }; + let bitrate = request.bitrate_kbps; + self.settings.share = defaults; + self.store_settings(); + self.share_busy = true; + self.share_error.clear(); + self.refresh_streams(); + let setup = StreamSetup { + name: form.name.trim().to_owned(), + bitrate, + audio: form.audio, + ..StreamSetup::default() + }; + let auto_accept = form.auto_accept; + let runtime = self.engine.runtime().clone(); + let source = usize::try_from(form.source).unwrap_or(0); + self.video.start_capture(&runtime, source, request, move |result| { + later(move |app| app.capture_ready(session, setup, auto_accept, result)); + }); + } + + /// The capture started (or not): go live. + fn capture_ready( + &mut self, + session: i64, + mut setup: StreamSetup, + auto_accept: bool, + result: Result, + ) { + self.share_busy = false; + match result { + Err(e) => { + self.share_error = format!("Could not start the capture: {e}"); + } + Ok(capture) => { + if let Some(token) = capture.restore_token() + && self.settings.portal_restore_token.as_ref() != Some(&token) + { + self.settings.portal_restore_token = Some(token); + self.store_settings(); + } + if setup.audio && !capture.has_audio() { + setup.audio = false; + let reason = capture.audio_error().unwrap_or_default(); + self.set_status(format!("Sharing without sound: {reason}")); + } + self.engine.send(Command::StartStream { session: session as u64, setup, auto_accept }); + self.share = Some(Share { + session, + capture, + live: false, + viewers: Vec::new(), + stopping: false, + }); + } + } + self.refresh_streams(); + } + + pub(crate) fn stop_share(&mut self) { + if let Some(share) = &mut self.share { + share.stopping = true; + self.engine.send(Command::StopStream { session: share.session as u64 }); + } + } + + pub(crate) fn respond_viewer(&mut self, viewer: u16, accept: bool) { + if let Some(share) = &self.share { + let session = share.session as u64; + self.engine.send(Command::AcceptViewer { session, viewer, accept }); + } + } + + pub(crate) fn kick_viewer(&mut self, viewer: u16) { + if let Some(share) = &self.share { + self.engine.send(Command::KickViewer { session: share.session as u64, viewer }); + } + } + + // Watching. + + pub(crate) fn watch_stream(&mut self, stream_id: String) { + if stream_id == "demo" && self.demo { + self.start_demo(); + return; + } + let Some(session) = self.current else { return }; + let Some(view) = self.sessions.get(&session) else { return }; + let Some(info) = view.streams.iter().find(|s| s.id == stream_id) else { return }; + let streamer = view.nickname(info.streamer.0); + let title = if info.name.is_empty() { format!("{streamer}'s stream") } else { info.name.clone() }; + self.leave_stream(); + self.engine.send(Command::WatchStream { session: session as u64, stream_id: stream_id.clone() }); + if self.stream_volume != 100.0 { + self.engine.send(Command::SetStreamVolume { + session: session as u64, + stream_id: stream_id.clone(), + volume: self.stream_volume / 100.0, + }); + } + let wake = || later(|app| app.show_picture()); + let decoder = self.video.watch(&self.engine, session as u64, &stream_id, wake); + self.watch = Some(Watch { + session: Some(session), + stream_id, + title, + status: format!("Asking {streamer} to let you watch…"), + streamer, + connected: false, + ended: false, + has_frame: false, + shown: true, + decoder: Some(decoder), + }); + self.refresh_viewer(); + self.refresh_streams(); + } + + /// The local test stream in the viewer (`TSC_DEMO_STREAM`). + pub(crate) fn start_demo(&mut self) { + self.leave_stream(); + self.watch = Some(Watch { + session: None, + stream_id: "demo".into(), + title: "Test pattern".into(), + streamer: "local preview".into(), + status: "Starting the local preview…".into(), + connected: true, + ended: false, + has_frame: false, + shown: true, + decoder: None, + }); + let runtime = self.engine.runtime().clone(); + let wake = || later(|app| app.show_picture()); + self.video.demo(&runtime, wake, |result| { + later(move |app| { + let Some(watch) = app.watch.as_mut().filter(|w| w.session.is_none()) else { + return; + }; + match result { + Ok(decoder) => watch.decoder = Some(decoder), + Err(e) => watch.status = format!("The preview failed: {e}"), + } + app.refresh_viewer(); + }); + }); + self.refresh_viewer(); + self.refresh_streams(); + } + + /// A decoded picture is waiting. + fn show_picture(&mut self) { + let Some(watch) = &mut self.watch else { return }; + let Some(image) = watch.decoder.as_ref().and_then(Decoder::take_picture) else { return }; + let first = !watch.has_frame; + watch.has_frame = true; + if first { + watch.status.clear(); + } + if let Some(ui) = self.ui.upgrade() { + let bridge = ui.global::(); + bridge.set_viewer_frame(image); + if first { + self.refresh_viewer(); + } + } + } + + pub(crate) fn show_viewer(&mut self, shown: bool) { + if let Some(watch) = &mut self.watch { + watch.shown = shown; + } + if !shown { + self.set_fullscreen(false); + } + self.refresh_viewer(); + self.refresh_streams(); + } + + /// Stop watching and close the viewer. + pub(crate) fn leave_stream(&mut self) { + if let Some(watch) = self.watch.take() + && let Some(session) = watch.session + && !watch.ended + { + self.engine.send(Command::LeaveStream { + session: session as u64, + stream_id: watch.stream_id, + }); + } + self.set_fullscreen(false); + self.refresh_viewer(); + self.refresh_streams(); + } + + pub(crate) fn set_stream_volume(&mut self, percent: f32) { + self.stream_volume = percent.round().clamp(0.0, 200.0); + if let Some(watch) = &self.watch + && let Some(session) = watch.session + { + self.engine.send(Command::SetStreamVolume { + session: session as u64, + stream_id: watch.stream_id.clone(), + volume: self.stream_volume / 100.0, + }); + } + } + + pub(crate) fn toggle_fullscreen(&mut self) { + let Some(ui) = self.ui.upgrade() else { return }; + let full = !ui.global::().get_viewer_fullscreen(); + self.set_fullscreen(full); + } + + fn set_fullscreen(&self, full: bool) { + let Some(ui) = self.ui.upgrade() else { return }; + let bridge = ui.global::(); + if bridge.get_viewer_fullscreen() == full { + return; + } + bridge.set_viewer_fullscreen(full); + ui.window().set_fullscreen(full); + } +} diff --git a/crates/tsc-ui/src/video.rs b/crates/tsc-ui/src/video.rs new file mode 100644 index 0000000..a30bcb9 --- /dev/null +++ b/crates/tsc-ui/src/video.rs @@ -0,0 +1,497 @@ +//! Video of streams for the UI: capture and encoding when we share, decoding +//! into Slint images when we watch, and the optional OpenH264 library. +//! +//! Needs the `media` feature (tsc-core's media pipeline). Without it the +//! same API exists and reports that video is not available; stream audio +//! still plays (the engine does that). + +pub(crate) use imp::*; + +/// Human-readable text for a capture source size. +fn size_text(width: u32, height: u32) -> String { + if width == 0 || height == 0 { String::new() } else { format!("{width}×{height}") } +} + +#[cfg(feature = "media")] +mod imp { + use std::path::{Path, PathBuf}; + use std::sync::Arc; + + use slint::{Image, Rgba8Pixel, SharedPixelBuffer}; + use tokio::runtime::Handle; + use tsc_core::media::tsc_media::capture::SourceId; + use tsc_core::media::tsc_media::codec::h264::{self, OpenH264}; + use tsc_core::media::tsc_media::{Codecs, VideoFrame, convert}; + use tsc_core::media::{ + self, Latest, LocalPreview, Streamer, StreamerConfig, Viewer, peer_config, stream_codec, + }; + use tsc_core::stream::PeerConfig; + use tsc_core::{Engine, StreamSink}; + use tracing::warn; + + use super::size_text; + + /// Whether this build can share and decode video. + pub const AVAILABLE: bool = true; + + type Picture = SharedPixelBuffer; + + /// OpenH264 state. + enum H264 { + Off, + /// Enabled, but not downloaded yet (or the file is not a known build). + Missing(String), + Downloading, + Loaded(PathBuf), + } + + pub(crate) struct Video { + codecs: Arc, + openh264_dir: PathBuf, + h264: H264, + /// Sources of the share dialog, by index. + sources: Vec<(SourceId, String)>, + } + + impl Video { + pub fn new(data_dir: &Path, openh264: bool) -> Self { + let mut video = Self { + codecs: Arc::new(Codecs::new()), + openh264_dir: data_dir.join("openh264"), + h264: H264::Off, + sources: Vec::new(), + }; + video.set_h264(openh264); + video + } + + /// `base` with the codecs this machine can encode and decode. + pub fn peer_config(&self, base: PeerConfig) -> PeerConfig { + peer_config(&self.codecs, base) + } + + /// Whether H.264 works, and a line for the settings page. + pub fn h264_status(&self) -> (bool, String) { + match &self.h264 { + H264::Off => (false, String::new()), + H264::Missing(reason) => (false, reason.clone()), + H264::Downloading => (false, "Downloading OpenH264 from Cisco…".into()), + H264::Loaded(path) => { + (true, format!("OpenH264 {} is loaded ({}).", h264::OPENH264_VERSION, path.display())) + } + } + } + + /// Enable or disable H.264; enabling loads a library downloaded + /// earlier. Takes effect for new connections. + pub fn set_h264(&mut self, enabled: bool) { + if !enabled { + self.h264 = H264::Off; + self.codecs = Arc::new(Codecs::new()); + return; + } + if matches!(self.h264, H264::Loaded(_) | H264::Downloading) { + return; + } + match OpenH264::find_in(&self.openh264_dir) { + Ok(library) => self.loaded(library), + Err(_) => { + self.h264 = H264::Missing("OpenH264 is not downloaded yet.".into()); + } + } + } + + fn loaded(&mut self, library: OpenH264) { + self.h264 = H264::Loaded(library.path().to_owned()); + self.codecs = Arc::new(Codecs::new().with_openh264(library)); + } + + /// Download Cisco's OpenH264 (only on the user's request). `done` + /// runs on the runtime; pass its argument to [`Video::downloaded`]. + pub fn download_h264( + &mut self, + runtime: &Handle, + done: impl FnOnce(H264Download) + Send + 'static, + ) { + if matches!(self.h264, H264::Downloading | H264::Loaded(_)) { + return; + } + self.h264 = H264::Downloading; + let dir = self.openh264_dir.clone(); + runtime.spawn(async move { + let result = h264::download_openh264(&dir).await.map_err(|e| e.to_string()); + done(H264Download(result)); + }); + } + + pub fn downloaded(&mut self, download: H264Download, enabled: bool) { + match download.0 { + Ok(library) if enabled => self.loaded(library), + Ok(_) => self.h264 = H264::Off, + Err(e) => { + warn!("OpenH264 download failed: {e}"); + self.h264 = H264::Missing(format!("Download failed: {e}")); + } + } + } + + /// Screens and windows to share, as (name, detail); the test pattern + /// too when asked for. + pub fn sources(&mut self, test_pattern: bool) -> Result, String> { + let mut error = None; + let mut sources = match media::screen_sources() { + Ok(list) => list, + Err(e) => { + error = Some(e.to_string()); + Vec::new() + } + }; + if test_pattern { + sources.push(media::test_pattern_source()); + } + if sources.is_empty() { + return Err(error.unwrap_or_else(|| "Nothing to share was found.".into())); + } + self.sources = sources.iter().map(|s| (s.id.clone(), s.name.clone())).collect(); + Ok(sources + .iter() + .map(|s| { + let name = match s.id { + SourceId::Portal => "Choose via system dialog".to_owned(), + _ => s.name.clone(), + }; + let detail = match (&s.id, s.primary) { + (SourceId::Monitor(_), true) => { + format!("{} · primary", size_text(s.width, s.height)) + } + (SourceId::Window(_), _) => { + format!("window {}", size_text(s.width, s.height)).trim().to_owned() + } + _ => size_text(s.width, s.height), + }; + (name, detail) + }) + .collect()) + } + + /// Start capturing source `index` of [`Video::sources`]; `done` runs + /// on the runtime (the portal may wait for the user first). + pub fn start_capture( + &self, + runtime: &Handle, + index: usize, + options: CaptureRequest, + done: impl FnOnce(Result) + Send + 'static, + ) { + let Some((source, name)) = self.sources.get(index).cloned() else { + done(Err("Pick something to share.".into())); + return; + }; + let peer = self.peer_config(PeerConfig::default()); + let Some(codec) = stream_codec(&self.codecs, &peer) else { + done(Err("No video encoder is available.".into())); + return; + }; + let codecs = self.codecs.clone(); + let config = StreamerConfig { + source, + fps: options.fps, + bitrate_kbps: options.bitrate_kbps, + codec, + audio: options.audio, + restore_token: options.restore_token, + ..StreamerConfig::default() + }; + runtime.spawn(async move { + let result = Streamer::start(&codecs, config).await; + done(result.map(|streamer| Capture { streamer, name }).map_err(|e| e.to_string())); + }); + } + + /// Decode stream `stream_id` of `session`; `wake` is called (on the + /// decoder thread) when a picture is ready and none is waiting. + pub fn watch( + &self, + engine: &Engine, + session: u64, + stream_id: &str, + wake: impl Fn() + Send + Sync + 'static, + ) -> Decoder { + let pictures = Arc::new(Latest::new()); + let on_frame = deliver(pictures.clone(), wake); + let viewer = Viewer::start(engine, session, stream_id, self.codecs.clone(), on_frame); + Decoder { source: Source::Viewer(viewer), pictures } + } + + /// The test pattern through the encoder and decoder, without a + /// server (`TSC_DEMO_STREAM`). + pub fn demo( + &self, + runtime: &Handle, + wake: impl Fn() + Send + Sync + 'static, + done: impl FnOnce(Result) + Send + 'static, + ) { + let pictures = Arc::new(Latest::new()); + let on_frame = deliver(pictures.clone(), wake); + let codecs = self.codecs.clone(); + let config = StreamerConfig { source: SourceId::Synthetic, ..StreamerConfig::default() }; + runtime.spawn(async move { + let result = LocalPreview::start(codecs, config, on_frame).await; + done( + result + .map(|preview| Decoder { source: Source::Preview(preview), pictures }) + .map_err(|e| e.to_string()), + ); + }); + } + } + + /// Converts decoded frames into Slint pixel buffers, keeping the newest. + fn deliver( + pictures: Arc>, + wake: impl Fn() + Send + Sync + 'static, + ) -> impl FnMut(VideoFrame) + Send + 'static { + move |frame: VideoFrame| { + let mut buffer = Picture::new(frame.width, frame.height); + let stride = frame.width as usize * 4; + if let Err(e) = convert::to_rgba(&frame, buffer.make_mut_bytes(), stride) { + warn!("cannot show a picture: {e}"); + return; + } + if pictures.put(buffer) { + wake(); + } + } + } + + /// The result of [`Video::download_h264`]. + pub(crate) struct H264Download(Result); + + /// Share settings from the dialog. + pub(crate) struct CaptureRequest { + pub fps: u32, + pub bitrate_kbps: u32, + pub audio: bool, + pub restore_token: Option, + } + + /// A running capture for our stream. Stops when dropped. + pub(crate) struct Capture { + streamer: Streamer, + name: String, + } + + impl Capture { + /// Encode into the live stream. + pub fn attach(&self, sink: StreamSink) { + self.streamer.attach(Arc::new(sink)); + } + + pub fn source_name(&self) -> &str { + &self.name + } + + pub fn has_audio(&self) -> bool { + self.streamer.has_audio() + } + + pub fn audio_error(&self) -> Option { + self.streamer.audio_error().map(str::to_owned) + } + + /// The portal's token for this choice, to keep. + pub fn restore_token(&self) -> Option { + self.streamer.restore_token().map(str::to_owned) + } + + /// The capture stopped by itself (e.g. sharing ended in the desktop). + pub fn ended(&self) -> bool { + self.streamer.stats().capture_ended + } + + /// One line about what is sent. + pub fn status(&self) -> String { + let stats = self.streamer.stats(); + let mut text = format!("{} · {}", self.name, size_text(stats.width, stats.height)); + text.push_str(&format!(" · {} frames sent", stats.video_frames)); + if self.streamer.has_audio() { + text.push_str(" · with sound"); + } + if let Some(e) = stats.error { + text.push_str(&format!(" · encoder: {e}")); + } + text + } + } + + enum Source { + Viewer(Viewer), + Preview(LocalPreview), + } + + /// Decodes a watched stream into pictures. Stops when dropped. + pub(crate) struct Decoder { + source: Source, + pictures: Arc>, + } + + impl Decoder { + /// The newest picture since the last call. + pub fn take_picture(&self) -> Option { + self.pictures.take().map(Image::from_rgba8) + } + + /// One line about the video: codec, size, problems. + pub fn info(&self) -> String { + let stats = match &self.source { + Source::Viewer(v) => v.stats(), + Source::Preview(p) => p.stats(), + }; + let mut parts = Vec::new(); + if let Some(codec) = stats.codec { + parts.push(codec.to_string()); + } + if stats.width > 0 { + parts.push(size_text(stats.width, stats.height)); + } + if let Some(e) = stats.error { + parts.push(e); + } + parts.join(" · ") + } + + /// Whether pictures could never come (no decoder for the codec). + pub fn error(&self) -> Option { + let stats = match &self.source { + Source::Viewer(v) => v.stats(), + Source::Preview(p) => p.stats(), + }; + stats.error.filter(|_| stats.decoded == 0) + } + } +} + +#[cfg(not(feature = "media"))] +mod imp { + use std::path::Path; + + use slint::Image; + use tokio::runtime::Handle; + use tsc_core::stream::PeerConfig; + use tsc_core::{Engine, StreamSink}; + + pub const AVAILABLE: bool = false; + const UNAVAILABLE: &str = "Video is not available in this build."; + + pub(crate) struct Video; + + impl Video { + pub fn new(_data_dir: &Path, _openh264: bool) -> Self { + Self + } + + pub fn peer_config(&self, base: PeerConfig) -> PeerConfig { + base + } + + pub fn h264_status(&self) -> (bool, String) { + (false, UNAVAILABLE.into()) + } + + pub fn set_h264(&mut self, _enabled: bool) {} + + pub fn download_h264(&mut self, _runtime: &Handle, _done: impl FnOnce(H264Download)) {} + + pub fn downloaded(&mut self, _download: H264Download, _enabled: bool) {} + + pub fn sources(&mut self, _test_pattern: bool) -> Result, String> { + Err(UNAVAILABLE.into()) + } + + pub fn start_capture( + &self, + _runtime: &Handle, + _index: usize, + _options: CaptureRequest, + done: impl FnOnce(Result), + ) { + done(Err(UNAVAILABLE.into())); + } + + pub fn watch( + &self, + _engine: &Engine, + _session: u64, + _stream_id: &str, + _wake: impl Fn() + Send + Sync + 'static, + ) -> Decoder { + Decoder + } + + pub fn demo( + &self, + _runtime: &Handle, + _wake: impl Fn() + Send + Sync + 'static, + done: impl FnOnce(Result), + ) { + done(Err(UNAVAILABLE.into())); + } + } + + pub(crate) struct H264Download; + + pub(crate) struct CaptureRequest { + pub fps: u32, + pub bitrate_kbps: u32, + pub audio: bool, + pub restore_token: Option, + } + + pub(crate) enum Capture {} + + impl Capture { + pub fn attach(&self, _sink: StreamSink) { + match *self {} + } + + pub fn source_name(&self) -> &str { + match *self {} + } + + pub fn has_audio(&self) -> bool { + match *self {} + } + + pub fn audio_error(&self) -> Option { + match *self {} + } + + pub fn restore_token(&self) -> Option { + match *self {} + } + + pub fn ended(&self) -> bool { + match *self {} + } + + pub fn status(&self) -> String { + match *self {} + } + } + + pub(crate) struct Decoder; + + impl Decoder { + pub fn take_picture(&self) -> Option { + None + } + + pub fn info(&self) -> String { + String::new() + } + + pub fn error(&self) -> Option { + Some(UNAVAILABLE.into()) + } + } +} diff --git a/crates/tsc-ui/ui/app.slint b/crates/tsc-ui/ui/app.slint index 4fd44a4..51a26a9 100644 --- a/crates/tsc-ui/ui/app.slint +++ b/crates/tsc-ui/ui/app.slint @@ -1,4 +1,4 @@ -import { Button, LineEdit, ListView, ComboBox, AboutSlint, VerticalBox, HorizontalBox, ScrollView } from "std-widgets.slint"; +import { Button, LineEdit, ListView, ComboBox, CheckBox, Slider, AboutSlint, VerticalBox, HorizontalBox, ScrollView, TabWidget } from "std-widgets.slint"; export struct ServerItem { id: int, @@ -21,6 +21,12 @@ export struct TreeItem { streaming: bool, locked: bool, collapsed: bool, + // Local playback of this client: muted, or its volume in percent + // (100 = unchanged). + local-muted: bool, + local-volume: int, + // Our own client. + myself: bool, } export struct ChatTab { @@ -51,6 +57,73 @@ export struct BookmarkForm { query-password: string, } +// A stream in our channel. An empty id: a client that streams, but the +// server did not announce the stream to us (it started before we joined). +export struct StreamItem { + id: string, + name: string, + streamer: string, + audio: bool, + // Shown in the viewer. + watching: bool, + // Our own stream. + own: bool, +} + +// A viewer of our stream. state: "requested", "connecting" or "connected". +export struct ViewerItem { + client: int, + name: string, + state: string, + message: string, +} + +// A capture source for the share dialog. +export struct SourceItem { + name: string, + detail: string, +} + +export struct ShareForm { + source: int, + name: string, + // Index into the frame rate choices (15, 30, 60). + fps-index: int, + // Index into the bitrate choices (2.5, 4.6, 8, 10 Mbit/s). + bitrate-index: int, + audio: bool, + auto-accept: bool, +} + +export struct AudioForm { + // 0 = system default, then the devices. + input-index: int, + output-index: int, + // 0 = push-to-talk, 1 = voice activation, 2 = continuous. + transmit: int, + // dBFS. + vad-threshold: float, + echo-cancellation: bool, + noise-suppression: bool, + // 0 = low ... 3 = very high. + noise-level: int, + auto-gain: bool, + // dB. + input-gain: float, + // Percent. + output-volume: float, + // Milliseconds. + playback-buffer: float, +} + +// Local playback settings of one client. volume in percent. +export struct ClientAudio { + id: int, + name: string, + volume: float, + muted: bool, +} + export global Bridge { in property <[ServerItem]> servers; in-out property current-server: -1; @@ -59,7 +132,7 @@ export global Bridge { in-out property current-tab: 0; in property <[ChatLine]> messages; in property status-text; - in property server-title: "No server selected"; + in property server-title: @tr("No server selected"); in property voice-connected; in property voice-connecting; in property observing; @@ -69,6 +142,55 @@ export global Bridge { in property transmitting; in property presence-source; + // Streams (TeamSpeak 6 while connected with voice). + in property streams-available; + in property <[StreamItem]> streams; + // Our stream: "", "starting", "live" or "ended". + in property share-state; + in property share-status; + in property <[ViewerItem]> share-viewers; + in property share-requests; + in property <[SourceItem]> share-sources; + in property share-error; + in property share-busy; + // Whether capture and encoding are built in. + in property can-share: true; + + // The stream shown in the viewer. + in property viewer-open; + in property viewer-frame; + in property viewer-has-frame; + in property viewer-title; + // Shown instead of (or over) the picture: waiting, ended, errors. + in property viewer-status; + in property viewer-info; + in property viewer-ended; + in-out property viewer-volume: 100; + in property viewer-fullscreen; + + // Settings. + in property <[string]> input-devices; + in property <[string]> output-devices; + in-out property audio; + // Microphone level in dBFS and whether voice is sent. + in property input-level: -100; + in property input-sending; + in property mic-test; + in-out property global-ptt; + in-out property ptt-key; + in property ptt-status; + in-out property h264-enabled; + in property h264-loaded; + in property h264-busy; + in property h264-status; + in property h264-attribution; + in-out property client-audio; + // Opt-in local crash reports, and a notice about reports on disk. + in-out property crash-reports; + in property crash-notice; + // Third-party notices, one entry per line, for the About page. + in property <[string]> notices; + callback select-server(int); callback connect-voice(); callback disconnect-voice(); @@ -85,6 +207,33 @@ export global Bridge { callback edit-bookmark(int) -> BookmarkForm; callback save-bookmark(BookmarkForm); callback delete-bookmark(int); + + callback open-share() -> ShareForm; + callback start-share(ShareForm); + callback stop-share(); + callback respond-viewer(int, bool); + callback kick-viewer(int); + callback watch-stream(string); + callback show-viewer(); + callback hide-viewer(); + callback leave-stream(); + callback set-stream-volume(float); + callback toggle-fullscreen(); + + callback open-settings(); + callback close-settings(); + callback audio-changed(AudioForm); + callback toggle-mic-test(); + callback apply-ptt(bool, string); + callback set-h264(bool); + callback download-h264(); + callback open-client(int) -> bool; + callback client-audio-changed(ClientAudio); + callback set-crash-reports(bool); + callback open-crash-folder(); + callback delete-crash-reports(); + callback dismiss-crash-notice(); + callback open-about(); } component StatusDot inherits Rectangle { @@ -110,76 +259,112 @@ component Field inherits HorizontalLayout { text <=> value; placeholder-text: placeholder; input-type: input-type; + accessible-label: label; } } -component BookmarkEditor inherits Rectangle { - in-out property form; - callback done(); +// A label beside a control, for settings rows. +component Row inherits HorizontalLayout { + in property label; + spacing: 8px; + Text { + text: label; + width: 170px; + vertical-alignment: center; + wrap: word-wrap; + } + @children +} + +// Small text tag in a list row. +component Tag inherits Text { + font-size: 10px; + vertical-alignment: center; +} + +// A dimmed full-window backdrop with a centered card. +component Dialog inherits Rectangle { + in property card-width: 520px; + in property card-height: 520px; + callback dismissed(); background: #000000a0; - TouchArea { } + TouchArea { + clicked => { dismissed(); } + } Rectangle { - width: min(parent.width - 32px, 520px); - height: min(parent.height - 32px, 520px); + width: min(parent.width - 32px, card-width); + height: min(parent.height - 32px, card-height); background: #1f2328; border-radius: 8px; - VerticalBox { - Text { - text: form.id < 0 ? "Add server" : "Edit server"; - font-size: 18px; - font-weight: 700; - } - ScrollView { - VerticalLayout { - spacing: 6px; - Field { label: "Name"; value <=> form.name; placeholder: "My server"; } - Field { label: "Address"; value <=> form.address; placeholder: "ts.example.org:9987"; } - Field { label: "Nickname"; value <=> form.nickname; } - Field { label: "Server password"; value <=> form.server-password; input-type: InputType.password; } + border-width: 1px; + border-color: #30363d; + // Clicks inside the card do not dismiss it. + TouchArea { } + @children + } +} + +component BookmarkEditor inherits Dialog { + in-out property form; + callback done(); + dismissed => { done(); } + VerticalBox { + Text { + text: form.id < 0 ? @tr("Add server") : @tr("Edit server"); + font-size: 18px; + font-weight: 700; + } + ScrollView { + VerticalLayout { + spacing: 6px; + Field { label: @tr("Name"); value <=> form.name; placeholder: @tr("My server"); } + Field { label: @tr("Address"); value <=> form.address; placeholder: "ts.example.org:9987"; } + Field { label: @tr("Nickname"); value <=> form.nickname; } + Field { label: @tr("Server password"); value <=> form.server-password; input-type: InputType.password; } + Text { + text: @tr("Invisible presence and chat without joining (optional)"); + font-weight: 600; + } + Field { label: @tr("Gateway URL"); value <=> form.gateway-url; placeholder: "wss://gw.example.org/v1"; } + HorizontalLayout { + spacing: 8px; Text { - text: "Invisible presence and chat without joining (optional)"; - font-weight: 600; + text: @tr("Query transport"); + width: 130px; + vertical-alignment: center; } - Field { label: "Gateway URL"; value <=> form.gateway-url; placeholder: "wss://gw.example.org/v1"; } - HorizontalLayout { - spacing: 8px; - Text { - text: "Query transport"; - width: 130px; - vertical-alignment: center; - } - ComboBox { - model: ["none", "ssh", "raw", "http"]; - current-value <=> form.query-transport; - } + ComboBox { + model: ["none", "ssh", "raw", "http"]; + current-value <=> form.query-transport; + accessible-label: @tr("Query transport"); } - Field { label: "Query address"; value <=> form.query-addr; placeholder: "ts.example.org:10022"; } - Field { label: "Query login"; value <=> form.query-user; } - Field { label: "Query password"; value <=> form.query-password; input-type: InputType.password; } + } + Field { label: @tr("Query address"); value <=> form.query-addr; placeholder: "ts.example.org:10022"; } + Field { label: @tr("Query login"); value <=> form.query-user; } + Field { label: @tr("Query password"); value <=> form.query-password; input-type: InputType.password; } + } + } + HorizontalLayout { + alignment: end; + spacing: 8px; + if form.id >= 0: Button { + text: @tr("Delete"); + clicked => { + Bridge.delete-bookmark(form.id); + done(); } } - HorizontalLayout { - alignment: end; - spacing: 8px; - if form.id >= 0: Button { - text: "Delete"; - clicked => { - Bridge.delete-bookmark(form.id); - done(); - } - } - Button { - text: "Cancel"; - clicked => { done(); } - } - Button { - text: "Save"; - primary: true; - enabled: form.address != "" && form.nickname != ""; - clicked => { - Bridge.save-bookmark(form); - done(); - } + Button { + text: @tr("Cancel"); + clicked => { done(); } + } + Button { + text: @tr("Save"); + primary: true; + enabled: form.address != "" && form.nickname != ""; + clicked => { + Bridge.save-bookmark(form); + done(); } } } @@ -190,16 +375,19 @@ component ServerList inherits Rectangle { callback add(); callback edit(int); background: #161b22; + accessible-role: list; + accessible-label: @tr("Servers"); VerticalBox { HorizontalLayout { Text { - text: "Servers"; + text: @tr("Servers"); font-weight: 700; vertical-alignment: center; } Button { text: "+"; width: 32px; + accessible-label: @tr("Add server"); clicked => { add(); } } } @@ -208,6 +396,12 @@ component ServerList inherits Rectangle { height: 48px; border-radius: 6px; background: Bridge.current-server == server.id ? #30363d : area.has-hover ? #21262d : transparent; + accessible-role: list-item; + accessible-label: server.name; + accessible-description: server.address; + accessible-item-selectable: true; + accessible-item-selected: Bridge.current-server == server.id; + accessible-action-default => { Bridge.select-server(server.id); } area := TouchArea { clicked => { Bridge.select-server(server.id); } double-clicked => { edit(server.id); } @@ -239,11 +433,25 @@ component ServerList inherits Rectangle { } component ChannelTree inherits Rectangle { + // A client row was clicked: its local volume and mute. + callback client-clicked(int); background: #0d1117; + accessible-role: list; + accessible-label: @tr("Channels and clients"); ListView { for row in Bridge.tree: Rectangle { height: 26px; background: row-area.has-hover ? #161b22 : transparent; + accessible-role: list-item; + accessible-label: row.is-channel ? @tr("Channel {}", row.name) : row.name; + accessible-description: (row.talking ? @tr("talking") + " " : "") + (row.streaming ? @tr("streaming") + " " : "") + (row.muted ? @tr("microphone off") + " " : "") + (row.local-muted ? @tr("muted for you") : ""); + accessible-action-default => { + if (row.is-channel) { + Bridge.open-channel-chat(row.id); + } else { + client-clicked(row.id); + } + } row-area := TouchArea { double-clicked => { if (row.is-channel) { @@ -253,6 +461,8 @@ component ChannelTree inherits Rectangle { clicked => { if (row.is-channel) { Bridge.open-channel-chat(row.id); + } else if (!row.myself) { + client-clicked(row.id); } } } @@ -263,6 +473,9 @@ component ChannelTree inherits Rectangle { if row.is-channel: Text { text: row.collapsed ? "▸" : "▾"; vertical-alignment: center; + accessible-role: button; + accessible-label: row.collapsed ? @tr("Expand") : @tr("Collapse"); + accessible-action-default => { Bridge.toggle-collapse(row.id); } TouchArea { clicked => { Bridge.toggle-collapse(row.id); } } @@ -283,11 +496,110 @@ component ChannelTree inherits Rectangle { color: row.away ? #8b949e : row.own ? #58a6ff : #e6edf3; overflow: elide; } - if row.locked: Text { text: "password"; font-size: 10px; color: #d29922; vertical-alignment: center; } - if row.muted: Text { text: "mic off"; font-size: 10px; color: #f85149; vertical-alignment: center; } - if row.sound-off: Text { text: "sound off"; font-size: 10px; color: #f85149; vertical-alignment: center; } - if row.streaming: Text { text: "LIVE"; font-size: 10px; color: #a371f7; vertical-alignment: center; } - if row.away: Text { text: "away"; font-size: 10px; color: #8b949e; vertical-alignment: center; } + if row.locked: Tag { text: @tr("password"); color: #d29922; } + if row.muted: Tag { text: @tr("mic off"); color: #f85149; } + if row.sound-off: Tag { text: @tr("sound off"); color: #f85149; } + if row.local-muted: Tag { text: @tr("muted for you"); color: #f0883e; } + if !row.local-muted && row.local-volume != 100 && !row.is-channel: Tag { + text: @tr("{}%", row.local-volume); + color: #8b949e; + } + if row.streaming: Tag { text: @tr("LIVE"); color: #a371f7; font-weight: 700; } + if row.away: Tag { text: @tr("away"); color: #8b949e; } + } + } + } +} + +// Streams in our channel, requests to watch ours. +component StreamsPanel inherits Rectangle { + callback manage-share(); + background: #0d1117; + border-width: 1px; + border-color: #21262d; + accessible-role: groupbox; + accessible-label: @tr("Streams"); + VerticalLayout { + padding: 8px; + spacing: 6px; + HorizontalLayout { + spacing: 6px; + Text { + text: @tr("Streams"); + font-weight: 700; + vertical-alignment: center; + } + if Bridge.share-state == "live": Text { + text: @tr("● You are live"); + color: #f85149; + font-size: 11px; + vertical-alignment: center; + } + Rectangle { } + if Bridge.share-state == "live" || Bridge.share-state == "starting": Button { + text: Bridge.share-requests > 0 ? @tr("Viewers ({})", Bridge.share-requests) : @tr("Manage"); + clicked => { manage-share(); } + } + } + if Bridge.streams.length == 0: Text { + text: @tr("No streams in your channel."); + color: #8b949e; + font-size: 12px; + } + for stream in Bridge.streams: HorizontalLayout { + spacing: 6px; + Rectangle { + width: 6px; + height: 6px; + y: (parent.height - self.height) / 2; + border-radius: 3px; + background: #a371f7; + } + VerticalLayout { + horizontal-stretch: 1; + Text { + text: stream.id == "" ? @tr("{} is streaming", stream.streamer) : stream.name == "" ? @tr("Untitled stream") : stream.name; + font-weight: 600; + overflow: elide; + } + Text { + text: stream.id == "" ? @tr("Started before you joined; the server did not announce it.") : stream.own ? @tr("your stream") : stream.audio ? @tr("by {} · with sound", stream.streamer) : @tr("by {}", stream.streamer); + font-size: 11px; + color: #8b949e; + overflow: elide; + } + } + if stream.id != "" && !stream.own && !stream.watching: Button { + text: @tr("Watch"); + accessible-label: @tr("Watch {}", stream.name); + clicked => { Bridge.watch-stream(stream.id); } + } + if stream.watching && !Bridge.viewer-open: Button { + text: @tr("Show"); + clicked => { Bridge.show-viewer(); } + } + if stream.watching: Button { + text: @tr("Leave"); + clicked => { Bridge.leave-stream(); } + } + } + for viewer in Bridge.share-viewers: HorizontalLayout { + spacing: 6px; + if viewer.state == "requested": Text { + text: @tr("{} wants to watch", viewer.name); + horizontal-stretch: 1; + vertical-alignment: center; + overflow: elide; + color: #d29922; + } + if viewer.state == "requested": Button { + text: @tr("Accept"); + primary: true; + clicked => { Bridge.respond-viewer(viewer.client, true); } + } + if viewer.state == "requested": Button { + text: @tr("Deny"); + clicked => { Bridge.respond-viewer(viewer.client, false); } } } } @@ -299,9 +611,17 @@ component ChatPanel inherits Rectangle { HorizontalLayout { height: 34px; spacing: 2px; + accessible-role: tab-list; + accessible-label: @tr("Chats"); for tab[i] in Bridge.tabs: Rectangle { width: tab-text.preferred-width + 28px; background: Bridge.current-tab == i ? #30363d : tab-area.has-hover ? #21262d : #161b22; + accessible-role: AccessibleRole.tab; + accessible-label: tab.title; + accessible-description: tab.unread > 0 ? @tr("{} unread", tab.unread) : ""; + accessible-item-selectable: true; + accessible-item-selected: Bridge.current-tab == i; + accessible-action-default => { Bridge.select-tab(i); } tab-area := TouchArea { clicked => { Bridge.select-tab(i); } } @@ -317,6 +637,9 @@ component ChatPanel inherits Rectangle { if tab.kind == 1: Text { text: "×"; vertical-alignment: center; + accessible-role: button; + accessible-label: @tr("Close {}", tab.title); + accessible-action-default => { Bridge.close-tab(i); } TouchArea { clicked => { Bridge.close-tab(i); } } @@ -326,6 +649,7 @@ component ChatPanel inherits Rectangle { Rectangle { } } ListView { + accessible-label: @tr("Messages"); for line in Bridge.messages: VerticalLayout { padding: 6px; HorizontalLayout { @@ -336,7 +660,7 @@ component ChatPanel inherits Rectangle { color: line.relayed ? #58a6ff : #e6edf3; } Text { - text: line.time + (line.relayed ? " via relay" : ""); + text: line.time + (line.relayed ? " " + @tr("via relay") : ""); font-size: 11px; color: #8b949e; vertical-alignment: center; @@ -352,7 +676,8 @@ component ChatPanel inherits Rectangle { padding: 6px; spacing: 6px; input := LineEdit { - placeholder-text: "Message"; + placeholder-text: @tr("Message"); + accessible-label: @tr("Message"); accepted(text) => { if (text != "") { Bridge.send-message(text); @@ -361,7 +686,7 @@ component ChatPanel inherits Rectangle { } } Button { - text: "Send"; + text: @tr("Send"); clicked => { if (input.text != "") { Bridge.send-message(input.text); @@ -373,8 +698,754 @@ component ChatPanel inherits Rectangle { } } +// The stream we watch: title, picture, and player controls below it. +component StreamViewer inherits Rectangle { + background: #010409; + accessible-role: groupbox; + accessible-label: @tr("Stream viewer"); + VerticalLayout { + Rectangle { + height: 42px; + background: #161b22; + VerticalLayout { + padding-left: 10px; + padding-right: 10px; + alignment: center; + Text { + text: Bridge.viewer-title; + font-weight: 700; + overflow: elide; + } + Text { + text: Bridge.viewer-info; + font-size: 11px; + color: #8b949e; + overflow: elide; + } + } + } + Rectangle { + vertical-stretch: 1; + Image { + width: parent.width; + height: parent.height; + source: Bridge.viewer-frame; + image-fit: contain; + visible: Bridge.viewer-has-frame; + accessible-role: image; + accessible-label: @tr("Stream picture"); + } + if Bridge.viewer-status != "": Rectangle { + width: min(parent.width - 32px, status-text.preferred-width + 32px); + height: status-text.preferred-height + 20px; + border-radius: 6px; + background: #161b22e0; + status-text := Text { + width: min(root.width - 64px, self.preferred-width); + text: Bridge.viewer-status; + horizontal-alignment: center; + wrap: word-wrap; + accessible-live-region: polite; + } + } + } + Rectangle { + height: 44px; + background: #161b22; + HorizontalLayout { + padding: 6px; + padding-left: 10px; + spacing: 8px; + Text { + text: @tr("Volume"); + vertical-alignment: center; + color: #8b949e; + } + Slider { + width: 140px; + minimum: 0; + maximum: 200; + value <=> Bridge.viewer-volume; + enabled: !Bridge.viewer-ended; + accessible-label: @tr("Stream volume"); + changed(v) => { Bridge.set-stream-volume(v); } + } + Text { + text: @tr("{}%", round(Bridge.viewer-volume)); + width: 40px; + vertical-alignment: center; + color: #8b949e; + } + Rectangle { } + Button { + text: Bridge.viewer-fullscreen ? @tr("Exit full screen") : @tr("Full screen"); + clicked => { Bridge.toggle-fullscreen(); } + } + if !Bridge.viewer-fullscreen: Button { + text: @tr("Chat"); + accessible-label: @tr("Back to the chat"); + clicked => { Bridge.hide-viewer(); } + } + Button { + text: Bridge.viewer-ended ? @tr("Close") : @tr("Leave"); + clicked => { Bridge.leave-stream(); } + } + } + } + } +} + +component ShareDialog inherits Dialog { + in-out property form; + callback done(); + card-width: 560px; + card-height: 560px; + dismissed => { done(); } + VerticalBox { + Text { + text: Bridge.share-state == "live" ? @tr("You are sharing your screen") : Bridge.share-state == "starting" ? @tr("Starting…") : @tr("Share screen"); + font-size: 18px; + font-weight: 700; + } + if Bridge.share-state == "live" || Bridge.share-state == "starting": VerticalLayout { + spacing: 8px; + vertical-stretch: 1; + Text { + text: Bridge.share-status; + color: #8b949e; + wrap: word-wrap; + } + Text { + text: @tr("Viewers"); + font-weight: 600; + } + if Bridge.share-viewers.length == 0: Text { + text: @tr("Nobody is watching yet. Viewers in your channel can join from their streams list."); + color: #8b949e; + wrap: word-wrap; + } + ListView { + vertical-stretch: 1; + accessible-label: @tr("Viewers"); + for viewer in Bridge.share-viewers: HorizontalLayout { + padding-top: 4px; + padding-bottom: 4px; + spacing: 8px; + VerticalLayout { + horizontal-stretch: 1; + alignment: center; + Text { + text: viewer.name; + font-weight: 600; + overflow: elide; + } + Text { + text: viewer.state == "requested" ? (viewer.message == "" ? @tr("asks to watch") : @tr("asks to watch: {}", viewer.message)) : viewer.state == "connecting" ? @tr("connecting") : @tr("watching"); + font-size: 11px; + color: viewer.state == "requested" ? #d29922 : viewer.state == "connected" ? #3fb950 : #8b949e; + overflow: elide; + } + } + if viewer.state == "requested": Button { + text: @tr("Accept"); + primary: true; + clicked => { Bridge.respond-viewer(viewer.client, true); } + } + if viewer.state == "requested": Button { + text: @tr("Deny"); + clicked => { Bridge.respond-viewer(viewer.client, false); } + } + if viewer.state != "requested": Button { + text: @tr("Remove"); + accessible-label: @tr("Remove {}", viewer.name); + clicked => { Bridge.kick-viewer(viewer.client); } + } + } + } + HorizontalLayout { + alignment: end; + spacing: 8px; + Button { + text: @tr("Close"); + clicked => { done(); } + } + Button { + text: @tr("Stop sharing"); + primary: true; + clicked => { Bridge.stop-share(); } + } + } + } + if Bridge.share-state != "live" && Bridge.share-state != "starting": VerticalLayout { + spacing: 8px; + vertical-stretch: 1; + Text { + text: @tr("What to share"); + font-weight: 600; + } + ListView { + vertical-stretch: 1; + min-height: 120px; + accessible-label: @tr("What to share"); + for source[i] in Bridge.share-sources: Rectangle { + height: 40px; + border-radius: 6px; + background: form.source == i ? #1f6feb40 : source-area.has-hover ? #21262d : transparent; + border-width: form.source == i ? 1px : 0px; + border-color: #1f6feb; + accessible-role: list-item; + accessible-label: source.name; + accessible-description: source.detail; + accessible-item-selectable: true; + accessible-item-selected: form.source == i; + accessible-action-default => { form.source = i; } + source-area := TouchArea { + clicked => { form.source = i; } + } + HorizontalLayout { + padding-left: 10px; + padding-right: 10px; + spacing: 8px; + Text { + text: source.name; + vertical-alignment: center; + horizontal-stretch: 1; + overflow: elide; + } + Text { + text: source.detail; + vertical-alignment: center; + font-size: 11px; + color: #8b949e; + } + } + } + } + Field { label: @tr("Stream name"); value <=> form.name; } + HorizontalLayout { + spacing: 8px; + Text { + text: @tr("Frame rate"); + width: 130px; + vertical-alignment: center; + } + ComboBox { + model: [@tr("15 fps"), @tr("30 fps"), @tr("60 fps")]; + current-index <=> form.fps-index; + accessible-label: @tr("Frame rate"); + } + } + HorizontalLayout { + spacing: 8px; + Text { + text: @tr("Quality"); + width: 130px; + vertical-alignment: center; + } + ComboBox { + model: [@tr("Low (2.5 Mbit/s)"), @tr("Standard (4.6 Mbit/s)"), @tr("High (8 Mbit/s)"), @tr("Best (10 Mbit/s)")]; + current-index <=> form.bitrate-index; + accessible-label: @tr("Quality"); + } + } + CheckBox { + text: @tr("Share system audio"); + checked <=> form.audio; + } + CheckBox { + text: @tr("Let everyone in the channel watch without asking"); + checked <=> form.auto-accept; + } + if Bridge.share-error != "": Text { + text: Bridge.share-error; + color: #f85149; + wrap: word-wrap; + } + HorizontalLayout { + alignment: end; + spacing: 8px; + Button { + text: @tr("Cancel"); + clicked => { done(); } + } + Button { + text: Bridge.share-busy ? @tr("Starting…") : @tr("Start sharing"); + primary: true; + enabled: !Bridge.share-busy && Bridge.streams-available && Bridge.share-sources.length > 0; + clicked => { Bridge.start-share(form); } + } + } + } + } +} + +// Microphone level with the voice activation threshold. +component LevelMeter inherits Rectangle { + in property level: -100; + in property threshold: -40; + in property show-threshold: true; + // dBFS shown at the left edge. + property floor: -70; + height: 12px; + border-radius: 3px; + background: #0d1117; + border-width: 1px; + border-color: #30363d; + accessible-role: progress-indicator; + accessible-label: @tr("Microphone level"); + accessible-value: @tr("{} dB", round(level)); + accessible-value-minimum: floor; + accessible-value-maximum: 0; + Rectangle { + x: 0; + width: parent.width * clamp((level - floor) / (0 - floor), 0, 1); + border-radius: 3px; + background: level >= threshold ? #3fb950 : #58a6ff; + } + if show-threshold: Rectangle { + x: parent.width * clamp((threshold - floor) / (0 - floor), 0, 1) - 1px; + width: 2px; + background: #e6edf3; + } +} + +component SettingsDialog inherits Dialog { + callback done(); + card-width: 640px; + card-height: 660px; + dismissed => { done(); } + VerticalBox { + Text { + text: @tr("Settings"); + font-size: 18px; + font-weight: 700; + } + TabWidget { + vertical-stretch: 1; + Tab { + title: @tr("Audio"); + ScrollView { + VerticalLayout { + padding: 8px; + spacing: 8px; + Row { + label: @tr("Microphone"); + ComboBox { + model: Bridge.input-devices; + current-index: Bridge.audio.input-index; + accessible-label: @tr("Microphone"); + selected => { + Bridge.audio.input-index = self.current-index; + Bridge.audio-changed(Bridge.audio); + } + } + } + Row { + label: @tr("Speakers"); + ComboBox { + model: Bridge.output-devices; + current-index: Bridge.audio.output-index; + accessible-label: @tr("Speakers"); + selected => { + Bridge.audio.output-index = self.current-index; + Bridge.audio-changed(Bridge.audio); + } + } + } + Row { + label: @tr("Transmit"); + ComboBox { + model: [@tr("Push-to-talk"), @tr("Voice activation"), @tr("Continuously")]; + current-index: Bridge.audio.transmit; + accessible-label: @tr("Transmit"); + selected => { + Bridge.audio.transmit = self.current-index; + Bridge.audio-changed(Bridge.audio); + } + } + } + Row { + label: @tr("Voice activation level"); + Slider { + minimum: -70; + maximum: -10; + value: Bridge.audio.vad-threshold; + enabled: Bridge.audio.transmit == 1; + accessible-label: @tr("Voice activation level"); + changed(v) => { + Bridge.audio.vad-threshold = round(v); + Bridge.audio-changed(Bridge.audio); + } + } + Text { + text: @tr("{} dB", round(Bridge.audio.vad-threshold)); + width: 56px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + Row { + label: @tr("Microphone level"); + VerticalLayout { + alignment: center; + LevelMeter { + level: Bridge.input-level; + threshold: Bridge.audio.vad-threshold; + show-threshold: Bridge.audio.transmit == 1; + } + } + Button { + text: Bridge.mic-test ? @tr("Stop test") : @tr("Test"); + enabled: !Bridge.voice-connected; + accessible-label: Bridge.mic-test ? @tr("Stop the microphone test") : @tr("Test the microphone"); + clicked => { Bridge.toggle-mic-test(); } + } + } + Text { + text: Bridge.voice-connected ? (Bridge.input-sending ? @tr("Sending voice") : @tr("Not sending")) : @tr("The meter shows the microphone while connected or during a test."); + font-size: 11px; + color: Bridge.input-sending ? #3fb950 : #8b949e; + wrap: word-wrap; + } + Text { + text: @tr("Processing"); + font-weight: 600; + } + CheckBox { + text: @tr("Echo cancellation"); + checked: Bridge.audio.echo-cancellation; + toggled => { + Bridge.audio.echo-cancellation = self.checked; + Bridge.audio-changed(Bridge.audio); + } + } + HorizontalLayout { + spacing: 8px; + CheckBox { + text: @tr("Noise suppression"); + checked: Bridge.audio.noise-suppression; + toggled => { + Bridge.audio.noise-suppression = self.checked; + Bridge.audio-changed(Bridge.audio); + } + } + ComboBox { + model: [@tr("Low"), @tr("Moderate"), @tr("High"), @tr("Very high")]; + current-index: Bridge.audio.noise-level; + enabled: Bridge.audio.noise-suppression; + accessible-label: @tr("Noise suppression level"); + selected => { + Bridge.audio.noise-level = self.current-index; + Bridge.audio-changed(Bridge.audio); + } + } + } + CheckBox { + text: @tr("Automatic gain control"); + checked: Bridge.audio.auto-gain; + toggled => { + Bridge.audio.auto-gain = self.checked; + Bridge.audio-changed(Bridge.audio); + } + } + Row { + label: @tr("Microphone gain"); + Slider { + minimum: -30; + maximum: 30; + value: Bridge.audio.input-gain; + accessible-label: @tr("Microphone gain"); + changed(v) => { + Bridge.audio.input-gain = round(v); + Bridge.audio-changed(Bridge.audio); + } + } + Text { + text: @tr("{} dB", round(Bridge.audio.input-gain)); + width: 56px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + Text { + text: @tr("Playback"); + font-weight: 600; + } + Row { + label: @tr("Volume"); + Slider { + minimum: 0; + maximum: 200; + value: Bridge.audio.output-volume; + accessible-label: @tr("Playback volume"); + changed(v) => { + Bridge.audio.output-volume = round(v); + Bridge.audio-changed(Bridge.audio); + } + } + Text { + text: @tr("{}%", round(Bridge.audio.output-volume)); + width: 56px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + Row { + label: @tr("Playback buffer"); + Slider { + minimum: 20; + maximum: 180; + value: Bridge.audio.playback-buffer; + accessible-label: @tr("Playback buffer"); + changed(v) => { + Bridge.audio.playback-buffer = round(v / 10) * 10; + Bridge.audio-changed(Bridge.audio); + } + } + Text { + text: @tr("{} ms", round(Bridge.audio.playback-buffer)); + width: 56px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + } + } + } + Tab { + title: @tr("Push-to-talk"); + VerticalLayout { + padding: 8px; + spacing: 8px; + alignment: start; + CheckBox { + text: @tr("Global push-to-talk key (works while other windows have focus)"); + checked <=> Bridge.global-ptt; + toggled => { Bridge.apply-ptt(Bridge.global-ptt, Bridge.ptt-key); } + } + Row { + label: @tr("Key"); + key-edit := LineEdit { + text <=> Bridge.ptt-key; + placeholder-text: "Ctrl+Shift+T"; + enabled: Bridge.global-ptt; + accessible-label: @tr("Push-to-talk key"); + accepted => { Bridge.apply-ptt(Bridge.global-ptt, Bridge.ptt-key); } + } + Button { + text: @tr("Apply"); + enabled: Bridge.global-ptt; + clicked => { Bridge.apply-ptt(Bridge.global-ptt, Bridge.ptt-key); } + } + } + Text { + text: Bridge.ptt-status; + color: #8b949e; + wrap: word-wrap; + } + Text { + text: @tr("Keys are written like Ctrl+Shift+T, Alt+F1, CapsLock or MouseBack. On Wayland the desktop asks to confirm the key and may let you pick another one. The \"Hold to talk\" button in the window always works."); + font-size: 11px; + color: #8b949e; + wrap: word-wrap; + } + } + } + Tab { + title: @tr("Streaming"); + VerticalLayout { + padding: 8px; + spacing: 8px; + alignment: start; + CheckBox { + text: @tr("Enable H.264 (downloads OpenH264 from Cisco)"); + checked <=> Bridge.h264-enabled; + toggled => { Bridge.set-h264(Bridge.h264-enabled); } + } + Text { + text: Bridge.h264-attribution; + font-size: 11px; + color: #8b949e; + wrap: word-wrap; + } + if Bridge.h264-enabled: HorizontalLayout { + spacing: 8px; + Text { + text: Bridge.h264-status; + vertical-alignment: center; + horizontal-stretch: 1; + wrap: word-wrap; + } + if !Bridge.h264-loaded: Button { + text: Bridge.h264-busy ? @tr("Downloading…") : @tr("Download OpenH264"); + enabled: !Bridge.h264-busy; + clicked => { Bridge.download-h264(); } + } + } + Text { + text: @tr("VP8 and VP9 work without it. H.264 lets you watch streams that other clients send as H.264. The library is downloaded from Cisco only when you click Download, and Cisco's license covers its patent royalties."); + font-size: 11px; + color: #8b949e; + wrap: word-wrap; + } + } + } + Tab { + title: @tr("Privacy"); + VerticalLayout { + padding: 8px; + spacing: 8px; + alignment: start; + CheckBox { + text: @tr("Save crash reports on this device (never uploaded)"); + checked <=> Bridge.crash-reports; + toggled => { Bridge.set-crash-reports(Bridge.crash-reports); } + } + Text { + text: @tr("A report is a text file with the error and where it happened. It may contain a server address from the error message. You can attach it to a bug report yourself; the app never sends it anywhere."); + font-size: 11px; + color: #8b949e; + wrap: word-wrap; + } + } + } + } + HorizontalLayout { + alignment: end; + Button { + text: @tr("Close"); + clicked => { done(); } + } + } + } +} + +// Local volume and mute of one client. +component ClientAudioDialog inherits Dialog { + callback done(); + card-width: 380px; + card-height: 220px; + dismissed => { done(); } + VerticalBox { + Text { + text: Bridge.client-audio.name; + font-size: 16px; + font-weight: 700; + overflow: elide; + } + Text { + text: @tr("Only changes what you hear."); + color: #8b949e; + font-size: 11px; + } + HorizontalLayout { + spacing: 8px; + Text { + text: @tr("Volume"); + vertical-alignment: center; + } + Slider { + minimum: 0; + maximum: 400; + value: Bridge.client-audio.volume; + enabled: !Bridge.client-audio.muted; + accessible-label: @tr("Volume of {}", Bridge.client-audio.name); + changed(v) => { + Bridge.client-audio.volume = round(v / 5) * 5; + Bridge.client-audio-changed(Bridge.client-audio); + } + } + Text { + text: @tr("{}%", round(Bridge.client-audio.volume)); + width: 48px; + vertical-alignment: center; + horizontal-alignment: right; + } + } + CheckBox { + text: @tr("Mute for me"); + checked: Bridge.client-audio.muted; + toggled => { + Bridge.client-audio.muted = self.checked; + Bridge.client-audio-changed(Bridge.client-audio); + } + } + HorizontalLayout { + alignment: end; + spacing: 8px; + Button { + text: @tr("Reset"); + clicked => { + Bridge.client-audio.volume = 100; + Bridge.client-audio.muted = false; + Bridge.client-audio-changed(Bridge.client-audio); + } + } + Button { + text: @tr("Close"); + primary: true; + clicked => { done(); } + } + } + } +} + +component AboutDialog inherits Dialog { + callback done(); + card-width: 720px; + card-height: 680px; + dismissed => { done(); } + VerticalBox { + Text { + text: @tr("About"); + font-size: 18px; + font-weight: 700; + } + Text { + text: @tr("Unofficial TeamSpeak 3/6 compatible client. Not affiliated with TeamSpeak Systems GmbH."); + wrap: word-wrap; + } + AboutSlint { + max-height: 150px; + } + if Bridge.h264-enabled: Text { + text: Bridge.h264-attribution; + wrap: word-wrap; + } + Text { + text: @tr("Third-party notices"); + font-weight: 600; + } + Rectangle { + vertical-stretch: 1; + background: #0d1117; + border-radius: 4px; + border-width: 1px; + border-color: #30363d; + ListView { + accessible-label: @tr("Third-party notices"); + for line in Bridge.notices: Text { + x: 8px; + width: parent.width - 16px; + text: line; + font-size: 11px; + color: #c9d1d9; + wrap: word-wrap; + } + } + } + HorizontalLayout { + alignment: end; + Button { + text: @tr("Close"); + clicked => { done(); } + } + } + } +} + export component MainWindow inherits Window { - title: "TS Client"; + title: @tr("TS Client"); preferred-width: 1200px; preferred-height: 760px; min-width: 360px; @@ -384,24 +1455,37 @@ export component MainWindow inherits Window { property editing: false; property show-about: false; + in-out property sharing-dialog: false; + in-out property settings-open: false; + property client-open: false; property form; + property share-form; // Phones and narrow windows show one pane at a time. Set from a change // handler: a binding on `width` would loop through the layout. property narrow: false; changed width => { narrow = self.width < 800px; } init => { narrow = self.width < 800px; } property pane: 1; + // The viewer takes the whole window in full screen. + property chrome: !(Bridge.viewer-open && Bridge.viewer-fullscreen); + + public function open-share-dialog() { + share-form = Bridge.open-share(); + sharing-dialog = true; + } VerticalLayout { // Toolbar - Rectangle { + if chrome: Rectangle { height: 48px; background: #161b22; + accessible-role: banner; HorizontalLayout { padding: 6px; spacing: 6px; if narrow: Button { - text: pane == 0 ? "Tree" : pane == 1 ? "Chat" : "Servers"; + text: pane == 0 ? @tr("Tree") : pane == 1 ? (Bridge.viewer-open ? @tr("Stream") : @tr("Chat")) : @tr("Servers"); + accessible-label: @tr("Switch pane"); clicked => { pane = mod(pane + 1, 3); } } Text { @@ -413,7 +1497,7 @@ export component MainWindow inherits Window { } Rectangle { } Button { - text: Bridge.voice-connected ? "Disconnect" : Bridge.voice-connecting ? "Connecting…" : "Connect"; + text: Bridge.voice-connected ? @tr("Disconnect") : Bridge.voice-connecting ? @tr("Connecting…") : @tr("Connect"); enabled: Bridge.current-server >= 0 && !Bridge.voice-connecting; primary: !Bridge.voice-connected; clicked => { @@ -425,17 +1509,17 @@ export component MainWindow inherits Window { } } Button { - text: Bridge.observing ? "Stop observing" : "Observe (invisible)"; + text: Bridge.observing ? @tr("Stop observing") : @tr("Observe (invisible)"); enabled: Bridge.can-observe; clicked => { Bridge.toggle-observe(); } } Button { - text: Bridge.input-muted ? "Mic: off" : "Mic: on"; + text: Bridge.input-muted ? @tr("Mic: off") : @tr("Mic: on"); enabled: Bridge.voice-connected; clicked => { Bridge.set-input-muted(!Bridge.input-muted); } } Button { - text: Bridge.output-muted ? "Sound: off" : "Sound: on"; + text: Bridge.output-muted ? @tr("Sound: off") : @tr("Sound: on"); enabled: Bridge.voice-connected; clicked => { Bridge.set-output-muted(!Bridge.output-muted); } } @@ -444,8 +1528,14 @@ export component MainWindow inherits Window { border-radius: 4px; background: Bridge.transmitting ? #238636 : ptt-area.has-hover ? #30363d : #21262d; opacity: Bridge.voice-connected ? 1.0 : 0.4; + accessible-role: button; + accessible-label: @tr("Hold to talk"); + accessible-enabled: Bridge.voice-connected; + accessible-checkable: true; + accessible-checked: Bridge.transmitting; + accessible-action-default => { Bridge.push-to-talk(!Bridge.transmitting); } Text { - text: Bridge.transmitting ? "Talking…" : "Hold to talk"; + text: Bridge.transmitting ? @tr("Talking…") : @tr("Hold to talk"); } ptt-area := TouchArea { enabled: Bridge.voice-connected; @@ -458,14 +1548,58 @@ export component MainWindow inherits Window { } } } + if Bridge.streams-available && Bridge.can-share: Button { + text: Bridge.share-state == "live" ? @tr("Sharing") : @tr("Share screen"); + primary: Bridge.share-state == "live"; + clicked => { open-share-dialog(); } + } Button { - text: "About"; - clicked => { show-about = true; } + text: @tr("Settings"); + clicked => { + Bridge.open-settings(); + settings-open = true; + } + } + Button { + text: @tr("About"); + clicked => { + Bridge.open-about(); + show-about = true; + } + } + } + } + if chrome && Bridge.crash-notice != "": Rectangle { + background: #3d2a0a; + accessible-role: groupbox; + accessible-label: @tr("Crash reports"); + HorizontalLayout { + padding: 6px; + padding-left: 10px; + spacing: 8px; + Text { + text: Bridge.crash-notice; + vertical-alignment: center; + horizontal-stretch: 1; + overflow: elide; + } + Button { + text: @tr("Open folder"); + clicked => { Bridge.open-crash-folder(); } + } + Button { + text: @tr("Delete"); + clicked => { Bridge.delete-crash-reports(); } + } + Button { + text: "×"; + accessible-label: @tr("Dismiss"); + clicked => { Bridge.dismiss-crash-notice(); } } } } HorizontalLayout { - if !narrow || pane == 2: ServerList { + if chrome && (!narrow || pane == 2): ServerList { // Fixed width beside the other panes, all the space alone. min-width: narrow ? 0px : 230px; max-width: narrow ? 100000px : 230px; @@ -479,17 +1613,31 @@ export component MainWindow inherits Window { editing = true; } } - if !narrow || pane == 0: ChannelTree { + if chrome && (!narrow || pane == 0): VerticalLayout { min-width: narrow ? 0px : 360px; max-width: narrow ? 100000px : 360px; horizontal-stretch: narrow ? 1 : 0; + ChannelTree { + vertical-stretch: 1; + client-clicked(id) => { + if (Bridge.open-client(id)) { + client-open = true; + } + } + } + if Bridge.streams-available: StreamsPanel { + vertical-stretch: 0; + manage-share => { open-share-dialog(); } + } } - if !narrow || pane == 1: ChatPanel { } + if (!narrow || pane == 1) && Bridge.viewer-open: StreamViewer { } + if chrome && (!narrow || pane == 1) && !Bridge.viewer-open: ChatPanel { } } // Status bar - Rectangle { + if chrome: Rectangle { height: 26px; background: #161b22; + accessible-role: content-info; HorizontalLayout { padding-left: 8px; padding-right: 8px; @@ -514,24 +1662,23 @@ export component MainWindow inherits Window { done => { editing = false; } } - if show-about: Rectangle { - background: #000000c0; - TouchArea { - clicked => { show-about = false; } - } - VerticalBox { - alignment: center; - Text { - text: "Unofficial TeamSpeak 3/6 compatible client. Not affiliated with TeamSpeak Systems GmbH."; - horizontal-alignment: center; - wrap: word-wrap; - } - AboutSlint { } - Text { - text: "Third-party licenses: see THIRD_PARTY_NOTICES. Click to close."; - horizontal-alignment: center; - color: #8b949e; - } + if sharing-dialog: ShareDialog { + form <=> share-form; + done => { sharing-dialog = false; } + } + + if settings-open: SettingsDialog { + done => { + settings-open = false; + Bridge.close-settings(); } } + + if client-open: ClientAudioDialog { + done => { client-open = false; } + } + + if show-about: AboutDialog { + done => { show-about = false; } + } }