diff --git a/app/.gitignore b/app/.gitignore index 4f96631..867224e 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -1,2 +1,3 @@ /target /dist +/.rhema diff --git a/app/Cargo.lock b/app/Cargo.lock index dd4a1bd..e19269a 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -1549,6 +1549,7 @@ dependencies = [ "tokio", "ureq", "uuid", + "windows", "winreg", ] diff --git a/app/Cargo.toml b/app/Cargo.toml index b11146f..5bec074 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -25,6 +25,11 @@ ureq = "3.5" [target.'cfg(windows)'.dependencies] winreg = "0.56" +windows = { version = "0.62", features = [ + "Win32_Foundation", + "Win32_System_Diagnostics_ToolHelp", + "Win32_System_Threading", +] } # Rune is patched in the workspace that builds it. A dependency's `[patch]` doesn't apply to # the app that depends on it, so these three copies (from rune's own vendor/) are repeated here. diff --git a/app/src/app.rs b/app/src/app.rs index 8cfb6a4..4752070 100644 --- a/app/src/app.rs +++ b/app/src/app.rs @@ -10,6 +10,7 @@ use crate::history::{self, QueueCategory, Timeline}; use crate::ipc::{self, Daemon}; use crate::os; use crate::portraits; +use crate::process; use crate::screens; use crate::settings::{AudioSource, AudioSourceType, Settings}; use crate::ui::{self, Paint, body, heading}; @@ -116,6 +117,13 @@ pub struct App { pub filter: Option, pub review: screens::review::Review, pub portraits: Option, + /// The icons of the processes the audio sources name, decoded from their executables. + pub icons: Option, + /// Which of those processes are running, refreshed while the audio tab is open. + pub processes: process::Processes, + pub processes_rx: Option>, + /// When the process table was last read, in the clock `poll` gets. + pub processes_at: f64, pub scroll: ui::ScrollBar, pub highlights_scroll: ui::ScrollBar, pub events_scroll: ui::ScrollBar, @@ -153,6 +161,10 @@ impl App { filter: None, review: screens::review::Review::default(), portraits: None, + icons: None, + processes: process::Processes::new(), + processes_rx: None, + processes_at: 0.0, scroll: ui::ScrollBar::new(), highlights_scroll: ui::ScrollBar::new(), events_scroll: ui::ScrollBar::new(), @@ -231,6 +243,23 @@ impl App { }, ]; self.form.apply(&settings); + // The sample sources read as a running process and one that is not, so a snapshot + // shows both states of the chip. + self.processes = settings + .audio + .capture_apps + .iter() + .map(|source| { + let running = source.device.eq_ignore_ascii_case("Discord.exe"); + ( + process::normalize(&source.device), + process::Found { + running, + path: None, + }, + ) + }) + .collect(); self.settings = Some(settings); } @@ -252,6 +281,46 @@ impl App { self.daemon.get_settings(); } + /// The process names the audio sources refer to, plus whatever is being typed into the + /// add dialog. + fn watch_names(&self) -> Vec { + let mut names: Vec = self + .form + .draft + .audio + .capture_apps + .iter() + .filter(|source| source.source_type == AudioSourceType::Application) + .map(|source| source.device.clone()) + .collect(); + if self.form.add_open { + let typed = self.form.source_device.text.trim(); + if !typed.is_empty() { + names.push(typed.to_string()); + } + } + names.sort(); + names.dedup(); + names + } + + /// Look at the process table on a thread of its own; `poll` picks the answer up. + pub fn refresh_processes(&mut self) { + if self.processes_rx.is_some() { + return; + } + let names = self.watch_names(); + if names.is_empty() { + self.processes.clear(); + return; + } + let (tx, rx) = channel(); + std::thread::spawn(move || { + let _ = tx.send(process::snapshot(names)); + }); + self.processes_rx = Some(rx); + } + /// Read the timelines on a thread of their own; `poll` picks the list up. pub fn refresh_games(&mut self) { if self.games_rx.is_some() { @@ -307,6 +376,7 @@ fn hide_window() { pub fn setup(app: &mut App, waker: rune::Waker) { app.waker = Some(waker.clone()); app.portraits = Some(portraits::Portraits::new(waker.clone())); + app.icons = Some(rune::ImageCache::new(waker.clone())); app.daemon.set_waker(waker.clone()); app.refresh_settings(); app.refresh_games(); @@ -447,6 +517,18 @@ impl App { } } + if let Some(rx) = &self.processes_rx { + match rx.try_recv() { + Ok(processes) => { + self.processes = processes; + self.processes_rx = None; + changed = true; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => self.processes_rx = None, + } + } + if let Some(rx) = &self.games_rx { match rx.try_recv() { Ok(games) => { @@ -491,6 +573,16 @@ impl App { self.last_status = t; self.daemon.get_status(); } + + // The audio tab says whether each process is up, so it reads the process table again + // every couple of seconds while it is on screen. + if self.screen == Screen::Settings + && (self.settings_tab == SettingsTab::Audio || self.form.add_open) + && t - self.processes_at >= 2.0 + { + self.processes_at = t; + self.refresh_processes(); + } // Keep the clock running so the status stays live even when nothing draws. tx.wake_after(Duration::from_millis(1000)); @@ -520,6 +612,10 @@ pub fn on_key(app: &mut App, event: &KeyEvent, _tx: &mut Tx) -> bool { app.screen = Screen::Settings; true } + (Key::Escape, _) if app.form.add_open => { + app.form.close_add(); + true + } (Key::Escape, _) if app.screen == Screen::Review => { screens::review::leave(app); app.screen = Screen::History; @@ -616,30 +712,32 @@ fn titlebar(p: Paint, app: &App) -> El { .font(heading(13.0)) .color(p.t.text), ); - let actions = row() - .key("actions") - .gap(8.0) - .center_y() - .child(ui::button( - p, - "refresh", - "Refresh", - false, - |app: &mut App| { - app.refresh_games(); - app.daemon.get_status(); - }, - )) - .child(ui::button( - p, - "open-settings", - "Settings", - false, - |app: &mut App| { - screens::review::leave(app); - app.screen = Screen::Settings; - }, - )); + let mut actions = row().key("actions").gap(8.0).center_y(); + // On the settings screen the title bar has nothing to offer: refreshing and opening + // settings again would only repeat what the screen already does. + if app.screen != Screen::Settings { + actions = actions + .child(ui::button( + p, + "refresh", + "Refresh", + false, + |app: &mut App| { + app.refresh_games(); + app.daemon.get_status(); + }, + )) + .child(ui::button( + p, + "open-settings", + "Settings", + false, + |app: &mut App| { + screens::review::leave(app); + app.screen = Screen::Settings; + }, + )); + } row() .key("titlebar") .h(48.0) @@ -706,7 +804,7 @@ pub fn view(app: &App, cx: &mut Cx) -> El { .child(titlebar(p, app)) .child(main) .child(statusbar(p, app)); - match app.screen { + let content = match app.screen { Screen::Review => window .child( app.highlights_scroll @@ -722,7 +820,13 @@ pub fn view(app: &App, cx: &mut Cx) -> El { "list-scroller" }, )), + }; + // The add-application dialog covers the whole window, title bar included. + let mut overlays = Vec::new(); + if app.screen == Screen::Settings && app.form.add_open { + screens::settings::add_dialog(app, p, &mut overlays); } + rune_kit::root(content, overlays) } /// Whether this is a headless run (`--snap out.png`, `--tree`, …) rather than a window. diff --git a/app/src/main.rs b/app/src/main.rs index f3c6839..5d8dc1b 100644 --- a/app/src/main.rs +++ b/app/src/main.rs @@ -12,6 +12,7 @@ mod history; mod ipc; mod os; mod portraits; +mod process; mod screens; mod settings; mod theme; @@ -60,6 +61,13 @@ fn main() { app.screen = app::Screen::Settings; app.settings_tab = app::SettingsTab::Audio; }), + ("add-app", |app| { + app.screen = app::Screen::Settings; + app.settings_tab = app::SettingsTab::Audio; + app.form.open_add(); + app.form.source_name = rune::TextEdit::new("Discord"); + app.form.source_device = rune::TextEdit::new("Discord.exe"); + }), ("daemon", |app| { app.screen = app::Screen::Settings; app.settings_tab = app::SettingsTab::Advanced; diff --git a/app/src/process.rs b/app/src/process.rs new file mode 100644 index 0000000..90c30cf --- /dev/null +++ b/app/src/process.rs @@ -0,0 +1,232 @@ +//! Which processes are running, and where their executable lives. +//! +//! The audio sources name a process (`Discord.exe`); the settings screen wants to say whether +//! that process is up and draw its icon. One snapshot of the process table answers both. + +use std::collections::HashMap; + +/// What the settings screen knows about one named process. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Found { + pub running: bool, + /// The executable to read the icon from, when the snapshot could open the process. + pub path: Option, +} + +/// Running processes by normalised name: lowercase, without the `.exe`. +pub type Processes = HashMap; + +/// `Discord.exe` and `discord` are the same process. +pub fn normalize(name: &str) -> String { + let name = name.trim().to_ascii_lowercase(); + name.strip_suffix(".exe").unwrap_or(&name).to_string() +} + +/// One pass over the process table, keeping only `names`. +/// +/// A name that is not running maps to a `Found` with `running: false`, so the screen can tell +/// "not running" from "not asked about yet". +pub fn snapshot(names: impl IntoIterator) -> Processes { + let wanted: HashMap = names + .into_iter() + .map(|name| (normalize(&name), Found::default())) + .collect(); + if wanted.is_empty() { + return wanted; + } + #[cfg(windows)] + { + windows_snapshot(wanted) + } + #[cfg(not(windows))] + { + wanted + } +} + +#[cfg(windows)] +fn windows_snapshot(mut wanted: Processes) -> Processes { + use windows::Win32::Foundation::CloseHandle; + use windows::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, + TH32CS_SNAPPROCESS, + }; + + // SAFETY: the snapshot handle is closed below, and `entry` is a plain struct the calls fill. + unsafe { + let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else { + return wanted; + }; + let mut entry = PROCESSENTRY32W { + dwSize: std::mem::size_of::() as u32, + ..Default::default() + }; + let mut more = Process32FirstW(snapshot, &mut entry).is_ok(); + while more { + if let Some(found) = wanted.get_mut(&normalize(&exe_name(&entry))) { + found.running = true; + if found.path.is_none() { + found.path = exe_path(entry.th32ProcessID); + } + } + // A process can exit mid-walk, which ends the enumeration early on some builds. + more = Process32NextW(snapshot, &mut entry).is_ok(); + } + let _ = CloseHandle(snapshot); + } + // A program that is not open has no process to read its icon from, so look where Windows + // keeps it. + for (name, found) in wanted.iter_mut() { + if found.path.is_none() { + found.path = locate(name); + } + } + wanted +} + +#[cfg(windows)] +fn exe_name(entry: &windows::Win32::System::Diagnostics::ToolHelp::PROCESSENTRY32W) -> String { + let len = entry + .szExeFile + .iter() + .position(|&c| c == 0) + .unwrap_or(entry.szExeFile.len()); + String::from_utf16_lossy(&entry.szExeFile[..len]) +} + +/// The full path of a process's executable, when it can be opened. +#[cfg(windows)] +fn exe_path(pid: u32) -> Option { + use windows::Win32::Foundation::CloseHandle; + use windows::Win32::System::Threading::{ + OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, + QueryFullProcessImageNameW, + }; + use windows::core::PWSTR; + + let mut buffer = [0u16; 512]; + let mut len = buffer.len() as u32; + // SAFETY: `buffer` outlives the call, and `len` carries its capacity in and the written + // length out. + unsafe { + let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?; + let query = QueryFullProcessImageNameW( + handle, + PROCESS_NAME_WIN32, + PWSTR(buffer.as_mut_ptr()), + &mut len, + ); + let _ = CloseHandle(handle); + query.ok()?; + } + Some(std::path::PathBuf::from(String::from_utf16_lossy( + &buffer[..len as usize], + ))) +} + +/// Where a program that is not running might be installed, so its icon can still be drawn. +/// +/// The search is bounded (a few thousand directories, five levels) and remembers its misses, so +/// a name costs at most one walk per run of the app. +fn locate(name: &str) -> Option { + use std::sync::{Mutex, OnceLock}; + static CACHE: OnceLock>>> = OnceLock::new(); + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + if let Some(hit) = cache.lock().ok()?.get(name) { + return hit.clone(); + } + let file = format!("{name}.exe"); + let roots = [ + "ProgramFiles", + "ProgramFiles(x86)", + "LOCALAPPDATA", + "APPDATA", + "ProgramData", + ]; + let mut budget = 20_000usize; + let found = roots + .iter() + .filter_map(|var| std::env::var_os(var).map(std::path::PathBuf::from)) + .find_map(|root| walk(&root, &file, 5, &mut budget)); + if let Ok(mut cache) = cache.lock() { + cache.insert(name.to_string(), found.clone()); + } + found +} + +fn walk( + dir: &std::path::Path, + file: &str, + depth: u32, + budget: &mut usize, +) -> Option { + if depth == 0 || *budget == 0 { + return None; + } + let mut below = Vec::new(); + for entry in std::fs::read_dir(dir).ok()?.flatten() { + *budget = budget.saturating_sub(1); + if *budget == 0 { + break; + } + let name = entry.file_name().to_string_lossy().to_ascii_lowercase(); + let path = entry.path(); + if name == file { + return Some(path); + } + if entry.file_type().is_ok_and(|kind| kind.is_dir()) { + below.push(path); + } + } + below + .into_iter() + .find_map(|dir| walk(&dir, file, depth - 1, budget)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_process_name_ignores_case_and_the_exe_suffix() { + assert_eq!(normalize("Discord.exe"), "discord"); + assert_eq!(normalize(" discord.EXE "), "discord"); + assert_eq!(normalize("chrome"), "chrome"); + assert_eq!(normalize(""), ""); + } + + #[test] + fn names_that_are_not_asked_about_are_not_in_the_snapshot() { + let found = snapshot(Vec::new()); + assert!(found.is_empty()); + } + + #[cfg(windows)] + #[test] + fn the_process_table_finds_this_test_binary() { + let exe = std::env::current_exe().expect("the test binary's path"); + let name = exe + .file_name() + .expect("the test binary's name") + .to_string_lossy() + .to_string(); + let found = snapshot(vec![name.clone()]); + let found = found + .get(&normalize(&name)) + .expect("the name was asked about"); + assert!(found.running, "{name} runs: this test is it"); + assert!( + found.path.as_ref().is_some_and(|path| path.is_file()), + "{name} resolves to its executable" + ); + } + + #[cfg(windows)] + #[test] + fn a_process_that_is_not_running_is_not_found() { + let found = snapshot(vec!["definitely-not-a-process-1f3a.exe".to_string()]); + let found = found.values().next().expect("the name was asked about"); + assert!(!found.running); + assert!(found.path.is_none()); + } +} diff --git a/app/src/screens/settings.rs b/app/src/screens/settings.rs index 5f99f14..de20dd0 100644 --- a/app/src/screens/settings.rs +++ b/app/src/screens/settings.rs @@ -1,7 +1,7 @@ //! Settings: a quick tab of everyday choices, then recording, audio and the daemon. use rune::tok::{radius, space, type_}; -use rune::{El, TextEdit, col, row, text}; +use rune::{Color, El, TextEdit, col, el, row, text}; use rune_kit::Select; use crate::app::{App, SettingsTab}; @@ -24,7 +24,7 @@ pub struct Form { pub bitrate: TextEdit, pub source_name: TextEdit, pub source_device: TextEdit, - pub source_type: AudioSourceType, + pub add_open: bool, } impl Form { @@ -40,7 +40,7 @@ impl Form { bitrate: TextEdit::new(draft.audio.bitrate.to_string()), source_name: TextEdit::new(""), source_device: TextEdit::new(""), - source_type: AudioSourceType::Application, + add_open: false, draft, loaded: false, dirty: false, @@ -103,6 +103,19 @@ impl Form { out } + /// Open the add-application dialog on empty fields. + pub fn open_add(&mut self) { + self.add_open = true; + self.open_select = None; + self.source_name = TextEdit::new(""); + self.source_device = TextEdit::new(""); + } + + /// Close the add-application dialog, whatever was typed. + pub fn close_add(&mut self) { + self.add_open = false; + } + pub fn choose(&mut self, key: &str, value: &str) { match key { "encoder" => { @@ -119,13 +132,6 @@ impl Form { "container" => self.draft.output.container = value.to_ascii_lowercase(), "log-level" => self.draft.daemon.log_level = value.to_ascii_lowercase(), "mic-device" => self.draft.audio.mic_device = Some(value.to_string()), - "source-type" => { - self.source_type = match value { - "Output device" => AudioSourceType::DeviceOutput, - "Input device" => AudioSourceType::DeviceInput, - _ => AudioSourceType::Application, - } - } _ => {} } self.dirty = true; @@ -136,7 +142,6 @@ const ENCODERS: [&str; 3] = ["NVIDIA NVENC", "AMD AMF", "x264 (Software)"]; const QUALITIES: [&str; 4] = ["Low", "Medium", "High", "Ultra"]; const CONTAINERS: [&str; 4] = ["mp4", "mkv", "mov", "flv"]; const LOG_LEVELS: [&str; 5] = ["trace", "debug", "info", "warn", "error"]; -const SOURCE_TYPES: [&str; 3] = ["Application", "Output device", "Input device"]; /// A row with a single-line field on the right. fn text_row( @@ -627,7 +632,7 @@ fn audio(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec, content: let mut sources = col().key("sources").gap(2.0); if a.capture_apps.is_empty() { sources = sources.child( - text("No applications yet. Add one below and its audio joins the clip.") + text("No applications yet. Add one and its audio joins the clip.") .key("sources-empty") .font(body(12.0)) .color(p.muted()) @@ -636,76 +641,7 @@ fn audio(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec, content: ); } for (index, source) in a.capture_apps.iter().enumerate() { - let id = source.id.clone(); - let volume = source.volume.unwrap_or(100); - sources = sources.child( - row() - .key(format!("source-{}", source.id)) - .h(48.0) - .px(space::S3) - .center_y() - .gap(space::S3) - .justify_between() - .radius(radius::MD) - .child( - col() - .key("source-labels") - .grow(1.0) - .gap(1.0) - .child( - text(source.name.clone()) - .key("name") - .font(type_::BODY) - .color(p.t.text), - ) - .child( - text(format!( - "{} · {}", - source.source_type.label(), - source.device - )) - .key("detail") - .font(body(11.0)) - .color(p.muted()), - ), - ) - .child( - row() - .key("source-volume") - .gap(space::S2) - .center_y() - .child(ui::slider( - p, - format!("volume-{}", source.id), - "Application volume", - volume, - move |app: &mut App, value| { - let payload = { - let Some(source) = - app.form.draft.audio.capture_apps.get_mut(index) - else { - return; - }; - source.volume = Some(value); - serde_json::to_value(&*source).ok() - }; - app.form.dirty = true; - if let Some(payload) = payload { - app.daemon.update_audio_source(payload); - } - }, - )), - ) - .child(ui::button( - p, - &format!("remove-{}", source.id), - "Remove", - false, - move |app: &mut App| { - app.daemon.remove_audio_source(&id); - }, - )), - ); + sources = sources.child(source_row(app, p, index, source)); } content @@ -777,100 +713,242 @@ fn audio(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec, content: mic_row(p, kit, layer, app, "mic-device"), ], )) - .child(ui::card( + .child(ui::card_action( p, Some("Applications"), - vec![sources, add_source(app, p, kit, layer)], + Some(ui::icon_button( + p, + "add-source", + "+", + "Add an application", + true, + |app: &mut App| app.form.open_add(), + )), + vec![sources], )) } -/// The row that adds an application source: a name, the process or device, and its kind. -fn add_source(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec) -> El { - let open = app.form.open_select == Some("source-type"); - let kind = Select::new("source-type", &SOURCE_TYPES) - .current(Some(app.form.source_type.label())) - .open(open) - .label("Type") - .width(170.0) - .on_toggle(|app: &mut App| { - app.form.open_select = if app.form.open_select == Some("source-type") { - None - } else { - Some("source-type") - }; - }) - .on_close(|app: &mut App| app.form.open_select = None) - .on_choose(|app: &mut App, value: &str, _: &mut rune::Tx| { - app.form.choose("source-type", value); - app.form.open_select = None; - }) - .build(kit, layer); - col() - .key("add-source") - .gap(space::S2) +/// One captured application: its icon, name, whether it is running, its volume and Remove. +fn source_row(app: &App, p: Paint, index: usize, source: &AudioSource) -> El { + let id = source.id.clone(); + let volume = source.volume.unwrap_or(100); + let mut row = row() + .key(format!("source-{}", source.id)) + .h(52.0) .px(space::S3) - .pb(space::S3) + .center_y() + .gap(space::S3) + .child(ui::process_icon(app, p, &source.device, 24.0)) .child( - text("Add an application") - .key("add-title") - .font(type_::SECTION) - .color(p.muted()), - ) - .child( - row() - .key("add-fields") - .gap(space::S3) - .center_y() - .child(labelled_field( - p, - "Name", - "source-name", - &app.form.source_name, - |app| &mut app.form.source_name, - )) - .child(labelled_field( - p, - "Process or device", - "source-device", - &app.form.source_device, - |app| &mut app.form.source_device, - )) - .child(kind) - .child(ui::button( - p, - "add-source-button", - "Add", - true, - |app: &mut App| { - let name = app.form.source_name.text.trim().to_string(); - let device = app.form.source_device.text.trim().to_string(); - if name.is_empty() || device.is_empty() { - app.notify_error( - "An audio source needs a name and a process or device", - ); - return; - } - let source = AudioSource { - id: String::new(), - name, - source_type: app.form.source_type, - device, - enabled: true, - volume: None, - }; - match serde_json::to_value(&source) { - Ok(value) => app.daemon.add_audio_source(value), - Err(e) => { - app.notify_error(format!("audio source did not serialize: {e}")) - } - } - }, - )), - ) + col() + .key("source-labels") + .grow(1.0) + .min_w(0.0) + .gap(1.0) + .child( + text(source.name.clone()) + .key("name") + .font(type_::BODY) + .color(p.t.text) + .truncate(), + ) + .child( + text(source_detail(source)) + .key("detail") + .font(body(11.0)) + .color(p.muted()) + .truncate(), + ), + ); + // Only a process source can be looked up; a device source names a device instead. + if source.source_type == AudioSourceType::Application + && let Some(found) = app + .processes + .get(&crate::process::normalize(&source.device)) + { + row = row.child(ui::process_state(p, found.running, 88.0)); + } + row.radius(radius::MD) + .child(ui::slider( + p, + format!("volume-{}", source.id), + "Application volume", + volume, + move |app: &mut App, value| { + let payload = { + let Some(source) = app.form.draft.audio.capture_apps.get_mut(index) else { + return; + }; + source.volume = Some(value); + serde_json::to_value(&*source).ok() + }; + app.form.dirty = true; + if let Some(payload) = payload { + app.daemon.update_audio_source(payload); + } + }, + )) + .child(ui::button( + p, + &format!("remove-{}", source.id), + "Remove", + false, + move |app: &mut App| { + app.daemon.remove_audio_source(&id); + }, + )) } -/// A field with its name above it, for a row of controls that has no room for setting labels. -fn labelled_field( +/// What a source captures, under its name in the list. +fn source_detail(source: &AudioSource) -> String { + match source.source_type { + AudioSourceType::Application => source.device.clone(), + other => format!("{} · {}", other.label(), source.device), + } +} + +/// Send the dialog's name and process to the daemon as a new application source. +fn submit_source(app: &mut App) { + let name = app.form.source_name.text.trim().to_string(); + let device = app.form.source_device.text.trim().to_string(); + if name.is_empty() || device.is_empty() { + return; + } + let source = AudioSource { + id: String::new(), + name, + source_type: AudioSourceType::Application, + device, + enabled: true, + volume: None, + }; + match serde_json::to_value(&source) { + Ok(value) => app.daemon.add_audio_source(value), + Err(e) => app.notify_error(format!("audio source did not serialize: {e}")), + } + app.form.close_add(); + app.refresh_processes(); +} + +/// The dialog the card's plus opens: what to call the application, and the process to listen +/// to. `app::view` draws it over the whole window, title bar included. +pub fn add_dialog(app: &App, p: Paint, layer: &mut Vec) { + let typed = app.form.source_device.text.trim(); + let found = app + .processes + .get(&crate::process::normalize(typed)) + .filter(|_| !typed.is_empty()); + let hint = match found { + Some(found) if found.running => "That process is running.".to_string(), + Some(_) => "That process is not running right now.".to_string(), + None => "The name Windows gives the program, for example Discord.exe.".to_string(), + }; + let valid = !app.form.source_name.text.trim().is_empty() && !typed.is_empty(); + let actions = row() + .key("dialog-actions") + .w_full() + .gap(space::S2) + .justify_end() + .child(ui::button( + p, + "add-cancel", + "Cancel", + false, + |app: &mut App| { + app.form.close_add(); + }, + )) + .child(if valid { + ui::button(p, "add-confirm", "Add", true, |app: &mut App| { + submit_source(app); + }) + } else { + ui::button_muted(p, "add-confirm", "Add") + }); + + let panel = col() + .key("add-dialog") + .role("dialog") + .label("Add an application") + .w(400.0) + .padding(space::S6) + .gap(space::S3) + .radius(radius::LG) + .fill(p.t.card) + .border(p.hair, p.t.card_border) + .shadow(4.0, 12.0, p.t.shadow) + .shadow(24.0, 48.0, p.t.shadow_soft) + .modal(true, |app: &mut App| app.form.close_add()) + .child( + row() + .key("dialog-header") + .w_full() + .justify_between() + .center_y() + .child( + text("Add an application") + .key("dialog-title") + .font(heading(15.0)) + .color(p.t.text), + ) + .child(ui::icon_button( + p, + "add-close", + "×", + "Close", + false, + |app: &mut App| app.form.close_add(), + )), + ) + .child( + text("Its audio is mixed into the clip beside the game's.") + .key("dialog-note") + .font(body(12.0)) + .color(p.muted()), + ) + .child(captioned_field( + p, + "Name", + "add-name", + &app.form.source_name, + |app| &mut app.form.source_name, + )) + .child(captioned_field( + p, + "Process", + "add-process", + &app.form.source_device, + |app| &mut app.form.source_device, + )) + .child( + text(hint) + .key("dialog-hint") + .font(body(11.0)) + .color(p.muted()), + ) + .child(actions); + + layer.push( + el().key("add-scrim") + .absolute(0.0, 0.0) + .w_full() + .h_full() + .fill(Color::BLACK.alpha(if app.dark { 0.55 } else { 0.28 })) + .a11y_hidden(), + ); + layer.push( + el().key("add-layer") + .absolute(0.0, 0.0) + .w_full() + .h_full() + .padding(16.0) + .center() + .child(panel), + ); +} + +/// A wide field under its own caption, for a dialog where labels do not fit beside it. +fn captioned_field( p: Paint, label: &'static str, key: &'static str, @@ -879,9 +957,19 @@ fn labelled_field( ) -> El { col() .key(key) + .w_full() .gap(space::S1) .child(text(label).key("caption").font(body(11.0)).color(p.muted())) - .child(ui::text_field(p, key, label, edit, to)) + .child(ui::text_field_width( + p, + key, + label, + 352.0, + rune::Align::Start, + edit, + to, + |_app| {}, + )) } fn advanced(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec, content: El) -> El { diff --git a/app/src/ui.rs b/app/src/ui.rs index 6ac0251..33d5cdb 100644 --- a/app/src/ui.rs +++ b/app/src/ui.rs @@ -51,6 +51,11 @@ pub fn body(size: f32) -> TextStyle { /// A titled card of rows with hairlines between them. pub fn card(p: Paint, title: Option<&str>, rows: Vec) -> El { + card_action(p, title, None, rows) +} + +/// [`card`] with a control in its header, such as the button that adds to the list below. +pub fn card_action(p: Paint, title: Option<&str>, action: Option, rows: Vec) -> El { let count = rows.len(); let mut inner = col() .key("card") @@ -75,13 +80,22 @@ pub fn card(p: Paint, title: Option<&str>, rows: Vec) -> El { } let mut section = col().gap(space::S2); if let Some(title) = title { - section = section.child( - text(title) - .key("header") - .font(type_::SECTION) - .color(p.t.text_secondary) - .ml(space::S3), - ); + let mut header = row() + .key("header") + .w_full() + .center_y() + .justify_between() + .child( + text(title) + .key("header-label") + .font(type_::SECTION) + .color(p.t.text_secondary) + .ml(space::S3), + ); + if let Some(action) = action { + header = header.child(action); + } + section = section.child(header); } section.child(inner) } @@ -283,12 +297,30 @@ pub fn text_field( label: &str, edit: &rune::TextEdit, to: fn(&mut App) -> &mut rune::TextEdit, +) -> El { + text_field_width(p, key, label, 220.0, rune::Align::End, edit, to, |app| { + app.form.dirty = true; + }) +} + +/// [`text_field`] at a given width and text alignment; a dialog field is wide and starts at its +/// left edge, where typing begins. +#[allow(clippy::too_many_arguments)] // the columns of a field: size, alignment and what typing does +pub fn text_field_width( + p: Paint, + key: &'static str, + label: &str, + width: f32, + align: rune::Align, + edit: &rune::TextEdit, + to: fn(&mut App) -> &mut rune::TextEdit, + on_input: fn(&mut App), ) -> El { let focused = edit.focused; row() .key(key) .h(28.0) - .w(220.0) + .w(width) .px(8.0) .center_y() .radius(radius::MD) @@ -308,10 +340,10 @@ pub fn text_field( .w_full() .label(label) .color(p.t.text) - .align(rune::Align::End) + .align(align) .caret(p.t.text, p.accent.alpha(0.3)) .on_edit(to) - .on_input_change(|app: &mut App, _| app.form.dirty = true), + .on_input_change(move |app: &mut App, _| on_input(app)), ) } @@ -390,6 +422,137 @@ pub fn button( ) } +/// A small square button holding one glyph, for the corner of a card or a dialog. +pub fn icon_button( + p: Paint, + key: &str, + glyph: &str, + label: &str, + primary: bool, + on_press: impl Fn(&mut App) + Send + Sync + 'static, +) -> El { + el().key(key) + .role("button") + .label(label) + .focusable(true) + .size(24.0, 24.0) + .center() + .radius(radius::MD) + .fill(if primary { + p.accent.alpha(0.14) + } else { + Color::TRANSPARENT + }) + .border( + p.hair, + if primary { + p.accent.alpha(0.32) + } else { + Color::TRANSPARENT + }, + ) + .hover(p.t.hover) + .press(p.t.press) + .on_press(on_press) + .child( + text(glyph) + .key("glyph") + .font(body(if primary { 16.0 } else { 15.0 })) + .color(if primary { p.accent } else { p.muted() }) + .a11y_hidden(), + ) +} + +/// A primary button with nothing to do yet, for a dialog whose fields are still empty. +pub fn button_muted(p: Paint, key: &str, label: &str) -> El { + el().key(key) + .role("button") + .label(label) + .disabled(true) + .h(28.0) + .px(14.0) + .center() + .radius(radius::MD) + .fill(p.accent.alpha(0.28)) + .child( + text(label) + .key("label") + .font(type_::LABEL) + .color(p.accent_ink.alpha(0.55)) + .a11y_hidden(), + ) +} + +/// A process's icon as Windows draws it for the executable, with its initial until the icon is +/// decoded and for processes whose executable has none. +pub fn process_icon(app: &App, p: Paint, process: &str, size: f32) -> El { + let radius = (size * 0.22).max(2.0); + let initial = process + .trim() + .chars() + .next() + .map(|c| c.to_ascii_uppercase().to_string()) + .unwrap_or_else(|| "?".to_string()); + let image = app + .processes + .get(&crate::process::normalize(process)) + .and_then(|found| found.path.as_deref()) + .and_then(|path| { + app.icons + .as_ref() + .map(|icons| icons.app_icon_scaled(path, size, p.scale)) + }); + let tile = el() + .key("process-icon") + .size(size, size) + .radius(radius) + .fill(p.t.control_off) + .a11y_hidden(); + match image { + Some(image) => tile.child( + el().key("process-image") + .w_full() + .h_full() + .radius(radius) + .pixels(image.pixels()), + ), + None => tile.child( + text(initial) + .key("initial") + .font(body(size * 0.52)) + .color(p.muted()) + .center(), + ), + } +} + +/// Whether a process is up: a chip beside its name in the list. +pub fn process_state(p: Paint, running: bool, width: f32) -> El { + let color = if running { p.success } else { p.muted() }; + row() + .key("process-state") + .w(width) + .h(20.0) + .px(8.0) + .gap(6.0) + .center_y() + .radius(radius::MD) + .fill(color.alpha(0.12)) + .child( + el().key("state-dot") + .size(6.0, 6.0) + .radius(3.0) + .fill(color) + .a11y_hidden(), + ) + .child( + text(if running { "Running" } else { "Not found" }) + .key("state-label") + .font(body(10.5)) + .color(color), + ) +} + /// A coloured dot used for status. pub fn dot(color: Color) -> El { el().key("dot")