From c5cb407481e19bbadfa4c02dc900c1e3d1d2aa23 Mon Sep 17 00:00:00 2001 From: X4Lo Date: Sun, 15 Nov 2026 21:25:10 +0000 Subject: [PATCH] feat: volume sliders, output device switching, About credits (1.1.0) - Per-app volume slider and a system volume card (slider + mute) - Default output device picker; per-app output device picker (Windows via IPolicyConfig / IAudioPolicyConfigFactory, Linux via sink moves; macOS has no per-app routing API) - Slider commands are coalesced on the audio thread - Fix the Windows title-bar and taskbar icon (set via winit attributes) - About: "by X4Lo" and a GitHub link - README: app icon above the title - --list prints output devices and system volume - CI: run on master and on manual dispatch --- .github/workflows/ci.yml | 3 +- Cargo.lock | 3 +- Cargo.toml | 9 +- README.md | 15 +- docs/architecture.md | 9 +- docs/assets/icon.png | Bin 0 -> 4480 bytes docs/design-decisions.md | 12 +- src/app.rs | 187 ++++++++++++++++++++---- src/audio/linux.rs | 122 +++++++++++++++- src/audio/macos.rs | 164 ++++++++++++++++++++- src/audio/mod.rs | 82 +++++++++-- src/audio/null.rs | 4 +- src/audio/windows.rs | 305 +++++++++++++++++++++++++++++++++++++-- src/audio/worker.rs | 129 ++++++++++++++++- src/main.rs | 24 ++- src/platform.rs | 16 ++ src/ui/mod.rs | 20 +++ src/ui/toast.rs | 2 +- ui/main.slint | 281 +++++++++++++++++++++++++++++------- ui/widgets.slint | 191 ++++++++++++++++++++++++ 20 files changed, 1440 insertions(+), 138 deletions(-) create mode 100644 docs/assets/icon.png diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 490035e..5062809 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,7 +2,8 @@ name: CI on: push: - branches: [main] + branches: [main, master] + workflow_dispatch: pull_request: env: diff --git a/Cargo.lock b/Cargo.lock index af722be..cc4db2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1772,7 +1772,7 @@ checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144" [[package]] name = "hushkey" -version = "1.0.0" +version = "1.1.0" dependencies = [ "auto-launch", "directories", @@ -1789,6 +1789,7 @@ dependencies = [ "toml", "tray-icon", "windows", + "windows-core", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index a703832..37eed2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hushkey" -version = "1.0.0" +version = "1.1.0" edition = "2021" rust-version = "1.82" description = "Global hotkeys to instantly mute/unmute individual apps — or everything at once." @@ -32,9 +32,16 @@ log = "0.4" env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] } [target.'cfg(target_os = "windows")'.dependencies] +# windows-core is needed directly by the `#[interface]` macro (private policy-config COM interfaces). +windows-core = "0.62" windows = { version = "0.62", features = [ "Win32_Foundation", + "Win32_Devices_FunctionDiscovery", + "Win32_Devices_Properties", "Win32_Media_Audio", + "Win32_Media_Audio_Endpoints", + "Win32_System_Variant", + "Win32_UI_Shell_PropertiesSystem", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Threading", diff --git a/README.md b/README.md index 5ad72cc..4a51341 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@
+HushKey icon + # HushKey **One keystroke to mute any app. One more to mute everything.** @@ -9,7 +11,7 @@ Bind global shortcuts to individual applications' audio and toggle them instantl [![License: MIT](https://img.shields.io/badge/License-MIT-7b6bff.svg)](LICENSE.md) ![Platforms](https://img.shields.io/badge/platforms-Windows%20%7C%20macOS%20%7C%20Linux-5b49f2) ![Rust](https://img.shields.io/badge/rust-stable-orange) - +![Built with Claude Opus 5.5](https://img.shields.io/badge/built%20with-Claude%20Opus%205.5-orange) HushKey main window @@ -22,6 +24,7 @@ Bind global shortcuts to individual applications' audio and toggle them instantl - **Per-app mute shortcuts.** Every app with an audio session (playing *or* idle) shows up; click **Set shortcut**, press a combo, done. The same shortcut toggles mute/unmute. - **Mute All.** One shortcut silences every app. Press it again to restore *exactly* the previous state — apps you had muted yourself stay muted. An optional second shortcut can be set to restore only. Apps that start playing while Mute All is on are silenced too. - **Works everywhere.** Shortcuts are system-wide and fire while HushKey is hidden in the tray and while games or fullscreen apps have focus. +- **Volume and output devices.** A slider for every app and for the system volume, plus a picker to switch the default output device or send a single app to another device (e.g. Discord to the headset, music to the speakers). - **Instant feedback.** A small, click-through on-screen confirmation (it never steals focus from your game), plus a tray-icon flash. - **Light on resources.** Native Rust with a software-rendered UI — no browser engine. The window is destroyed when closed, so the tray-resident app holds only the tray icon, the hotkey listener and an idle audio thread. Idle CPU is zero: nothing polls while the window is hidden. - **Safe muting.** Uses the OS mixer's own mute flag rather than setting volume to 0, so your volume levels are never lost — even if HushKey crashes. @@ -35,6 +38,8 @@ Bind global shortcuts to individual applications' audio and toggle them instantl | Detect apps with audio | ✅ WASAPI sessions | ✅ Core Audio process objects | ✅ PulseAudio / PipeWire sink inputs | | Per-app mute | ✅ | ✅ via process taps | ✅ | | Per-app volume level | ✅ | ❌ no public API ([why](docs/design-decisions.md#macos-per-app-audio)) | ✅ | +| Per-app output device | ✅ | ❌ no public API | ✅ | +| System volume & default device | ✅ | ✅ | ✅ | | Global shortcuts | ✅ | ✅ | ✅ X11 · ⚠️ Wayland ([details](docs/design-decisions.md#wayland-global-shortcuts)) | | Tray icon | ✅ | ✅ menu bar | ✅ StatusNotifierItem | | Status | Tested on hardware | Compile-checked, needs testers | Compile-checked, needs testers | @@ -92,10 +97,10 @@ Command line: `hushkey --minimized` starts in the tray; `hushkey --list` prints - [Design decisions](docs/design-decisions.md) — why Slint, platform limitations and workarounds - [Contributing](CONTRIBUTING.md) +## Credits + +Developed by X4Lo with the help of **Claude Opus 5.5** (Anthropic), which wrote the code and documentation from X4Lo's specification. + ## License [MIT](LICENSE.md). The UI is built with [Slint](https://slint.dev), used under its Royalty-free Desktop license (attribution is shown in the app's About section). - ---- - -HushKey was created using Claude Opus 5.5. diff --git a/docs/architecture.md b/docs/architecture.md index fc67447..9df23b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -45,12 +45,19 @@ HushKey is a single Rust binary with four layers. Only `src/audio/{windows,macos ```rust pub trait AudioController { fn backend_name(&self) -> &'static str; - fn capabilities(&self) -> Capabilities; // per_app_volume / per_app_mute + fn capabilities(&self) -> Capabilities; // per-app volume/mute/device, master volume, devices fn list_audio_apps(&mut self) -> AudioResult>; fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()>; fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()>; fn mute_all(&mut self) -> AudioResult; // default impl fn restore_all(&mut self, snapshot: &MuteSnapshot) -> AudioResult<()>; // default impl + // Optional; the defaults return Unsupported / nothing: + fn output_devices(&mut self) -> AudioResult>; + fn set_default_output_device(&mut self, id: &str) -> AudioResult<()>; + fn master_volume(&mut self) -> AudioResult; + fn set_master_volume(&mut self, volume: f32) -> AudioResult<()>; + fn set_master_mute(&mut self, muted: bool) -> AudioResult<()>; + fn set_app_output_device(&mut self, app: &str, device: Option<&str>) -> AudioResult<()>; fn app_icon(&mut self, app: &AudioApp) -> Option { None } fn platform_note(&self) -> Option<&'static str> { None } } diff --git a/docs/assets/icon.png b/docs/assets/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..8519f30eaae89a16670d2bd67233d1275736486a GIT binary patch literal 4480 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 I>~)LyAGR~@9smFU literal 0 HcmV?d00001 diff --git a/docs/design-decisions.md b/docs/design-decisions.md index 2948b4a..58db4dd 100644 --- a/docs/design-decisions.md +++ b/docs/design-decisions.md @@ -31,7 +31,11 @@ The original spec described muting as "set volume to 0, restore the previous vol - If HushKey crashes or is killed while apps are muted, nothing is stuck at 0%. The user unmutes in the system mixer as usual. On macOS, taps are released automatically when the process exits. - The OS mixer UI shows the app as muted, which matches what the user sees in HushKey. -`set_app_volume` is still implemented on Windows and Linux as part of the backend contract. +Volume sliders are independent of the mute flag: moving a slider changes the level, and a muted app stays muted. Slider drags send a command per mouse move; the audio thread coalesces them so only the latest level is applied, and the UI updates optimistically so the knob never jumps. + +## Output devices + +The Apps page has a system-volume card with a picker for the default output device, and every app row has its own device picker ("System default" or a specific device). HushKey doesn't store these choices: the OS already persists them per app (Windows' "App volume and device preferences", PulseAudio's stream-restore module / PipeWire), so they keep working without HushKey running. ## Stable app identity @@ -62,7 +66,9 @@ macOS has **no public API to change another process's volume**. The CoreAudio HA **HushKey uses option 2.** As a result: - ✅ Per-app **mute/unmute** works (that's all HushKey's shortcuts need). -- ❌ Per-app **volume levels** are not possible. The backend reports `per_app_volume: false`, the UI hides volume bars, and `set_app_volume` returns `Unsupported` for values between 0 and 1. It never fakes a level. +- ❌ Per-app **volume levels** are not possible. The backend reports `per_app_volume: false`, the UI hides volume sliders, and `set_app_volume` returns `Unsupported` for values between 0 and 1. It never fakes a level. +- ❌ Per-app **output devices** are not possible either (no public API to reroute another process). The backend reports `per_app_device: false` and the UI hides the per-app picker. +- ✅ **System volume**, system mute and switching the **default output device** use public Core Audio properties and work normally. - Requires **macOS 14.2+**. The tap functions are resolved with `dlsym` at runtime, so the binary still launches on older macOS. There, apps are listed read-only and a banner explains why. - Requires the **Screen & System Audio Recording** permission. The app bundle must declare `NSAudioCaptureUsageDescription` (see [building.md](building.md#macos)). - Apps are grouped by their outermost `.app` bundle, so helper processes (e.g. Chrome's renderer helpers) are muted together. When an app spawns a new helper while muted, the tap is rebuilt on the next refresh. @@ -80,3 +86,5 @@ GNOME Shell doesn't show StatusNotifierItem icons without an extension. If no tr ### Windows The Windows backend is fully native. Sessions are enumerated on every active output device, not just the default one, so apps routed to a headset or virtual device are found. Protected processes HushKey can't open are still controllable; they're listed as "Process " with a PID-based key, which can't be bound persistently. + +Changing the default output device and an app's output device has **no public Windows API**, even though the Settings app does both. HushKey uses the same undocumented COM interfaces as EarTrumpet and SoundSwitch: `IPolicyConfig::SetDefaultEndpoint` (stable since Vista) and `IAudioPolicyConfigFactory::SetPersistedDefaultAudioEndpoint` (Windows 10 1803+; its IID changed in 21H2, so both IIDs are tried). If the per-app interface can't be created, the backend reports `per_app_device: false` and the per-app pickers are hidden. Some apps only switch device when they next open an audio stream (e.g. on the next track or after a restart); that's how Windows itself behaves too. System sounds can't be rerouted. diff --git a/src/app.rs b/src/app.rs index 2edc793..eca4f11 100644 --- a/src/app.rs +++ b/src/app.rs @@ -6,11 +6,11 @@ //! surfaces, render buffers or UI trees. use crate::audio::worker::{self, AudioCommand, AudioEvent, AudioHandle}; -use crate::audio::{AudioApp, Capabilities}; +use crate::audio::{AudioApp, Capabilities, MasterVolume, OutputDevice}; use crate::config::{Config, ConfigStore, Theme}; use crate::hotkeys::{capture_from_key_event, Accelerator, Capture, HotkeyAction, Hotkeys}; use crate::platform; -use crate::ui::icon::{self, IconState}; +use crate::ui::icon::IconState; use crate::ui::toast::ToastPresenter; use crate::ui::tray::{Tray, TrayCommand}; use crate::{AppRow, MainWindow}; @@ -23,6 +23,7 @@ use std::time::Duration; const REFRESH_EVERY: Duration = Duration::from_millis(1500); const TARGET_ALL: &str = "@all"; const TARGET_RESTORE: &str = "@restore"; +const SYSTEM_DEFAULT_LABEL: &str = "System default"; thread_local! { static APP: RefCell>> = const { RefCell::new(None) }; @@ -49,6 +50,11 @@ pub struct App { rows: Rc>, apps: RefCell>, icons: RefCell>, + devices: RefCell>, + master: Cell>, + /// Device names for the system picker, and "System default" + names for app pickers. + device_names: Rc>, + app_device_options: Rc>, all_muted: Cell, caps: Cell, backend: RefCell, @@ -98,8 +104,12 @@ impl App { rows: Rc::new(VecModel::default()), apps: RefCell::default(), icons: RefCell::default(), + devices: RefCell::default(), + master: Cell::new(None), + device_names: Rc::new(VecModel::default()), + app_device_options: Rc::new(VecModel::from(vec![SharedString::from(SYSTEM_DEFAULT_LABEL)])), all_muted: Cell::new(false), - caps: Cell::new(Capabilities { per_app_volume: true, per_app_mute: true }), + caps: Cell::new(Capabilities { per_app_volume: true, per_app_mute: true, ..Capabilities::default() }), backend: RefCell::new("starting…".into()), platform_note: RefCell::default(), capturing: RefCell::new(None), @@ -231,6 +241,8 @@ impl App { w.set_version(env!("CARGO_PKG_VERSION").into()); w.set_config_path(self.store.path().display().to_string().into()); w.set_apps(ModelRc::from(self.rows.clone())); + w.set_output_devices(ModelRc::from(self.device_names.clone())); + w.set_app_device_options(ModelRc::from(self.app_device_options.clone())); w.window().on_close_requested(|| { // Can't drop the component from inside its own callback; do it next tick. @@ -264,6 +276,24 @@ impl App { w.on_dismiss_status(|| { with_app(|a| a.set_status("", false)); }); + w.on_set_app_volume(|key, v| { + with_app(|a| a.set_app_volume(key.as_str(), v)); + }); + w.on_pick_app_device(|key, i| { + with_app(|a| a.pick_app_device(key.as_str(), i)); + }); + w.on_set_master_volume(|v| { + with_app(|a| a.set_master_volume(v)); + }); + w.on_toggle_master_mute(|| { + with_app(|a| a.toggle_master_mute()); + }); + w.on_pick_default_device(|i| { + with_app(|a| a.pick_default_device(i)); + }); + w.on_open_url(|url| { + platform::open_url(url.as_str()); + }); w.on_open_config_dir(|| { with_app(|a| { if let Some(dir) = a.store.path().parent() { @@ -299,7 +329,11 @@ impl App { fn push_all(&self, w: &MainWindow) { w.set_backend(self.backend.borrow().as_str().into()); w.set_platform_note(self.platform_note.borrow().as_str().into()); - w.set_show_volume(self.caps.get().per_app_volume); + let caps = self.caps.get(); + w.set_show_volume(caps.per_app_volume); + w.set_show_app_device(caps.per_app_device); + w.set_show_master_volume(caps.master_volume && self.master.get().is_some()); + w.set_show_output_devices(caps.output_devices && !self.devices.borrow().is_empty()); w.set_all_muted(self.all_muted.get()); let (msg, err) = self.status.borrow().clone(); w.set_status(msg.into()); @@ -308,9 +342,98 @@ impl App { w.set_hotkey_hint("Press a combo · Esc cancels · Backspace clears".into()); self.push_settings_to(w); self.push_shortcuts_to(w); + self.push_output_to(w); self.sync_rows(); } + fn push_output_to(&self, w: &MainWindow) { + let caps = self.caps.get(); + let master = self.master.get(); + w.set_show_master_volume(caps.master_volume && master.is_some()); + w.set_show_output_devices(caps.output_devices && !self.devices.borrow().is_empty()); + w.set_master_volume(master.and_then(|m| m.volume).unwrap_or(-1.0)); + w.set_master_muted(master.is_some_and(|m| m.muted)); + let devices = self.devices.borrow(); + w.set_default_device_index(devices.iter().position(|d| d.is_default).map_or(-1, |i| i as i32)); + } + + /// Rebuild the picker models only when the device set actually changed. + fn sync_device_models(&self) { + let devices = self.devices.borrow(); + let names: Vec = devices.iter().map(|d| SharedString::from(d.name.as_str())).collect(); + let current: Vec = self.device_names.iter().collect(); + if current != names { + let mut options = Vec::with_capacity(names.len() + 1); + options.push(SharedString::from(SYSTEM_DEFAULT_LABEL)); + options.extend(names.iter().cloned()); + self.device_names.set_vec(names); + self.app_device_options.set_vec(options); + } + } + + // ── Volume & devices ─────────────────────────────────────────────────────── + // The UI is updated optimistically; the next refresh confirms what the OS did. + + fn set_app_volume(&self, key: &str, volume: f32) { + if let Some(a) = self.apps.borrow_mut().iter_mut().find(|a| a.key == key) { + a.volume = Some(volume); + } + self.sync_rows(); + self.send(AudioCommand::SetAppVolume { key: key.to_owned(), volume }); + } + + fn pick_app_device(&self, key: &str, index: i32) { + let device = if index <= 0 { + None + } else { + match self.devices.borrow().get(index as usize - 1) { + Some(d) => Some(d.id.clone()), + None => return, + } + }; + if let Some(a) = self.apps.borrow_mut().iter_mut().find(|a| a.key == key) { + a.device = device.clone(); + } + self.sync_rows(); + self.send(AudioCommand::SetAppDevice { key: key.to_owned(), device }); + } + + fn set_master_volume(&self, volume: f32) { + if let Some(mut m) = self.master.get() { + m.volume = Some(volume); + self.master.set(Some(m)); + } + if let Some(w) = self.ui() { + self.push_output_to(&w); + } + self.send(AudioCommand::SetMasterVolume(volume)); + } + + fn toggle_master_mute(&self) { + let Some(mut m) = self.master.get() else { return }; + m.muted = !m.muted; + self.master.set(Some(m)); + if let Some(w) = self.ui() { + self.push_output_to(&w); + } + self.send(AudioCommand::SetMasterMute(m.muted)); + } + + fn pick_default_device(&self, index: i32) { + let id = { + let mut devices = self.devices.borrow_mut(); + let Some(id) = devices.get(index.max(0) as usize).map(|d| d.id.clone()) else { return }; + for d in devices.iter_mut() { + d.is_default = d.id == id; + } + id + }; + if let Some(w) = self.ui() { + self.push_output_to(&w); + } + self.send(AudioCommand::SetDefaultDevice(id)); + } + fn push_settings(&self) { if let Some(w) = self.ui() { self.push_settings_to(&w); @@ -348,27 +471,19 @@ impl App { let cfg = self.cfg.borrow(); let apps = self.apps.borrow(); let icons = self.icons.borrow(); + let devices = self.devices.borrow(); let caps = self.caps.get(); let mut rows: Vec = Vec::with_capacity(apps.len() + cfg.bindings.len()); for a in apps.iter() { - let status = if a.muted { - "Muted".to_owned() - } else if let (true, Some(v)) = (caps.per_app_volume, a.volume) { - format!("Volume {}%", (v * 100.0).round()) - } else { - "Active".to_owned() - }; - rows.push(make_row( - &a.key, - &a.name, - &format!("{status} · {}", a.key), - true, - a.muted, - a.volume, - &cfg, - &icons, - )); + let status = if a.muted { "Muted" } else { "Active" }; + let mut row = + make_row(&a.key, &a.name, &format!("{status} · {}", a.key), true, a.muted, a.volume, &cfg, &icons); + row.volume = if caps.per_app_volume { a.volume.unwrap_or(-1.0) } else { -1.0 }; + row.routable = a.routable; + row.device_index = + a.device.as_ref().and_then(|id| devices.iter().position(|d| &d.id == id)).map_or(0, |i| i as i32 + 1); + rows.push(row); } // Bound apps that aren't running stay visible so their shortcut can be edited. for b in &cfg.bindings { @@ -419,6 +534,18 @@ impl App { *self.apps.borrow_mut() = apps; self.sync_rows(); } + AudioEvent::Output { devices, master } => { + let changed = *self.devices.borrow() != devices; + *self.devices.borrow_mut() = devices; + self.master.set(master); + if changed { + self.sync_device_models(); + self.sync_rows(); // device indices shift when devices come and go + } + if let Some(w) = self.ui() { + self.push_output_to(&w); + } + } AudioEvent::Icon { key, icon } => { self.icons.borrow_mut().insert(key, crate::ui::image_from_icon(&icon)); self.sync_rows(); @@ -628,21 +755,17 @@ impl App { } } -/// Title-bar theme (dark title bar on Windows 10/11, appearance on macOS) and window icon. +/// Title-bar theme (dark title bar on Windows 10/11, appearance on macOS) and window icons. +/// The icons are also set at window creation (`ui::with_app_icons`); setting them again +/// here covers windows that already existed. fn apply_native_chrome(w: &slint::winit_030::winit::window::Window, dark: bool) { - use slint::winit_030::winit::window::{Icon, Theme as WinitTheme}; + use slint::winit_030::winit::window::Theme as WinitTheme; w.set_theme(Some(if dark { WinitTheme::Dark } else { WinitTheme::Light })); - // Small icon: title bar / Alt+Tab. - if let Ok(icon) = Icon::from_rgba(icon::render(32, IconState::Normal), 32, 32) { - w.set_window_icon(Some(icon)); - } - // Windows uses a separate "big" icon for the taskbar; winit only sets it on request. + w.set_window_icon(crate::ui::winit_icon(32)); #[cfg(target_os = "windows")] { use slint::winit_030::winit::platform::windows::WindowExtWindows; - if let Ok(icon) = Icon::from_rgba(icon::render(64, IconState::Normal), 64, 64) { - w.set_taskbar_icon(Some(icon)); - } + w.set_taskbar_icon(crate::ui::winit_icon(64)); } } @@ -674,5 +797,7 @@ fn make_row( muted, volume: volume.unwrap_or(-1.0), shortcut: label(cfg.binding_for(key).map(|b| b.hotkey.as_str())).into(), + routable: false, + device_index: 0, } } diff --git a/src/audio/linux.rs b/src/audio/linux.rs index f2a9894..a3f7314 100644 --- a/src/audio/linux.rs +++ b/src/audio/linux.rs @@ -3,12 +3,14 @@ //! //! Every playback stream an app opens is a *sink input*; that includes paused/corked //! streams, so idle-but-registered apps show up too. Full per-app volume and mute are -//! natively supported. +//! natively supported. Output devices are *sinks*: system volume is the default sink's +//! volume, and per-app routing moves the app's sink inputs (PulseAudio's stream-restore +//! module, and PipeWire, remember the choice per app). //! //! Uses the single-threaded standard mainloop driven synchronously from the audio worker //! thread: each call issues an operation and iterates the loop until it completes. -use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities}; +use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, MasterVolume, OutputDevice}; use libpulse_binding as pulse; use pulse::callbacks::ListResult; use pulse::context::{Context, FlagSet, State}; @@ -29,6 +31,17 @@ struct Input { muted: bool, volume: f32, channels: u8, + sink: u32, +} + +#[derive(Clone)] +struct Sink { + index: u32, + name: String, + description: String, + volume: f32, + muted: bool, + channels: u8, } pub struct PulseController { @@ -95,6 +108,7 @@ impl PulseController { muted: i.mute, volume: i.volume.avg().0 as f32 / Volume::NORMAL.0 as f32, channels: i.volume.len(), + sink: i.sink, }); } }); @@ -103,6 +117,46 @@ impl PulseController { Ok(v) } + fn sinks(&mut self) -> AudioResult> { + let out: Rc>> = Rc::default(); + let sink = out.clone(); + let op = self.context.introspect().get_sink_info_list(move |r| { + if let ListResult::Item(i) = r { + let name = i.name.as_deref().unwrap_or_default().to_owned(); + sink.borrow_mut().push(Sink { + index: i.index, + description: i.description.as_deref().filter(|d| !d.is_empty()).unwrap_or(&name).to_owned(), + name, + volume: i.volume.avg().0 as f32 / Volume::NORMAL.0 as f32, + muted: i.mute, + channels: i.volume.len(), + }); + } + }); + self.wait(op)?; + let v = out.borrow().clone(); + Ok(v) + } + + fn default_sink_name(&mut self) -> AudioResult> { + let out: Rc>> = Rc::default(); + let sink = out.clone(); + let op = self.context.introspect().get_server_info(move |info| { + *sink.borrow_mut() = info.default_sink_name.as_deref().map(str::to_owned); + }); + self.wait(op)?; + let v = out.borrow().clone(); + Ok(v) + } + + fn default_sink(&mut self) -> AudioResult { + let name = self.default_sink_name()?; + let sinks = self.sinks()?; + name.and_then(|n| sinks.iter().find(|s| s.name == n).cloned()) + .or_else(|| sinks.first().cloned()) + .ok_or_else(|| backend("no output device")) + } + fn for_each_input_of( &mut self, app: &str, @@ -126,10 +180,18 @@ impl AudioController for PulseController { } fn capabilities(&self) -> Capabilities { - Capabilities { per_app_volume: true, per_app_mute: true } + Capabilities { + per_app_volume: true, + per_app_mute: true, + per_app_device: true, + master_volume: true, + output_devices: true, + } } fn list_audio_apps(&mut self) -> AudioResult> { + let sinks = self.sinks().unwrap_or_default(); + let default_sink = self.default_sink_name().ok().flatten(); let mut grouped: BTreeMap> = BTreeMap::new(); for i in self.inputs()? { grouped.entry(i.key.clone()).or_default().push(i); @@ -139,7 +201,16 @@ impl AudioController for PulseController { .map(|(key, ins)| { let mut pids: Vec = ins.iter().map(|i| i.pid).filter(|p| *p != 0).collect(); pids.dedup(); + // PulseAudio doesn't say whether a stream *follows* the default; treat a + // stream on the default sink as following it, anything else as routed. + let device = sinks + .iter() + .find(|s| s.index == ins[0].sink) + .map(|s| s.name.clone()) + .filter(|name| Some(name) != default_sink.as_ref()); AudioApp { + device, + routable: true, name: ins[0].name.clone(), volume: Some(ins.iter().map(|i| i.volume).sum::() / ins.len() as f32), muted: ins.iter().all(|i| i.muted), @@ -165,4 +236,49 @@ impl AudioController for PulseController { fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()> { self.for_each_input_of(app, |me, input| me.context.introspect().set_sink_input_mute(input.index, muted, None)) } + + fn output_devices(&mut self) -> AudioResult> { + let default = self.default_sink_name()?; + let mut out: Vec = self + .sinks()? + .into_iter() + .map(|s| OutputDevice { is_default: Some(&s.name) == default.as_ref(), id: s.name, name: s.description }) + .collect(); + out.sort_by_key(|d| d.name.to_lowercase()); + Ok(out) + } + + fn set_default_output_device(&mut self, id: &str) -> AudioResult<()> { + let op = self.context.set_default_sink(id, |_| {}); + self.wait(op) + } + + fn master_volume(&mut self) -> AudioResult { + let s = self.default_sink()?; + Ok(MasterVolume { volume: Some(s.volume), muted: s.muted }) + } + + fn set_master_volume(&mut self, volume: f32) -> AudioResult<()> { + let s = self.default_sink()?; + let mut cv = ChannelVolumes::default(); + cv.set(s.channels.max(1), Volume((volume.clamp(0.0, 1.0) * Volume::NORMAL.0 as f32) as u32)); + let op = self.context.introspect().set_sink_volume_by_name(&s.name, &cv, None); + self.wait(op) + } + + fn set_master_mute(&mut self, muted: bool) -> AudioResult<()> { + let s = self.default_sink()?; + let op = self.context.introspect().set_sink_mute_by_name(&s.name, muted, None); + self.wait(op) + } + + fn set_app_output_device(&mut self, app: &str, device: Option<&str>) -> AudioResult<()> { + let target = match device { + Some(d) => d.to_owned(), + None => self.default_sink()?.name, + }; + self.for_each_input_of(app, |me, input| { + me.context.introspect().move_sink_input_by_name(input.index, &target, None) + }) + } } diff --git a/src/audio/macos.rs b/src/audio/macos.rs index e93aef9..c4c558c 100644 --- a/src/audio/macos.rs +++ b/src/audio/macos.rs @@ -11,6 +11,9 @@ //! //! Consequences: //! - Per-app **mute works**; per-app **volume levels do not** (`per_app_volume: false`). +//! - Per-app **output devices do not** either (`per_app_device: false`): there is no +//! public API to reroute another process. System volume/mute (the default device's +//! virtual main volume) and switching the default output device are public and supported. //! `set_app_volume` accepts only 0.0 (mute) and 1.0 (unmute) and reports `Unsupported` //! for anything in between — it never fakes a level. //! - Requires macOS 14.2+. On older systems the symbols are absent; we look them up with @@ -25,7 +28,7 @@ //! **Untested on real hardware by the original author** (developed on Windows, compile- //! checked for `aarch64-apple-darwin`). Reports from macOS users are very welcome. -use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities}; +use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, MasterVolume, OutputDevice}; use objc2::msg_send; use objc2::rc::Retained; use objc2::runtime::{AnyClass, AnyObject}; @@ -55,6 +58,16 @@ const K_HW_PROCESS_OBJECT_LIST: u32 = fourcc(b"prs#"); const K_PROCESS_PID: u32 = fourcc(b"ppid"); const K_PROCESS_BUNDLE_ID: u32 = fourcc(b"pbid"); const K_PROCESS_IS_RUNNING_OUTPUT: u32 = fourcc(b"piro"); +const K_SCOPE_OUTPUT: u32 = fourcc(b"outp"); +const K_HW_DEVICES: u32 = fourcc(b"dev#"); +const K_HW_DEFAULT_OUTPUT_DEVICE: u32 = fourcc(b"dOut"); +const K_DEVICE_STREAMS: u32 = fourcc(b"stm#"); +const K_DEVICE_UID: u32 = fourcc(b"uid "); +const K_OBJECT_NAME: u32 = fourcc(b"lnam"); +const K_DEVICE_VOLUME_SCALAR: u32 = fourcc(b"volm"); +const K_DEVICE_MUTE: u32 = fourcc(b"mute"); +/// `kAudioHardwareServiceDeviceProperty_VirtualMainVolume` (the menu-bar volume). +const K_VIRTUAL_MAIN_VOLUME: u32 = fourcc(b"vmvc"); /// `CATapMuteBehavior.CATapMuted` const CA_TAP_MUTED: isize = 1; @@ -75,6 +88,35 @@ extern "C" { io_size: *mut u32, out: *mut c_void, ) -> OSStatus; + fn AudioObjectSetPropertyData( + id: AudioObjectID, + addr: *const AudioObjectPropertyAddress, + qualifier_size: u32, + qualifier: *const c_void, + data_size: u32, + data: *const c_void, + ) -> OSStatus; +} + +// The virtual main volume is only served through the AudioHardwareService shim. +#[link(name = "AudioToolbox", kind = "framework")] +extern "C" { + fn AudioHardwareServiceGetPropertyData( + id: AudioObjectID, + addr: *const AudioObjectPropertyAddress, + qualifier_size: u32, + qualifier: *const c_void, + io_size: *mut u32, + out: *mut c_void, + ) -> OSStatus; + fn AudioHardwareServiceSetPropertyData( + id: AudioObjectID, + addr: *const AudioObjectPropertyAddress, + qualifier_size: u32, + qualifier: *const c_void, + data_size: u32, + data: *const c_void, + ) -> OSStatus; } type CreateTapFn = unsafe extern "C" fn(*mut AnyObject, *mut AudioObjectID) -> OSStatus; @@ -201,7 +243,13 @@ impl AudioController for CoreAudioTapController { } fn capabilities(&self) -> Capabilities { - Capabilities { per_app_volume: false, per_app_mute: self.api.is_some() } + Capabilities { + per_app_volume: false, + per_app_mute: self.api.is_some(), + per_app_device: false, + master_volume: true, + output_devices: true, + } } fn list_audio_apps(&mut self) -> AudioResult> { @@ -245,6 +293,8 @@ impl AudioController for CoreAudioTapController { pids: ps.iter().map(|p| p.pid).collect(), volume: None, // not readable per-app on macOS exe_path: ps[0].path.clone(), + device: None, + routable: false, key, }) .collect::>(); @@ -282,10 +332,70 @@ impl AudioController for CoreAudioTapController { Ok(()) } + fn output_devices(&mut self) -> AudioResult> { + let default = default_output_device(); + let ids: Vec = unsafe { get_array(K_AUDIO_OBJECT_SYSTEM_OBJECT, K_HW_DEVICES)? }; + let mut out = Vec::new(); + for id in ids { + if !has_output_streams(id) { + continue; + } + let Some(uid) = (unsafe { get_cfstring(id, K_DEVICE_UID) }) else { continue }; + let name = unsafe { get_cfstring(id, K_OBJECT_NAME) }.unwrap_or_else(|| uid.clone()); + out.push(OutputDevice { id: uid, name, is_default: Some(id) == default }); + } + out.sort_by_key(|d| d.name.to_lowercase()); + Ok(out) + } + + fn set_default_output_device(&mut self, uid: &str) -> AudioResult<()> { + let ids: Vec = unsafe { get_array(K_AUDIO_OBJECT_SYSTEM_OBJECT, K_HW_DEVICES)? }; + let id = ids + .into_iter() + .find(|id| unsafe { get_cfstring(*id, K_DEVICE_UID) }.as_deref() == Some(uid)) + .ok_or_else(|| AudioError::Backend("that output device is gone".into()))?; + let a = addr(K_HW_DEFAULT_OUTPUT_DEVICE); + let status = unsafe { + AudioObjectSetPropertyData(K_AUDIO_OBJECT_SYSTEM_OBJECT, &a, 0, std::ptr::null(), 4, &id as *const u32 as _) + }; + check(status, "set default output device") + } + + fn master_volume(&mut self) -> AudioResult { + let dev = default_output_device().ok_or_else(|| AudioError::Backend("no output device".into()))?; + let volume = unsafe { service_get::(dev, output_addr(K_VIRTUAL_MAIN_VOLUME)) } + .or_else(|| unsafe { get_at::(dev, output_addr(K_DEVICE_VOLUME_SCALAR)) }); + let muted = unsafe { get_at::(dev, output_addr(K_DEVICE_MUTE)) }.unwrap_or(0) != 0; + Ok(MasterVolume { volume, muted }) + } + + fn set_master_volume(&mut self, volume: f32) -> AudioResult<()> { + let dev = default_output_device().ok_or_else(|| AudioError::Backend("no output device".into()))?; + let v = volume.clamp(0.0, 1.0); + let a = output_addr(K_VIRTUAL_MAIN_VOLUME); + let status = + unsafe { AudioHardwareServiceSetPropertyData(dev, &a, 0, std::ptr::null(), 4, &v as *const f32 as _) }; + if status == 0 { + return Ok(()); + } + let a = output_addr(K_DEVICE_VOLUME_SCALAR); + check( + unsafe { AudioObjectSetPropertyData(dev, &a, 0, std::ptr::null(), 4, &v as *const f32 as _) }, + "set volume", + ) + } + + fn set_master_mute(&mut self, muted: bool) -> AudioResult<()> { + let dev = default_output_device().ok_or_else(|| AudioError::Backend("no output device".into()))?; + let m = muted as u32; + let a = output_addr(K_DEVICE_MUTE); + check(unsafe { AudioObjectSetPropertyData(dev, &a, 0, std::ptr::null(), 4, &m as *const u32 as _) }, "set mute") + } + fn platform_note(&self) -> Option<&'static str> { Some(if self.api.is_some() { - "macOS can mute individual apps but can't set their volume level. Muting needs the \ - Screen & System Audio Recording permission." + "macOS can mute individual apps but can't set their volume level or output device. \ + Muting needs the Screen & System Audio Recording permission." } else { "Per-app muting needs macOS 14.2 or newer. Apps are listed read-only." }) @@ -326,6 +436,52 @@ fn addr(selector: u32) -> AudioObjectPropertyAddress { AudioObjectPropertyAddress { selector, scope: K_SCOPE_GLOBAL, element: K_ELEMENT_MAIN } } +fn output_addr(selector: u32) -> AudioObjectPropertyAddress { + AudioObjectPropertyAddress { selector, scope: K_SCOPE_OUTPUT, element: K_ELEMENT_MAIN } +} + +fn check(status: OSStatus, what: &str) -> AudioResult<()> { + if status == 0 { + Ok(()) + } else { + Err(AudioError::Backend(format!("{what}: OSStatus {status}"))) + } +} + +fn default_output_device() -> Option { + unsafe { get_scalar::(K_AUDIO_OBJECT_SYSTEM_OBJECT, K_HW_DEFAULT_OUTPUT_DEVICE) } + .filter(|id| *id != 0) +} + +fn has_output_streams(id: AudioObjectID) -> bool { + let a = output_addr(K_DEVICE_STREAMS); + let mut size = 0u32; + let status = unsafe { AudioObjectGetPropertyDataSize(id, &a, 0, std::ptr::null(), &mut size) }; + status == 0 && size > 0 +} + +unsafe fn get_at(object: AudioObjectID, a: AudioObjectPropertyAddress) -> Option { + let mut v = T::default(); + let mut size = std::mem::size_of::() as u32; + let status = + AudioObjectGetPropertyData(object, &a, 0, std::ptr::null(), &mut size, &mut v as *mut T as *mut c_void); + (status == 0).then_some(v) +} + +unsafe fn service_get(object: AudioObjectID, a: AudioObjectPropertyAddress) -> Option { + let mut v = T::default(); + let mut size = std::mem::size_of::() as u32; + let status = AudioHardwareServiceGetPropertyData( + object, + &a, + 0, + std::ptr::null(), + &mut size, + &mut v as *mut T as *mut c_void, + ); + (status == 0).then_some(v) +} + unsafe fn get_array(object: AudioObjectID, selector: u32) -> AudioResult> { let a = addr(selector); let mut size = 0u32; diff --git a/src/audio/mod.rs b/src/audio/mod.rs index 449e3b1..254160f 100644 --- a/src/audio/mod.rs +++ b/src/audio/mod.rs @@ -5,16 +5,19 @@ //! (see [`worker`]) so they may hold thread-affine handles (COM objects, the //! PulseAudio mainloop, CoreAudio taps) without being `Send`. //! -//! | OS | Mechanism | Per-app volume | Per-app mute | -//! |---------|---------------------------------------------|----------------|--------------| -//! | Windows | WASAPI `IAudioSessionManager2` sessions | yes | yes | -//! | Linux | PulseAudio / PipeWire-pulse sink inputs | yes | yes | -//! | macOS | Core Audio process taps (macOS 14.2+) | **no** | yes | +//! | OS | Mechanism | Per-app volume | Per-app mute | Per-app device | +//! |---------|-----------------------------------------|----------------|--------------|----------------| +//! | Windows | WASAPI `IAudioSessionManager2` sessions | yes | yes | yes | +//! | Linux | PulseAudio / PipeWire-pulse sink inputs | yes | yes | yes | +//! | macOS | Core Audio process taps (macOS 14.2+) | **no** | yes | **no** | //! -//! macOS has no public API for setting another process's volume. HushKey mutes an -//! app by creating a *muted process tap* on it, which silences that process while +//! System volume, system mute and switching the default output device work on all three. +//! +//! macOS has no public API for setting another process's volume or output device. HushKey +//! mutes an app by creating a *muted process tap* on it, which silences that process while //! the tap exists. Arbitrary volume levels are not possible — the backend reports -//! `per_app_volume: false` and the UI hides volume levels instead of faking them. +//! `per_app_volume: false` / `per_app_device: false` and the UI hides those controls +//! instead of faking them. mod mute; pub mod worker; @@ -55,12 +58,39 @@ pub struct AudioApp { pub muted: bool, /// Executable path for icon lookup, when known. pub exe_path: Option, + /// [`OutputDevice::id`] this app is explicitly routed to; `None` = follows the system default. + pub device: Option, + /// Whether this app's output device can be changed (false for e.g. Windows system sounds). + pub routable: bool, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +/// An active playback device (speakers, headphones, HDMI, virtual cable…). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OutputDevice { + /// Backend-specific stable id (MMDevice id, PulseAudio sink name, Core Audio UID). + pub id: String, + pub name: String, + pub is_default: bool, +} + +/// Volume and mute of the system default output device. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MasterVolume { + /// 0.0..=1.0. `None` when the device has no volume control (some HDMI/USB outputs). + pub volume: Option, + pub muted: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct Capabilities { pub per_app_volume: bool, pub per_app_mute: bool, + /// Per-app output device routing. + pub per_app_device: bool, + /// System volume / mute of the default output device. + pub master_volume: bool, + /// Listing output devices and switching the system default. + pub output_devices: bool, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -68,7 +98,6 @@ pub enum AudioError { /// No running app has this key right now. NotRunning(AppKey), /// The platform can't do this (see the capability table above). - #[cfg_attr(not(target_os = "macos"), allow(dead_code))] Unsupported(&'static str), /// The OS needs a permission the user hasn't granted (macOS audio capture). #[cfg_attr(not(target_os = "macos"), allow(dead_code))] @@ -115,10 +144,7 @@ pub trait AudioController { /// idle ones that aren't currently producing sound. One entry per [`AppKey`]. fn list_audio_apps(&mut self) -> AudioResult>; - /// Set the volume of every session of `app` (0.0..=1.0). - /// Part of the backend contract (and `--list` diagnostics); the UI currently toggles - /// mute only, which preserves the user's own level in the OS mixer. - #[allow(dead_code)] + /// Set the volume of every session of `app` (0.0..=1.0). Independent of the mute flag. fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()>; /// Mute/unmute every session of `app`. Uses the OS mixer's own mute flag, so the @@ -151,6 +177,34 @@ pub trait AudioController { Ok(()) } + /// Active output devices, default first is *not* guaranteed (check `is_default`). + fn output_devices(&mut self) -> AudioResult> { + Ok(Vec::new()) + } + + /// Make `id` the system default output device. + fn set_default_output_device(&mut self, _id: &str) -> AudioResult<()> { + Err(AudioError::Unsupported("switching the output device")) + } + + /// Volume / mute of the default output device. + fn master_volume(&mut self) -> AudioResult { + Err(AudioError::Unsupported("system volume")) + } + + fn set_master_volume(&mut self, _volume: f32) -> AudioResult<()> { + Err(AudioError::Unsupported("system volume")) + } + + fn set_master_mute(&mut self, _muted: bool) -> AudioResult<()> { + Err(AudioError::Unsupported("system mute")) + } + + /// Route every stream of `app` to `device`, or back to the system default with `None`. + fn set_app_output_device(&mut self, _app: &str, _device: Option<&str>) -> AudioResult<()> { + Err(AudioError::Unsupported("per-app output devices")) + } + /// Best-effort app icon. Default: none (UI shows a letter avatar). fn app_icon(&mut self, _app: &AudioApp) -> Option { None diff --git a/src/audio/null.rs b/src/audio/null.rs index fa98047..70d799c 100644 --- a/src/audio/null.rs +++ b/src/audio/null.rs @@ -22,6 +22,8 @@ impl NullController { volume: Some(1.0), muted: *muted, exe_path: None, + device: None, + routable: true, }) .collect(), mute_calls: 0, @@ -39,7 +41,7 @@ impl AudioController for NullController { } fn capabilities(&self) -> Capabilities { - Capabilities { per_app_volume: true, per_app_mute: true } + Capabilities { per_app_volume: true, per_app_mute: true, ..Capabilities::default() } } fn list_audio_apps(&mut self) -> AudioResult> { diff --git a/src/audio/windows.rs b/src/audio/windows.rs index b727be8..087c10c 100644 --- a/src/audio/windows.rs +++ b/src/audio/windows.rs @@ -5,26 +5,44 @@ //! active render device**, not just the default one, so apps routed to headphones //! or a virtual device are found too. Sessions are grouped by executable name. //! -//! Full per-app volume and mute are natively supported (`ISimpleAudioVolume`). +//! Full per-app volume and mute are natively supported (`ISimpleAudioVolume`). System +//! volume uses `IAudioEndpointVolume` on the default device. +//! +//! # Undocumented interfaces +//! Windows has no *public* API to change the default output device or an app's output +//! device, yet both are what the Sound settings page does. HushKey uses the same private +//! COM interfaces as EarTrumpet, SoundSwitch and friends: +//! - `IPolicyConfig` (`CPolicyConfigClient`) → `SetDefaultEndpoint`, stable since Vista. +//! - `IAudioPolicyConfigFactory` (`Windows.Media.Internal.AudioPolicyConfig`) → +//! `Set/GetPersistedDefaultAudioEndpoint`, Windows 10 1803+. Its IID changed in 21H2, +//! so both are tried. If neither works the feature is reported unsupported instead of +//! failing. Windows itself persists the per-app choice (by executable), like the +//! "App volume and device preferences" page. +//! //! Threading: this type must stay on the thread that created it (COM MTA init). -use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, IconData}; +use super::{AudioApp, AudioController, AudioError, AudioResult, Capabilities, IconData, MasterVolume, OutputDevice}; use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; use std::os::windows::ffi::OsStrExt; use std::path::{Path, PathBuf}; -use windows::core::{Interface, HSTRING, PCWSTR, PWSTR}; +use windows::core::{Interface, GUID, HRESULT, HSTRING, PCWSTR, PWSTR}; +use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName; use windows::Win32::Foundation::{CloseHandle, S_OK}; use windows::Win32::Graphics::Gdi::{ DeleteObject, GetDC, GetDIBits, GetObjectW, ReleaseDC, BITMAP, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, }; +use windows::Win32::Media::Audio::Endpoints::IAudioEndpointVolume; use windows::Win32::Media::Audio::{ - eRender, AudioSessionStateExpired, IAudioSessionControl2, IAudioSessionManager2, IMMDeviceEnumerator, - ISimpleAudioVolume, MMDeviceEnumerator, DEVICE_STATE_ACTIVE, + eConsole, eMultimedia, eRender, AudioSessionStateExpired, IAudioSessionControl2, IAudioSessionManager2, IMMDevice, + IMMDeviceEnumerator, ISimpleAudioVolume, MMDeviceEnumerator, DEVICE_STATE_ACTIVE, }; use windows::Win32::Storage::FileSystem::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW}; -use windows::Win32::System::Com::{CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED}; +use windows::Win32::System::Com::StructuredStorage::PropVariantToStringAlloc; +use windows::Win32::System::Com::{ + CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED, STGM_READ, +}; use windows::Win32::System::Threading::{ OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, }; @@ -34,6 +52,103 @@ use windows::Win32::UI::WindowsAndMessaging::{DestroyIcon, GetIconInfo, HICON, I const SYSTEM_SOUNDS_KEY: &str = "system-sounds"; const ICON_SIZE: u32 = 64; +// ── Private policy-config interfaces (see module docs) ───────────────────────────── +// Only the methods HushKey calls have real signatures; the others are vtable padding. + +const CLSID_POLICY_CONFIG_CLIENT: GUID = GUID::from_u128(0x870af99c_171d_4f9e_af0d_e63df40c2bc9); + +const AUDIO_POLICY_CONFIG_CLASS: &str = "Windows.Media.Internal.AudioPolicyConfig"; +/// IID since Windows 10 21H2 (build 21390+), then the one used by 1803–21H1. +const AUDIO_POLICY_CONFIG_IIDS: [GUID; 2] = + [GUID::from_u128(0xab3d4648_e242_459f_b02f_541c70306324), GUID::from_u128(0x2a59116d_6c4f_45e0_a74f_707e3fef9258)]; +const MMDEVAPI_PREFIX: &str = r"\\?\SWD#MMDEVAPI#"; +const RENDER_INTERFACE_SUFFIX: &str = "#{e6327cad-dcec-4949-ae8a-991e976a79d2}"; + +mod policy { + #![allow(non_snake_case, dead_code)] + use std::ffi::c_void; + use windows::core::{IUnknown, IUnknown_Vtbl, HRESULT, PCWSTR}; + use windows::Win32::Media::Audio::{EDataFlow, ERole}; + + #[windows::core::interface("f8679f50-850a-41cf-9c72-430f290290c8")] + pub unsafe trait IPolicyConfig: IUnknown { + pub fn GetMixFormat(&self) -> HRESULT; + pub fn GetDeviceFormat(&self) -> HRESULT; + pub fn ResetDeviceFormat(&self) -> HRESULT; + pub fn SetDeviceFormat(&self) -> HRESULT; + pub fn GetProcessingPeriod(&self) -> HRESULT; + pub fn SetProcessingPeriod(&self) -> HRESULT; + pub fn GetShareMode(&self) -> HRESULT; + pub fn SetShareMode(&self) -> HRESULT; + pub fn GetPropertyValue(&self) -> HRESULT; + pub fn SetPropertyValue(&self) -> HRESULT; + pub fn SetDefaultEndpoint(&self, device_id: PCWSTR, role: ERole) -> HRESULT; + pub fn SetEndpointVisibility(&self) -> HRESULT; + } + + // The IID here is only used by `cast()`, which HushKey never does: the factory is + // obtained via `RoGetActivationFactory` with whichever IID the OS accepts (same layout). + #[windows::core::interface("ab3d4648-e242-459f-b02f-541c70306324")] + pub unsafe trait IAudioPolicyConfigFactory: IUnknown { + // IInspectable + pub fn GetIids(&self) -> HRESULT; + pub fn GetRuntimeClassName(&self) -> HRESULT; + pub fn GetTrustLevel(&self) -> HRESULT; + pub fn add_CtxVolumeChange(&self) -> HRESULT; + pub fn remove_CtxVolumeChanged(&self) -> HRESULT; + pub fn add_RingerVibrateStateChanged(&self) -> HRESULT; + pub fn remove_RingerVibrateStateChange(&self) -> HRESULT; + pub fn SetVolumeGroupGainForId(&self) -> HRESULT; + pub fn GetVolumeGroupGainForId(&self) -> HRESULT; + pub fn GetActiveVolumeGroupForEndpointId(&self) -> HRESULT; + pub fn GetVolumeGroupsForEndpoint(&self) -> HRESULT; + pub fn GetCurrentVolumeContext(&self) -> HRESULT; + pub fn SetVolumeGroupMuteForId(&self) -> HRESULT; + pub fn GetVolumeGroupMuteForId(&self) -> HRESULT; + pub fn SetRingerVibrateState(&self) -> HRESULT; + pub fn GetRingerVibrateState(&self) -> HRESULT; + pub fn SetPreferredChatApplication(&self) -> HRESULT; + pub fn ResetPreferredChatApplication(&self) -> HRESULT; + pub fn GetPreferredChatApplication(&self) -> HRESULT; + pub fn GetCurrentChatApplications(&self) -> HRESULT; + pub fn add_ChatContextChanged(&self) -> HRESULT; + pub fn remove_ChatContextChanged(&self) -> HRESULT; + // `device_id` is a borrowed HSTRING handle (null = back to the system default). + pub fn SetPersistedDefaultAudioEndpoint( + &self, + pid: u32, + flow: EDataFlow, + role: ERole, + device_id: *mut c_void, + ) -> HRESULT; + // Writes an owned HSTRING handle to `device_id` (null when the app follows the default). + pub fn GetPersistedDefaultAudioEndpoint( + &self, + pid: u32, + flow: EDataFlow, + role: ERole, + device_id: *mut *mut c_void, + ) -> HRESULT; + pub fn ClearAllPersistedApplicationDefaultEndpoints(&self) -> HRESULT; + } +} +use policy::{IAudioPolicyConfigFactory, IPolicyConfig}; + +fn audio_policy_factory() -> Option { + windows::core::link!("api-ms-win-core-winrt-l1-1-0.dll" "system" fn RoGetActivationFactory(class: *mut c_void, iid: *const GUID, factory: *mut *mut c_void) -> HRESULT); + let class = HSTRING::from(AUDIO_POLICY_CONFIG_CLASS); + for iid in &AUDIO_POLICY_CONFIG_IIDS { + let mut raw: *mut c_void = std::ptr::null_mut(); + // SAFETY: HSTRING is a transparent handle; the factory comes back +1 and from_raw adopts it. + let hr = unsafe { RoGetActivationFactory(std::mem::transmute_copy(&class), iid, &mut raw) }; + if hr.is_ok() && !raw.is_null() { + return Some(unsafe { IAudioPolicyConfigFactory::from_raw(raw) }); + } + } + log::info!("per-app output devices unavailable (AudioPolicyConfig factory not found)"); + None +} + fn err(context: &str, e: windows::core::Error) -> AudioError { AudioError::Backend(format!("{context}: {e}")) } @@ -62,6 +177,8 @@ impl Drop for ComGuard { pub struct WasapiController { enumerator: IMMDeviceEnumerator, procs: HashMap, + device_names: HashMap, + policy: Option, _com: ComGuard, } @@ -72,10 +189,55 @@ impl WasapiController { let guard = ComGuard; let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|e| err("MMDeviceEnumerator", e))?; - Ok(Self { enumerator, procs: HashMap::new(), _com: guard }) + Ok(Self { + enumerator, + procs: HashMap::new(), + device_names: HashMap::new(), + policy: audio_policy_factory(), + _com: guard, + }) } } + fn default_device(&self) -> AudioResult { + unsafe { self.enumerator.GetDefaultAudioEndpoint(eRender, eMultimedia) }.map_err(|e| err("default device", e)) + } + + fn endpoint_volume(&self) -> AudioResult { + let device = self.default_device()?; + unsafe { device.Activate::(CLSCTX_ALL, None) }.map_err(|e| err("endpoint volume", e)) + } + + fn device_name(&mut self, device: &IMMDevice, id: &str) -> String { + if let Some(n) = self.device_names.get(id) { + return n.clone(); + } + let name = unsafe { + device + .OpenPropertyStore(STGM_READ) + .and_then(|store| store.GetValue(&PKEY_Device_FriendlyName)) + .and_then(|value| PropVariantToStringAlloc(&value)) + .ok() + .map(take_pwstr) + } + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| "Unknown device".to_owned()); + self.device_names.insert(id.to_owned(), name.clone()); + name + } + + /// The device an app is explicitly routed to, from the first of its processes that has one. + fn persisted_device(&self, pids: &[u32]) -> Option { + let policy = self.policy.as_ref()?; + pids.iter().filter(|p| **p != 0).find_map(|&pid| unsafe { + let mut raw: *mut c_void = std::ptr::null_mut(); + policy.GetPersistedDefaultAudioEndpoint(pid, eRender, eMultimedia, &mut raw).ok().ok()?; + // SAFETY: an owned HSTRING handle (or null = empty); HSTRING frees it on drop. + let s: HSTRING = std::mem::transmute::<*mut c_void, HSTRING>(raw); + unpack_device_id(&s.to_string_lossy()) + }) + } + fn proc_info(&mut self, pid: u32) -> ProcInfo { if let Some(p) = self.procs.get(&pid) { return p.clone(); @@ -160,7 +322,13 @@ impl AudioController for WasapiController { } fn capabilities(&self) -> Capabilities { - Capabilities { per_app_volume: true, per_app_mute: true } + Capabilities { + per_app_volume: true, + per_app_mute: true, + per_app_device: self.policy.is_some(), + master_volume: true, + output_devices: true, + } } fn list_audio_apps(&mut self) -> AudioResult> { @@ -181,14 +349,17 @@ impl AudioController for WasapiController { let mut apps: Vec = grouped .into_iter() .map(|(key, (pids, vols, muted))| { - let (name, exe_path) = if key == SYSTEM_SOUNDS_KEY { + let system = key == SYSTEM_SOUNDS_KEY; + let (name, exe_path) = if system { ("System Sounds".to_owned(), None) } else { let info = pids.iter().find_map(|p| self.procs.get(p)).cloned(); info.map(|i| (i.name, i.path)).unwrap_or_else(|| (key.clone(), None)) }; let volume = Some(vols.iter().sum::() / vols.len().max(1) as f32); - AudioApp { key, name, pids, volume, muted, exe_path } + let device = if system { None } else { self.persisted_device(&pids) }; + let routable = !system && self.policy.is_some(); + AudioApp { key, name, pids, volume, muted, exe_path, device, routable } }) .collect(); apps.sort_by_key(|a| a.name.to_lowercase()); @@ -204,11 +375,112 @@ impl AudioController for WasapiController { self.for_each_session_of(app, |s| unsafe { s.SetMute(muted, std::ptr::null()) }) } + fn output_devices(&mut self) -> AudioResult> { + let default_id = self.default_device().ok().and_then(|d| unsafe { d.GetId() }.ok()).map(take_pwstr); + let mut out = Vec::new(); + unsafe { + let devices = self + .enumerator + .EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE) + .map_err(|e| err("EnumAudioEndpoints", e))?; + for i in 0..devices.GetCount().map_err(|e| err("GetCount", e))? { + let Ok(device) = devices.Item(i) else { continue }; + let Ok(id) = device.GetId().map(take_pwstr) else { continue }; + let name = self.device_name(&device, &id); + out.push(OutputDevice { is_default: default_id.as_deref() == Some(id.as_str()), id, name }); + } + } + out.sort_by_key(|d| d.name.to_lowercase()); + Ok(out) + } + + fn set_default_output_device(&mut self, id: &str) -> AudioResult<()> { + unsafe { + let policy: IPolicyConfig = + CoCreateInstance(&CLSID_POLICY_CONFIG_CLIENT, None, CLSCTX_ALL).map_err(|e| err("PolicyConfig", e))?; + let wide_id = HSTRING::from(id); + for role in [eConsole, eMultimedia] { + policy + .SetDefaultEndpoint(PCWSTR(wide_id.as_ptr()), role) + .ok() + .map_err(|e| err("SetDefaultEndpoint", e))?; + } + } + Ok(()) + } + + fn master_volume(&mut self) -> AudioResult { + let ep = self.endpoint_volume()?; + unsafe { + Ok(MasterVolume { + volume: ep.GetMasterVolumeLevelScalar().ok(), + muted: ep.GetMute().map(|b| b.as_bool()).unwrap_or(false), + }) + } + } + + fn set_master_volume(&mut self, volume: f32) -> AudioResult<()> { + let ep = self.endpoint_volume()?; + unsafe { ep.SetMasterVolumeLevelScalar(volume.clamp(0.0, 1.0), std::ptr::null()) } + .map_err(|e| err("system volume", e)) + } + + fn set_master_mute(&mut self, muted: bool) -> AudioResult<()> { + let ep = self.endpoint_volume()?; + unsafe { ep.SetMute(muted, std::ptr::null()) }.map_err(|e| err("system mute", e)) + } + + fn set_app_output_device(&mut self, app: &str, device: Option<&str>) -> AudioResult<()> { + if app == SYSTEM_SOUNDS_KEY { + return Err(AudioError::Unsupported("routing system sounds")); + } + let Some(policy) = self.policy.clone() else { + return Err(AudioError::Unsupported("per-app output devices (needs Windows 10 1803 or newer)")); + }; + let mut pids: Vec = self.sessions()?.into_iter().filter(|s| s.key == app).map(|s| s.pid).collect(); + pids.sort_unstable(); + pids.dedup(); + if pids.is_empty() { + return Err(AudioError::NotRunning(app.to_owned())); + } + let packed = device.map(|id| HSTRING::from(format!("{MMDEVAPI_PREFIX}{id}{RENDER_INTERFACE_SUFFIX}"))); + // SAFETY: a borrowed handle that outlives the calls; null resets the app to the default. + let raw: *mut c_void = + packed.as_ref().map(|h| unsafe { std::mem::transmute_copy(h) }).unwrap_or(std::ptr::null_mut()); + for pid in pids { + for role in [eConsole, eMultimedia] { + unsafe { policy.SetPersistedDefaultAudioEndpoint(pid, eRender, role, raw) } + .ok() + .map_err(|e| err("SetPersistedDefaultAudioEndpoint", e))?; + } + } + Ok(()) + } + fn app_icon(&mut self, app: &AudioApp) -> Option { exe_icon(app.exe_path.as_deref()?) } } +/// Copy a CoTaskMem-allocated wide string and free it. +fn take_pwstr(p: PWSTR) -> String { + if p.is_null() { + return String::new(); + } + unsafe { + let s = p.to_string().unwrap_or_default(); + CoTaskMemFree(Some(p.0 as *const c_void)); + s + } +} + +/// `\\?\SWD#MMDEVAPI#{0.0.0.00000000}.{guid}#{e6327cad-…}` → `{0.0.0.00000000}.{guid}`. +fn unpack_device_id(s: &str) -> Option { + let s = s.strip_prefix(MMDEVAPI_PREFIX).unwrap_or(s); + let s = s.strip_suffix(RENDER_INTERFACE_SUFFIX).unwrap_or(s); + (!s.is_empty()).then(|| s.to_owned()) +} + fn wide(path: &Path) -> Vec { path.as_os_str().encode_wide().chain(std::iter::once(0)).collect() } @@ -337,3 +609,16 @@ unsafe fn hicon_to_rgba(icon: HICON) -> Option { } Some(IconData { width: w as u32, height: h as u32, rgba: buf }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn device_id_round_trip() { + let id = "{0.0.0.00000000}.{5c6a2d1e-7a3b-4c1d-9e2f-1a2b3c4d5e6f}"; + let packed = format!("{MMDEVAPI_PREFIX}{id}{RENDER_INTERFACE_SUFFIX}"); + assert_eq!(unpack_device_id(&packed).as_deref(), Some(id)); + assert_eq!(unpack_device_id(""), None); + } +} diff --git a/src/audio/worker.rs b/src/audio/worker.rs index baa3a69..654c93c 100644 --- a/src/audio/worker.rs +++ b/src/audio/worker.rs @@ -6,10 +6,16 @@ //! //! The thread blocks on its channel when idle — zero CPU. The only periodic work is //! while "Mute All" is engaged: every 2 s it silences apps that started afterwards. +//! +//! Volume sliders send a command per mouse move; consecutive volume commands for the +//! same target are coalesced so only the latest level is applied. use super::mute::ToggleOutcome; -use super::{create_controller, AudioApp, AudioError, Capabilities, IconData, MuteManager}; -use std::collections::HashSet; +use super::{ + create_controller, AudioApp, AudioController, AudioError, Capabilities, IconData, MasterVolume, MuteManager, + OutputDevice, +}; +use std::collections::{HashSet, VecDeque}; use std::sync::mpsc::{self, RecvTimeoutError, Sender}; use std::thread::JoinHandle; use std::time::Duration; @@ -30,9 +36,43 @@ pub enum AudioCommand { RestoreAll { from_hotkey: bool, }, + SetAppVolume { + key: String, + volume: f32, + }, + SetMasterVolume(f32), + SetMasterMute(bool), + SetDefaultDevice(String), + /// `device: None` routes the app back to the system default. + SetAppDevice { + key: String, + device: Option, + }, Shutdown, } +impl AudioCommand { + /// Commands where only the most recent one matters, keyed by target. + fn coalesce_key(&self) -> Option<&str> { + match self { + AudioCommand::SetAppVolume { key, .. } => Some(key), + AudioCommand::SetMasterVolume(_) => Some("@master"), + _ => None, + } + } +} + +/// Replace `cmd` with the newest queued command for the same target, removing the stale ones. +fn coalesce(mut cmd: AudioCommand, pending: &mut VecDeque) -> AudioCommand { + let Some(target) = cmd.coalesce_key().map(str::to_owned) else { return cmd }; + while let Some(pos) = pending.iter().position(|c| c.coalesce_key() == Some(&target)) { + if let Some(newer) = pending.remove(pos) { + cmd = newer; + } + } + cmd +} + #[derive(Debug, Clone)] pub enum AudioEvent { Ready { @@ -41,6 +81,11 @@ pub enum AudioEvent { note: Option<&'static str>, }, Apps(Vec), + /// Output devices and system volume. `master` is `None` when unsupported/unavailable. + Output { + devices: Vec, + master: Option, + }, Icon { key: String, icon: IconData, @@ -118,8 +163,9 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle { let mut mute = MuteManager::default(); let mut icons_sent: HashSet = HashSet::new(); - let publish_apps = - |ctl: &mut dyn super::AudioController, icons_sent: &mut HashSet| match ctl.list_audio_apps() { + let caps = ctl.capabilities(); + let publish_apps = |ctl: &mut dyn AudioController, icons_sent: &mut HashSet| { + match ctl.list_audio_apps() { Ok(apps) => { for app in &apps { if icons_sent.insert(app.key.clone()) { @@ -131,10 +177,27 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle { sink(AudioEvent::Apps(apps)); } Err(e) => sink(AudioEvent::Error { message: e.to_string(), from_hotkey: false }), - }; + } + if caps.output_devices || caps.master_volume { + let devices = ctl.output_devices().unwrap_or_else(|e| { + log::debug!("output devices: {e}"); + Vec::new() + }); + let master = if caps.master_volume { ctl.master_volume().ok() } else { None }; + sink(AudioEvent::Output { devices, master }); + } + }; + let report = |result: Result<(), AudioError>, what: &str| { + if let Err(e) = result { + sink(AudioEvent::Error { message: format!("{what}: {e}"), from_hotkey: false }); + } + }; + let mut pending: VecDeque = VecDeque::new(); loop { - let cmd = if mute.all_muted() { + let cmd = if let Some(cmd) = pending.pop_front() { + cmd + } else if mute.all_muted() { match rx.recv_timeout(ENFORCE_INTERVAL) { Ok(cmd) => cmd, Err(RecvTimeoutError::Timeout) => { @@ -148,6 +211,12 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle { } else { rx.recv().unwrap_or(AudioCommand::Shutdown) }; + let cmd = if cmd.coalesce_key().is_some() { + pending.extend(rx.try_iter()); + coalesce(cmd, &mut pending) + } else { + cmd + }; match cmd { AudioCommand::Refresh => { @@ -176,6 +245,24 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle { } publish_apps(ctl.as_mut(), &mut icons_sent); } + // Sliders: the UI already shows the new level, so no full republish per move. + AudioCommand::SetAppVolume { key, volume } => match ctl.set_app_volume(&key, volume) { + Ok(()) | Err(AudioError::NotRunning(_)) => {} + Err(e) => report(Err(e), &key), + }, + AudioCommand::SetMasterVolume(v) => report(ctl.set_master_volume(v), "System volume"), + AudioCommand::SetMasterMute(m) => { + report(ctl.set_master_mute(m), "System mute"); + publish_apps(ctl.as_mut(), &mut icons_sent); + } + AudioCommand::SetDefaultDevice(id) => { + report(ctl.set_default_output_device(&id), "Output device"); + publish_apps(ctl.as_mut(), &mut icons_sent); + } + AudioCommand::SetAppDevice { key, device } => { + report(ctl.set_app_output_device(&key, device.as_deref()), &key); + publish_apps(ctl.as_mut(), &mut icons_sent); + } AudioCommand::Shutdown => { if let Err(e) = mute.restore_all(ctl.as_mut()) { log::warn!("restore on shutdown failed: {e}"); @@ -188,3 +275,33 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle { .expect("spawn audio thread"); AudioHandle { tx, thread: Some(thread) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn vol(key: &str, v: f32) -> AudioCommand { + AudioCommand::SetAppVolume { key: key.into(), volume: v } + } + + #[test] + fn coalesces_same_target_and_keeps_others_in_order() { + let mut pending: VecDeque = + [vol("a", 0.2), AudioCommand::Refresh, vol("b", 0.9), vol("a", 0.7), AudioCommand::SetMasterVolume(0.4)] + .into_iter() + .collect(); + let cmd = coalesce(vol("a", 0.1), &mut pending); + assert!(matches!(cmd, AudioCommand::SetAppVolume { ref key, volume } if key == "a" && volume == 0.7)); + assert_eq!(pending.len(), 3); + assert!(matches!(pending[0], AudioCommand::Refresh)); + assert!(matches!(pending[1], AudioCommand::SetAppVolume { ref key, .. } if key == "b")); + assert!(matches!(pending[2], AudioCommand::SetMasterVolume(_))); + } + + #[test] + fn non_volume_commands_pass_through() { + let mut pending: VecDeque = [AudioCommand::Refresh].into_iter().collect(); + assert!(matches!(coalesce(AudioCommand::SetMasterMute(true), &mut pending), AudioCommand::SetMasterMute(true))); + assert_eq!(pending.len(), 1); + } +} diff --git a/src/main.rs b/src/main.rs index fae3a0c..f0c7544 100644 --- a/src/main.rs +++ b/src/main.rs @@ -106,9 +106,31 @@ fn list_apps() { Ok(apps) => { for a in apps { let vol = a.volume.map(|v| format!("{:>3.0}%", v * 100.0)).unwrap_or_else(|| " — ".into()); - println!("{:<32} {:<28} vol {vol} muted {:<5} pids {:?}", a.key, a.name, a.muted, a.pids); + let dev = a.device.as_deref().unwrap_or("default"); + println!( + "{:<32} {:<28} vol {vol} muted {:<5} pids {:?} device {dev}", + a.key, a.name, a.muted, a.pids + ); } } Err(e) => eprintln!("error: {e}"), } + if let Ok(m) = ctl.master_volume() { + let vol = m.volume.map(|v| format!("{:.0}%", v * 100.0)).unwrap_or_else(|| "—".into()); + println!( + " +system volume {vol} muted {}", + m.muted + ); + } + match ctl.output_devices() { + Ok(devices) if !devices.is_empty() => { + println!("output devices:"); + for d in devices { + println!(" {} {:<36} {}", if d.is_default { "*" } else { " " }, d.name, d.id); + } + } + Ok(_) => {} + Err(e) => eprintln!("output devices: {e}"), + } } diff --git a/src/platform.rs b/src/platform.rs index 3790a2c..cbe31b9 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -40,6 +40,22 @@ pub fn open_folder(path: &Path) { } } +/// Open an http(s) URL in the default browser. +pub fn open_url(url: &str) { + if !(url.starts_with("https://") || url.starts_with("http://")) { + return; + } + #[cfg(target_os = "windows")] + let result = std::process::Command::new("rundll32").args(["url.dll,FileProtocolHandler", url]).spawn(); + #[cfg(target_os = "macos")] + let result = std::process::Command::new("open").arg(url).spawn(); + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + let result = std::process::Command::new("xdg-open").arg(url).spawn(); + if let Err(e) = result { + log::warn!("open {url}: {e}"); + } +} + // ── Single instance ──────────────────────────────────────────────────────────── // A loopback-only socket doubles as lock and "show yourself" signal: launching HushKey // again just brings the running window up. Loopback binds don't trigger firewall prompts. diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 341145d..74b0e36 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -39,3 +39,23 @@ pub fn icon_image(size: u32, state: IconState) -> slint::Image { let buf = slint::SharedPixelBuffer::::clone_from_slice(&rgba, size, size); slint::Image::from_rgba8(buf) } + +/// The app icon as a winit window icon. +pub fn winit_icon(size: u32) -> Option { + slint::winit_030::winit::window::Icon::from_rgba(icon::render(size, IconState::Normal), size, size).ok() +} + +/// Window icons applied when the native window is *created*. Slint can't convert icons made +/// from pixel buffers itself, and the window doesn't exist yet when `show()` returns, so +/// this is the reliable place (title bar / Alt+Tab, plus the Windows taskbar's big icon). +pub fn with_app_icons( + attrs: slint::winit_030::winit::window::WindowAttributes, +) -> slint::winit_030::winit::window::WindowAttributes { + let attrs = attrs.with_window_icon(winit_icon(32)); + #[cfg(target_os = "windows")] + let attrs = { + use slint::winit_030::winit::platform::windows::WindowAttributesExtWindows; + attrs.with_taskbar_icon(winit_icon(64)) + }; + attrs +} diff --git a/src/ui/toast.rs b/src/ui/toast.rs index f22d8de..7a8af23 100644 --- a/src/ui/toast.rs +++ b/src/ui/toast.rs @@ -30,7 +30,7 @@ const BOTTOM_MARGIN: f64 = 110.0; /// Window-attribute hook: applied to every winit window Slint creates. pub fn window_attributes_hook(attrs: winit::window::WindowAttributes) -> winit::window::WindowAttributes { if !NEXT_WINDOW_IS_TOAST.with(|f| f.replace(false)) { - return attrs; + return super::with_app_icons(attrs); } let attrs = attrs .with_active(false) diff --git a/ui/main.slint b/ui/main.slint index 69828f5..01c6a41 100644 --- a/ui/main.slint +++ b/ui/main.slint @@ -1,7 +1,8 @@ import { ListView, ScrollView, Palette } from "std-widgets.slint"; import { Theme } from "theme.slint"; import { - SpeakerIcon, ThemeIcon, IconButton, Tabs, Switch, ShortcutChip, SettingRow, Card, SectionLabel + SpeakerIcon, ThemeIcon, IconButton, Tabs, Switch, ShortcutChip, SettingRow, Card, SectionLabel, + VolumeSlider, DevicePicker } from "widgets.slint"; export { Toast } from "toast.slint"; @@ -18,6 +19,8 @@ export struct AppRow { muted: bool, volume: float, // 0..1, < 0 when unknown shortcut: string, // display label, "" when unbound + routable: bool, // output device can be changed + device-index: int, // index into MainWindow.app-device-options (0 = system default) } component Avatar inherits Rectangle { @@ -71,11 +74,17 @@ component AppRowView inherits Rectangle { in property app; in property capturing; in property show-volume; + in property show-device; + in property <[string]> device-options; callback toggle(); callback capture(); callback clear(); + callback volume-moved(float); + callback device-picked(int); + + property has-volume: show-volume && app.running && app.volume >= 0; + property has-device: show-device && app.running && app.routable; - height: 64px; border-radius: 12px; background: hover.has-hover ? Theme.surface-hover : Theme.surface; border-width: 1px; @@ -84,65 +93,164 @@ component AppRowView inherits Rectangle { hover := TouchArea { } - HorizontalLayout { + VerticalLayout { padding-left: 12px; padding-right: 10px; - spacing: 12px; - alignment: stretch; + padding-top: 12px; + padding-bottom: 12px; + spacing: 8px; - VerticalLayout { - alignment: center; - Avatar { app: root.app; opacity: root.app.running ? 1 : 0.45; } - } - VerticalLayout { - alignment: center; - spacing: 3px; - horizontal-stretch: 1; - Text { - text: root.app.name; - font-size: 13.5px; - font-weight: 600; - color: root.app.running ? Theme.text : Theme.text-muted; - overflow: elide; + HorizontalLayout { + spacing: 12px; + alignment: stretch; + + VerticalLayout { + alignment: center; + Avatar { app: root.app; opacity: root.app.running ? 1 : 0.45; } } - Text { - text: root.app.subtitle; - font-size: 11.5px; - color: root.app.muted ? Theme.danger : Theme.text-faint; - overflow: elide; + VerticalLayout { + alignment: center; + spacing: 3px; + horizontal-stretch: 1; + Text { + text: root.app.name; + font-size: 13.5px; + font-weight: 600; + color: root.app.running ? Theme.text : Theme.text-muted; + overflow: elide; + } + Text { + text: root.app.subtitle; + font-size: 11.5px; + color: root.app.muted ? Theme.danger : Theme.text-faint; + overflow: elide; + } } - if root.show-volume && root.app.running && root.app.volume >= 0: Rectangle { - height: 3px; - border-radius: 1.5px; - background: Theme.surface-sunken; - Rectangle { - x: 0; - width: parent.width * clamp(root.app.volume, 0, 1); - height: parent.height; - border-radius: 1.5px; - background: root.app.muted ? Theme.text-faint : Theme.accent; - animate width { duration: 200ms; } + VerticalLayout { + alignment: center; + ShortcutChip { + width: 132px; + shortcut: root.app.shortcut; + capturing: root.capturing; + label: root.app.name + " shortcut"; + clicked => { root.capture(); } + cleared => { root.clear(); } + } + } + VerticalLayout { + alignment: center; + MuteButton { + muted: root.app.muted; + enabled: root.app.running; + label: root.app.name; + clicked => { root.toggle(); } } } } - VerticalLayout { + + if root.has-volume || root.has-device: HorizontalLayout { + padding-left: 48px; // line up with the name, past the avatar + padding-right: 2px; + spacing: 10px; + if root.has-volume: VolumeSlider { + horizontal-stretch: 1; + value: root.app.volume; + dimmed: root.app.muted; + label: root.app.name + " volume"; + moved(v) => { root.volume-moved(v); } + } + if root.has-volume: Text { + width: 34px; + text: round(root.app.volume * 100) + "%"; + font-size: 11.5px; + color: Theme.text-muted; + horizontal-alignment: right; + vertical-alignment: center; + } + if !root.has-volume: Rectangle { horizontal-stretch: 1; } + if root.has-device: DevicePicker { + width: 150px; + options: root.device-options; + selected: root.app.device-index; + label: root.app.name + " output device"; + picked(i) => { root.device-picked(i); } + } + } + } +} + +// System volume + default output device. +component OutputCard inherits Rectangle { + in property volume; // 0..1, < 0 when the device has no volume control + in property muted; + in property show-volume; + in property show-device; + in property <[string]> devices; + in property device-index; + callback toggle-mute(); + callback volume-moved(float); + callback device-picked(int); + + property has-volume: show-volume && volume >= 0; + + border-radius: 12px; + background: Theme.surface; + border-width: 1px; + border-color: Theme.border; + + HorizontalLayout { + padding-left: 12px; + padding-right: 12px; + padding-top: 10px; + padding-bottom: 10px; + spacing: 12px; + + if root.show-volume: VerticalLayout { alignment: center; - ShortcutChip { - width: 132px; - shortcut: root.app.shortcut; - capturing: root.capturing; - label: root.app.name + " shortcut"; - clicked => { root.capture(); } - cleared => { root.clear(); } + MuteButton { + muted: root.muted; + label: "system volume"; + clicked => { root.toggle-mute(); } } } VerticalLayout { alignment: center; - MuteButton { - muted: root.app.muted; - enabled: root.app.running; - label: root.app.name; - clicked => { root.toggle(); } + spacing: 4px; + horizontal-stretch: 1; + HorizontalLayout { + Text { + text: "System volume"; + font-size: 13px; + font-weight: 600; + color: Theme.text; + horizontal-stretch: 1; + } + Text { + text: root.muted ? "Muted" : (root.has-volume ? round(root.volume * 100) + "%" : ""); + font-size: 11.5px; + color: root.muted ? Theme.danger : Theme.text-muted; + } + } + if root.has-volume: VolumeSlider { + value: root.volume; + dimmed: root.muted; + label: "System volume"; + moved(v) => { root.volume-moved(v); } + } + if !root.has-volume && root.show-volume: Text { + text: "This device has no volume control"; + font-size: 11.5px; + color: Theme.text-faint; + } + } + if root.show-device: VerticalLayout { + alignment: center; + DevicePicker { + width: 160px; + options: root.devices; + selected: root.device-index; + label: "Output device"; + picked(i) => { root.device-picked(i); } } } } @@ -248,8 +356,8 @@ component MuteAllCard inherits Rectangle { export component MainWindow inherits Window { title: "HushKey"; icon: root.app-icon; - preferred-width: 460px; - preferred-height: 660px; + preferred-width: 480px; + preferred-height: 720px; min-width: 400px; min-height: 480px; background: Theme.bg; @@ -268,6 +376,14 @@ export component MainWindow inherits Window { in property backend; in property platform-note; in property show-volume: true; + in property show-app-device; + in property show-master-volume; + in property show-output-devices; + in property <[string]> output-devices; // names, for the system picker + in property <[string]> app-device-options; // "System default" + names + in property default-device-index; + in property master-volume: -1; + in property master-muted; in property config-path; in property version; in property hotkey-hint; @@ -289,6 +405,12 @@ export component MainWindow inherits Window { callback open-config-dir(); callback refresh(); callback dismiss-status(); + callback set-app-volume(string, float); + callback pick-app-device(string, int); + callback set-master-volume(float); + callback toggle-master-mute(); + callback pick-default-device(int); + callback open-url(string); init => { Theme.dark = root.dark; @@ -370,6 +492,18 @@ export component MainWindow inherits Window { clear(t) => { root.clear-shortcut(t); } } + if root.show-master-volume || root.show-output-devices: OutputCard { + volume: root.master-volume; + muted: root.master-muted; + show-volume: root.show-master-volume; + show-device: root.show-output-devices; + devices: root.output-devices; + device-index: root.default-device-index; + toggle-mute => { root.toggle-master-mute(); } + volume-moved(v) => { root.set-master-volume(v); } + device-picked(i) => { root.pick-default-device(i); } + } + if root.platform-note != "": Rectangle { border-radius: 10px; background: Theme.accent-soft; @@ -427,7 +561,11 @@ export component MainWindow inherits Window { app: row; capturing: root.capturing == row.key; show-volume: root.show-volume; + show-device: root.show-app-device; + device-options: root.app-device-options; toggle => { root.toggle-app(row.key); } + volume-moved(v) => { root.set-app-volume(row.key, v); } + device-picked(i) => { root.pick-app-device(row.key, i); } capture => { root.begin-capture(row.key); } clear => { root.clear-shortcut(row.key); } } @@ -498,11 +636,22 @@ export component MainWindow inherits Window { VerticalLayout { padding: 16px; spacing: 6px; - Text { - text: "HushKey " + root.version; - font-size: 14px; - font-weight: 700; - color: Theme.text; + HorizontalLayout { + spacing: 6px; + alignment: start; + Text { + text: "HushKey " + root.version; + font-size: 14px; + font-weight: 700; + color: Theme.text; + vertical-alignment: center; + } + Text { + text: "by X4Lo"; + font-size: 12.5px; + color: Theme.text-muted; + vertical-alignment: center; + } } Text { text: "Audio backend: " + root.backend; @@ -519,6 +668,26 @@ export component MainWindow inherits Window { HorizontalLayout { alignment: start; padding-top: 4px; + spacing: 8px; + Rectangle { + height: 30px; + border-radius: 8px; + background: gh.has-hover ? Theme.surface-hover : Theme.surface-sunken; + border-width: 1px; + border-color: Theme.border; + accessible-role: button; + accessible-label: "Open HushKey on GitHub"; + accessible-action-default => { root.open-url("https://github.com/X4Lo/HushKey"); } + HorizontalLayout { + padding-left: 12px; + padding-right: 12px; + Text { text: "GitHub ↗"; font-size: 12px; font-weight: 600; color: Theme.accent; vertical-alignment: center; } + } + gh := TouchArea { + mouse-cursor: pointer; + clicked => { root.open-url("https://github.com/X4Lo/HushKey"); } + } + } Rectangle { height: 30px; border-radius: 8px; @@ -540,7 +709,7 @@ export component MainWindow inherits Window { } } Text { - text: "MIT License · Built with Slint (slint.dev) · Created using Claude Opus 5.5"; + text: "github.com/X4Lo/HushKey · MIT License · Built with Slint (slint.dev)"; font-size: 11px; color: Theme.text-faint; wrap: word-wrap; diff --git a/ui/widgets.slint b/ui/widgets.slint index ab31171..da506ca 100644 --- a/ui/widgets.slint +++ b/ui/widgets.slint @@ -258,3 +258,194 @@ export component SectionLabel inherits Text { letter-spacing: 0.8px; color: Theme.text-faint; } + +// Horizontal volume slider. `value` comes from Rust; while dragging the knob follows the +// pointer locally, so periodic refreshes never make it jump under the user's finger. +export component VolumeSlider inherits Rectangle { + in property value; // 0..1 + in property enabled: true; + in property dimmed; // muted: grey fill + in property label; + callback moved(float); // 0..1, fires continuously while dragging + + property drag-value; + property shown: touch.pressed ? drag-value : clamp(value, 0, 1); + property knob: 14px; + + height: 22px; + min-width: 60px; + opacity: enabled ? 1 : 0.4; + + accessible-role: slider; + accessible-label: label; + accessible-value: round(root.shown * 100) + "%"; + accessible-value-minimum: 0; + accessible-value-maximum: 100; + accessible-value-step: 5; + accessible-action-increment => { root.moved(min(1, root.value + 0.05)); } + accessible-action-decrement => { root.moved(max(0, root.value - 0.05)); } + + function set-from(x: length) { + root.drag-value = clamp((x - root.knob / 2) / max(1px, root.width - root.knob), 0, 1); + root.moved(root.drag-value); + } + + Rectangle { + y: (parent.height - 4px) / 2; + height: 4px; + border-radius: 2px; + background: Theme.border; + } + Rectangle { + x: 0; + y: (parent.height - 4px) / 2; + height: 4px; + width: (root.width - root.knob) * root.shown + root.knob / 2; + border-radius: 2px; + background: root.dimmed ? Theme.text-faint : Theme.accent; + } + Rectangle { + x: (root.width - root.knob) * root.shown; + y: (parent.height - root.knob) / 2; + width: root.knob; + height: root.knob; + border-radius: root.knob / 2; + background: white; + border-width: 1px; + border-color: touch.has-hover || touch.pressed ? (root.dimmed ? Theme.text-faint : Theme.accent) : Theme.border-strong; + drop-shadow-blur: 3px; + drop-shadow-color: #00000040; + } + touch := TouchArea { + enabled: root.enabled; + mouse-cursor: pointer; + pointer-event(e) => { + if (e.kind == PointerEventKind.down && e.button == PointerEventButton.left) { + root.set-from(self.mouse-x); + } + } + moved => { + if (self.pressed) { + root.set-from(self.mouse-x); + } + } + scroll-event(e) => { + if (e.delta-y == 0) { + return reject; + } + root.moved(clamp(root.value + (e.delta-y > 0 ? 0.05 : -0.05), 0, 1)); + accept + } + } +} + +// Compact drop-down: shows the selected option, opens a themed popup list. +export component DevicePicker inherits Rectangle { + in property <[string]> options; + in property selected; // index into options, -1 = none + in property label; // accessibility label + in property enabled: true; + in property popup-width: 260px; + callback picked(int); + + property current: selected >= 0 && selected < options.length ? options[selected] : "—"; + + height: 28px; + min-width: 80px; + border-radius: 8px; + border-width: 1px; + border-color: Theme.border; + background: touch.has-hover ? Theme.surface-hover : Theme.surface-sunken; + opacity: enabled ? 1 : 0.5; + animate background { duration: Theme.fast; } + + accessible-role: combobox; + accessible-label: label; + accessible-value: current; + accessible-action-default => { if (root.enabled) { popup.show(); } } + + HorizontalLayout { + padding-left: 10px; + padding-right: 9px; + spacing: 6px; + Text { + text: root.current; + font-size: 12px; + color: Theme.text; + vertical-alignment: center; + overflow: elide; + horizontal-stretch: 1; + } + Path { + width: 9px; + height: 5px; + y: (parent.height - self.height) / 2; + viewbox-width: 10; + viewbox-height: 6; + commands: "M1 1l4 4 4-4"; + stroke: Theme.text-muted; + stroke-width: 1.5px; + fill: transparent; + } + } + touch := TouchArea { + enabled: root.enabled; + mouse-cursor: pointer; + clicked => { popup.show(); } + } + popup := PopupWindow { + x: root.width - root.popup-width; + y: root.height + 4px; + width: root.popup-width; + Rectangle { + background: Theme.surface; + border-radius: 10px; + border-width: 1px; + border-color: Theme.border-strong; + drop-shadow-blur: 16px; + drop-shadow-offset-y: 4px; + drop-shadow-color: #00000059; + VerticalLayout { + padding: 4px; + spacing: 1px; + for option[i] in root.options: Rectangle { + height: 30px; + border-radius: 6px; + background: item.has-hover ? Theme.surface-hover : transparent; + accessible-role: list-item; + accessible-label: option; + accessible-action-default => { root.picked(i); } + HorizontalLayout { + padding-left: 10px; + padding-right: 10px; + spacing: 8px; + Text { + text: option; + font-size: 12px; + font-weight: i == root.selected ? 600 : 400; + color: i == root.selected ? Theme.accent : Theme.text; + vertical-alignment: center; + overflow: elide; + horizontal-stretch: 1; + } + if i == root.selected: Path { + width: 11px; + height: 8px; + y: (parent.height - self.height) / 2; + viewbox-width: 12; + viewbox-height: 9; + commands: "M1 4.5l3.5 3.5 6.5-7"; + stroke: Theme.accent; + stroke-width: 1.7px; + fill: transparent; + } + } + item := TouchArea { + mouse-cursor: pointer; + clicked => { root.picked(i); } + } + } + } + } + } +}