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
This commit is contained in:
1 parent
8f476dbe52
commit
c5cb407481
20 files changed
+1402
-100
No files matched your search
@@ -2,7 +2,8 @@ name: CI
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main, master]
|
||||||
|
workflow_dispatch:
|
||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
|
|||||||
Generated
+2
-1
@@ -1772,7 +1772,7 @@ checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hushkey"
|
name = "hushkey"
|
||||||
version = "1.0.0"
|
version = "1.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"auto-launch",
|
"auto-launch",
|
||||||
"directories",
|
"directories",
|
||||||
@@ -1789,6 +1789,7 @@ dependencies = [
|
|||||||
"toml",
|
"toml",
|
||||||
"tray-icon",
|
"tray-icon",
|
||||||
"windows",
|
"windows",
|
||||||
|
"windows-core",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
+8
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "hushkey"
|
name = "hushkey"
|
||||||
version = "1.0.0"
|
version = "1.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.82"
|
rust-version = "1.82"
|
||||||
description = "Global hotkeys to instantly mute/unmute individual apps — or everything at once."
|
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"] }
|
env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] }
|
||||||
|
|
||||||
[target.'cfg(target_os = "windows")'.dependencies]
|
[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 = [
|
windows = { version = "0.62", features = [
|
||||||
"Win32_Foundation",
|
"Win32_Foundation",
|
||||||
|
"Win32_Devices_FunctionDiscovery",
|
||||||
|
"Win32_Devices_Properties",
|
||||||
"Win32_Media_Audio",
|
"Win32_Media_Audio",
|
||||||
|
"Win32_Media_Audio_Endpoints",
|
||||||
|
"Win32_System_Variant",
|
||||||
|
"Win32_UI_Shell_PropertiesSystem",
|
||||||
"Win32_System_Com",
|
"Win32_System_Com",
|
||||||
"Win32_System_Com_StructuredStorage",
|
"Win32_System_Com_StructuredStorage",
|
||||||
"Win32_System_Threading",
|
"Win32_System_Threading",
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
|
<img src="docs/assets/icon.png" alt="HushKey icon" width="96">
|
||||||
|
|
||||||
# HushKey
|
# HushKey
|
||||||
|
|
||||||
**One keystroke to mute any app. One more to mute everything.**
|
**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.md)
|
[](LICENSE.md)
|
||||||

|

|
||||||

|

|
||||||
|

|
||||||
|
|
||||||
<img src="docs/assets/main-window.webp" alt="HushKey main window" width="460">
|
<img src="docs/assets/main-window.webp" alt="HushKey main window" width="460">
|
||||||
|
|
||||||
@@ -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.
|
- **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.
|
- **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.
|
- **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.
|
- **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.
|
- **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.
|
- **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 |
|
| Detect apps with audio | ✅ WASAPI sessions | ✅ Core Audio process objects | ✅ PulseAudio / PipeWire sink inputs |
|
||||||
| Per-app mute | ✅ | ✅ via process taps | ✅ |
|
| Per-app mute | ✅ | ✅ via process taps | ✅ |
|
||||||
| Per-app volume level | ✅ | ❌ no public API ([why](docs/design-decisions.md#macos-per-app-audio)) | ✅ |
|
| 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)) |
|
| Global shortcuts | ✅ | ✅ | ✅ X11 · ⚠️ Wayland ([details](docs/design-decisions.md#wayland-global-shortcuts)) |
|
||||||
| Tray icon | ✅ | ✅ menu bar | ✅ StatusNotifierItem |
|
| Tray icon | ✅ | ✅ menu bar | ✅ StatusNotifierItem |
|
||||||
| Status | Tested on hardware | Compile-checked, needs testers | Compile-checked, needs testers |
|
| 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
|
- [Design decisions](docs/design-decisions.md) — why Slint, platform limitations and workarounds
|
||||||
- [Contributing](CONTRIBUTING.md)
|
- [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
|
## 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).
|
[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).
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
<sub>HushKey was created using Claude Opus 5.5.</sub>
|
|
||||||
@@ -45,12 +45,19 @@ HushKey is a single Rust binary with four layers. Only `src/audio/{windows,macos
|
|||||||
```rust
|
```rust
|
||||||
pub trait AudioController {
|
pub trait AudioController {
|
||||||
fn backend_name(&self) -> &'static str;
|
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<Vec<AudioApp>>;
|
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>>;
|
||||||
fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()>;
|
fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()>;
|
||||||
fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()>;
|
fn set_app_mute(&mut self, app: &str, muted: bool) -> AudioResult<()>;
|
||||||
fn mute_all(&mut self) -> AudioResult<MuteSnapshot>; // default impl
|
fn mute_all(&mut self) -> AudioResult<MuteSnapshot>; // default impl
|
||||||
fn restore_all(&mut self, snapshot: &MuteSnapshot) -> 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<Vec<OutputDevice>>;
|
||||||
|
fn set_default_output_device(&mut self, id: &str) -> AudioResult<()>;
|
||||||
|
fn master_volume(&mut self) -> AudioResult<MasterVolume>;
|
||||||
|
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<IconData> { None }
|
fn app_icon(&mut self, app: &AudioApp) -> Option<IconData> { None }
|
||||||
fn platform_note(&self) -> Option<&'static str> { None }
|
fn platform_note(&self) -> Option<&'static str> { None }
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 4.4 KiB |
@@ -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.
|
- 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.
|
- 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
|
## 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:
|
**HushKey uses option 2.** As a result:
|
||||||
|
|
||||||
- ✅ Per-app **mute/unmute** works (that's all HushKey's shortcuts need).
|
- ✅ 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 **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)).
|
- 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.
|
- 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
|
### 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 <pid>" with a PID-based key, which can't be bound persistently.
|
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 <pid>" 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.
|
||||||
+156
-31
@@ -6,11 +6,11 @@
|
|||||||
//! surfaces, render buffers or UI trees.
|
//! surfaces, render buffers or UI trees.
|
||||||
|
|
||||||
use crate::audio::worker::{self, AudioCommand, AudioEvent, AudioHandle};
|
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::config::{Config, ConfigStore, Theme};
|
||||||
use crate::hotkeys::{capture_from_key_event, Accelerator, Capture, HotkeyAction, Hotkeys};
|
use crate::hotkeys::{capture_from_key_event, Accelerator, Capture, HotkeyAction, Hotkeys};
|
||||||
use crate::platform;
|
use crate::platform;
|
||||||
use crate::ui::icon::{self, IconState};
|
use crate::ui::icon::IconState;
|
||||||
use crate::ui::toast::ToastPresenter;
|
use crate::ui::toast::ToastPresenter;
|
||||||
use crate::ui::tray::{Tray, TrayCommand};
|
use crate::ui::tray::{Tray, TrayCommand};
|
||||||
use crate::{AppRow, MainWindow};
|
use crate::{AppRow, MainWindow};
|
||||||
@@ -23,6 +23,7 @@ use std::time::Duration;
|
|||||||
const REFRESH_EVERY: Duration = Duration::from_millis(1500);
|
const REFRESH_EVERY: Duration = Duration::from_millis(1500);
|
||||||
const TARGET_ALL: &str = "@all";
|
const TARGET_ALL: &str = "@all";
|
||||||
const TARGET_RESTORE: &str = "@restore";
|
const TARGET_RESTORE: &str = "@restore";
|
||||||
|
const SYSTEM_DEFAULT_LABEL: &str = "System default";
|
||||||
|
|
||||||
thread_local! {
|
thread_local! {
|
||||||
static APP: RefCell<Option<Rc<App>>> = const { RefCell::new(None) };
|
static APP: RefCell<Option<Rc<App>>> = const { RefCell::new(None) };
|
||||||
@@ -49,6 +50,11 @@ pub struct App {
|
|||||||
rows: Rc<VecModel<AppRow>>,
|
rows: Rc<VecModel<AppRow>>,
|
||||||
apps: RefCell<Vec<AudioApp>>,
|
apps: RefCell<Vec<AudioApp>>,
|
||||||
icons: RefCell<HashMap<String, slint::Image>>,
|
icons: RefCell<HashMap<String, slint::Image>>,
|
||||||
|
devices: RefCell<Vec<OutputDevice>>,
|
||||||
|
master: Cell<Option<MasterVolume>>,
|
||||||
|
/// Device names for the system picker, and "System default" + names for app pickers.
|
||||||
|
device_names: Rc<VecModel<SharedString>>,
|
||||||
|
app_device_options: Rc<VecModel<SharedString>>,
|
||||||
all_muted: Cell<bool>,
|
all_muted: Cell<bool>,
|
||||||
caps: Cell<Capabilities>,
|
caps: Cell<Capabilities>,
|
||||||
backend: RefCell<String>,
|
backend: RefCell<String>,
|
||||||
@@ -98,8 +104,12 @@ impl App {
|
|||||||
rows: Rc::new(VecModel::default()),
|
rows: Rc::new(VecModel::default()),
|
||||||
apps: RefCell::default(),
|
apps: RefCell::default(),
|
||||||
icons: 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),
|
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()),
|
backend: RefCell::new("starting…".into()),
|
||||||
platform_note: RefCell::default(),
|
platform_note: RefCell::default(),
|
||||||
capturing: RefCell::new(None),
|
capturing: RefCell::new(None),
|
||||||
@@ -231,6 +241,8 @@ impl App {
|
|||||||
w.set_version(env!("CARGO_PKG_VERSION").into());
|
w.set_version(env!("CARGO_PKG_VERSION").into());
|
||||||
w.set_config_path(self.store.path().display().to_string().into());
|
w.set_config_path(self.store.path().display().to_string().into());
|
||||||
w.set_apps(ModelRc::from(self.rows.clone()));
|
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(|| {
|
w.window().on_close_requested(|| {
|
||||||
// Can't drop the component from inside its own callback; do it next tick.
|
// Can't drop the component from inside its own callback; do it next tick.
|
||||||
@@ -264,6 +276,24 @@ impl App {
|
|||||||
w.on_dismiss_status(|| {
|
w.on_dismiss_status(|| {
|
||||||
with_app(|a| a.set_status("", false));
|
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(|| {
|
w.on_open_config_dir(|| {
|
||||||
with_app(|a| {
|
with_app(|a| {
|
||||||
if let Some(dir) = a.store.path().parent() {
|
if let Some(dir) = a.store.path().parent() {
|
||||||
@@ -299,7 +329,11 @@ impl App {
|
|||||||
fn push_all(&self, w: &MainWindow) {
|
fn push_all(&self, w: &MainWindow) {
|
||||||
w.set_backend(self.backend.borrow().as_str().into());
|
w.set_backend(self.backend.borrow().as_str().into());
|
||||||
w.set_platform_note(self.platform_note.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());
|
w.set_all_muted(self.all_muted.get());
|
||||||
let (msg, err) = self.status.borrow().clone();
|
let (msg, err) = self.status.borrow().clone();
|
||||||
w.set_status(msg.into());
|
w.set_status(msg.into());
|
||||||
@@ -308,9 +342,98 @@ impl App {
|
|||||||
w.set_hotkey_hint("Press a combo · Esc cancels · Backspace clears".into());
|
w.set_hotkey_hint("Press a combo · Esc cancels · Backspace clears".into());
|
||||||
self.push_settings_to(w);
|
self.push_settings_to(w);
|
||||||
self.push_shortcuts_to(w);
|
self.push_shortcuts_to(w);
|
||||||
|
self.push_output_to(w);
|
||||||
self.sync_rows();
|
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<SharedString> = devices.iter().map(|d| SharedString::from(d.name.as_str())).collect();
|
||||||
|
let current: Vec<SharedString> = 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) {
|
fn push_settings(&self) {
|
||||||
if let Some(w) = self.ui() {
|
if let Some(w) = self.ui() {
|
||||||
self.push_settings_to(&w);
|
self.push_settings_to(&w);
|
||||||
@@ -348,27 +471,19 @@ impl App {
|
|||||||
let cfg = self.cfg.borrow();
|
let cfg = self.cfg.borrow();
|
||||||
let apps = self.apps.borrow();
|
let apps = self.apps.borrow();
|
||||||
let icons = self.icons.borrow();
|
let icons = self.icons.borrow();
|
||||||
|
let devices = self.devices.borrow();
|
||||||
let caps = self.caps.get();
|
let caps = self.caps.get();
|
||||||
|
|
||||||
let mut rows: Vec<AppRow> = Vec::with_capacity(apps.len() + cfg.bindings.len());
|
let mut rows: Vec<AppRow> = Vec::with_capacity(apps.len() + cfg.bindings.len());
|
||||||
for a in apps.iter() {
|
for a in apps.iter() {
|
||||||
let status = if a.muted {
|
let status = if a.muted { "Muted" } else { "Active" };
|
||||||
"Muted".to_owned()
|
let mut row =
|
||||||
} else if let (true, Some(v)) = (caps.per_app_volume, a.volume) {
|
make_row(&a.key, &a.name, &format!("{status} · {}", a.key), true, a.muted, a.volume, &cfg, &icons);
|
||||||
format!("Volume {}%", (v * 100.0).round())
|
row.volume = if caps.per_app_volume { a.volume.unwrap_or(-1.0) } else { -1.0 };
|
||||||
} else {
|
row.routable = a.routable;
|
||||||
"Active".to_owned()
|
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(make_row(
|
rows.push(row);
|
||||||
&a.key,
|
|
||||||
&a.name,
|
|
||||||
&format!("{status} · {}", a.key),
|
|
||||||
true,
|
|
||||||
a.muted,
|
|
||||||
a.volume,
|
|
||||||
&cfg,
|
|
||||||
&icons,
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
// Bound apps that aren't running stay visible so their shortcut can be edited.
|
// Bound apps that aren't running stay visible so their shortcut can be edited.
|
||||||
for b in &cfg.bindings {
|
for b in &cfg.bindings {
|
||||||
@@ -419,6 +534,18 @@ impl App {
|
|||||||
*self.apps.borrow_mut() = apps;
|
*self.apps.borrow_mut() = apps;
|
||||||
self.sync_rows();
|
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 } => {
|
AudioEvent::Icon { key, icon } => {
|
||||||
self.icons.borrow_mut().insert(key, crate::ui::image_from_icon(&icon));
|
self.icons.borrow_mut().insert(key, crate::ui::image_from_icon(&icon));
|
||||||
self.sync_rows();
|
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) {
|
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 }));
|
w.set_theme(Some(if dark { WinitTheme::Dark } else { WinitTheme::Light }));
|
||||||
// Small icon: title bar / Alt+Tab.
|
w.set_window_icon(crate::ui::winit_icon(32));
|
||||||
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.
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
use slint::winit_030::winit::platform::windows::WindowExtWindows;
|
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(crate::ui::winit_icon(64));
|
||||||
w.set_taskbar_icon(Some(icon));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -674,5 +797,7 @@ fn make_row(
|
|||||||
muted,
|
muted,
|
||||||
volume: volume.unwrap_or(-1.0),
|
volume: volume.unwrap_or(-1.0),
|
||||||
shortcut: label(cfg.binding_for(key).map(|b| b.hotkey.as_str())).into(),
|
shortcut: label(cfg.binding_for(key).map(|b| b.hotkey.as_str())).into(),
|
||||||
|
routable: false,
|
||||||
|
device_index: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+119
-3
@@ -3,12 +3,14 @@
|
|||||||
//!
|
//!
|
||||||
//! Every playback stream an app opens is a *sink input*; that includes paused/corked
|
//! 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
|
//! 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
|
//! 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.
|
//! 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 libpulse_binding as pulse;
|
||||||
use pulse::callbacks::ListResult;
|
use pulse::callbacks::ListResult;
|
||||||
use pulse::context::{Context, FlagSet, State};
|
use pulse::context::{Context, FlagSet, State};
|
||||||
@@ -29,6 +31,17 @@ struct Input {
|
|||||||
muted: bool,
|
muted: bool,
|
||||||
volume: f32,
|
volume: f32,
|
||||||
channels: u8,
|
channels: u8,
|
||||||
|
sink: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct Sink {
|
||||||
|
index: u32,
|
||||||
|
name: String,
|
||||||
|
description: String,
|
||||||
|
volume: f32,
|
||||||
|
muted: bool,
|
||||||
|
channels: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct PulseController {
|
pub struct PulseController {
|
||||||
@@ -95,6 +108,7 @@ impl PulseController {
|
|||||||
muted: i.mute,
|
muted: i.mute,
|
||||||
volume: i.volume.avg().0 as f32 / Volume::NORMAL.0 as f32,
|
volume: i.volume.avg().0 as f32 / Volume::NORMAL.0 as f32,
|
||||||
channels: i.volume.len(),
|
channels: i.volume.len(),
|
||||||
|
sink: i.sink,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -103,6 +117,46 @@ impl PulseController {
|
|||||||
Ok(v)
|
Ok(v)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sinks(&mut self) -> AudioResult<Vec<Sink>> {
|
||||||
|
let out: Rc<RefCell<Vec<Sink>>> = 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<Option<String>> {
|
||||||
|
let out: Rc<RefCell<Option<String>>> = 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<Sink> {
|
||||||
|
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(
|
fn for_each_input_of(
|
||||||
&mut self,
|
&mut self,
|
||||||
app: &str,
|
app: &str,
|
||||||
@@ -126,10 +180,18 @@ impl AudioController for PulseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn capabilities(&self) -> Capabilities {
|
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<Vec<AudioApp>> {
|
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
|
||||||
|
let sinks = self.sinks().unwrap_or_default();
|
||||||
|
let default_sink = self.default_sink_name().ok().flatten();
|
||||||
let mut grouped: BTreeMap<String, Vec<Input>> = BTreeMap::new();
|
let mut grouped: BTreeMap<String, Vec<Input>> = BTreeMap::new();
|
||||||
for i in self.inputs()? {
|
for i in self.inputs()? {
|
||||||
grouped.entry(i.key.clone()).or_default().push(i);
|
grouped.entry(i.key.clone()).or_default().push(i);
|
||||||
@@ -139,7 +201,16 @@ impl AudioController for PulseController {
|
|||||||
.map(|(key, ins)| {
|
.map(|(key, ins)| {
|
||||||
let mut pids: Vec<u32> = ins.iter().map(|i| i.pid).filter(|p| *p != 0).collect();
|
let mut pids: Vec<u32> = ins.iter().map(|i| i.pid).filter(|p| *p != 0).collect();
|
||||||
pids.dedup();
|
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 {
|
AudioApp {
|
||||||
|
device,
|
||||||
|
routable: true,
|
||||||
name: ins[0].name.clone(),
|
name: ins[0].name.clone(),
|
||||||
volume: Some(ins.iter().map(|i| i.volume).sum::<f32>() / ins.len() as f32),
|
volume: Some(ins.iter().map(|i| i.volume).sum::<f32>() / ins.len() as f32),
|
||||||
muted: ins.iter().all(|i| i.muted),
|
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<()> {
|
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))
|
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<Vec<OutputDevice>> {
|
||||||
|
let default = self.default_sink_name()?;
|
||||||
|
let mut out: Vec<OutputDevice> = 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<MasterVolume> {
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+160
-4
@@ -11,6 +11,9 @@
|
|||||||
//!
|
//!
|
||||||
//! Consequences:
|
//! Consequences:
|
||||||
//! - Per-app **mute works**; per-app **volume levels do not** (`per_app_volume: false`).
|
//! - 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`
|
//! `set_app_volume` accepts only 0.0 (mute) and 1.0 (unmute) and reports `Unsupported`
|
||||||
//! for anything in between — it never fakes a level.
|
//! 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
|
//! - 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-
|
//! **Untested on real hardware by the original author** (developed on Windows, compile-
|
||||||
//! checked for `aarch64-apple-darwin`). Reports from macOS users are very welcome.
|
//! 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::msg_send;
|
||||||
use objc2::rc::Retained;
|
use objc2::rc::Retained;
|
||||||
use objc2::runtime::{AnyClass, AnyObject};
|
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_PID: u32 = fourcc(b"ppid");
|
||||||
const K_PROCESS_BUNDLE_ID: u32 = fourcc(b"pbid");
|
const K_PROCESS_BUNDLE_ID: u32 = fourcc(b"pbid");
|
||||||
const K_PROCESS_IS_RUNNING_OUTPUT: u32 = fourcc(b"piro");
|
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`
|
/// `CATapMuteBehavior.CATapMuted`
|
||||||
const CA_TAP_MUTED: isize = 1;
|
const CA_TAP_MUTED: isize = 1;
|
||||||
|
|
||||||
@@ -75,6 +88,35 @@ extern "C" {
|
|||||||
io_size: *mut u32,
|
io_size: *mut u32,
|
||||||
out: *mut c_void,
|
out: *mut c_void,
|
||||||
) -> OSStatus;
|
) -> 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;
|
type CreateTapFn = unsafe extern "C" fn(*mut AnyObject, *mut AudioObjectID) -> OSStatus;
|
||||||
@@ -201,7 +243,13 @@ impl AudioController for CoreAudioTapController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn capabilities(&self) -> Capabilities {
|
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<Vec<AudioApp>> {
|
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
|
||||||
@@ -245,6 +293,8 @@ impl AudioController for CoreAudioTapController {
|
|||||||
pids: ps.iter().map(|p| p.pid).collect(),
|
pids: ps.iter().map(|p| p.pid).collect(),
|
||||||
volume: None, // not readable per-app on macOS
|
volume: None, // not readable per-app on macOS
|
||||||
exe_path: ps[0].path.clone(),
|
exe_path: ps[0].path.clone(),
|
||||||
|
device: None,
|
||||||
|
routable: false,
|
||||||
key,
|
key,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
@@ -282,10 +332,70 @@ impl AudioController for CoreAudioTapController {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn output_devices(&mut self) -> AudioResult<Vec<OutputDevice>> {
|
||||||
|
let default = default_output_device();
|
||||||
|
let ids: Vec<AudioObjectID> = 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<AudioObjectID> = 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<MasterVolume> {
|
||||||
|
let dev = default_output_device().ok_or_else(|| AudioError::Backend("no output device".into()))?;
|
||||||
|
let volume = unsafe { service_get::<f32>(dev, output_addr(K_VIRTUAL_MAIN_VOLUME)) }
|
||||||
|
.or_else(|| unsafe { get_at::<f32>(dev, output_addr(K_DEVICE_VOLUME_SCALAR)) });
|
||||||
|
let muted = unsafe { get_at::<u32>(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> {
|
fn platform_note(&self) -> Option<&'static str> {
|
||||||
Some(if self.api.is_some() {
|
Some(if self.api.is_some() {
|
||||||
"macOS can mute individual apps but can't set their volume level. Muting needs the \
|
"macOS can mute individual apps but can't set their volume level or output device. \
|
||||||
Screen & System Audio Recording permission."
|
Muting needs the Screen & System Audio Recording permission."
|
||||||
} else {
|
} else {
|
||||||
"Per-app muting needs macOS 14.2 or newer. Apps are listed read-only."
|
"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 }
|
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<AudioObjectID> {
|
||||||
|
unsafe { get_scalar::<AudioObjectID>(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<T: Copy + Default>(object: AudioObjectID, a: AudioObjectPropertyAddress) -> Option<T> {
|
||||||
|
let mut v = T::default();
|
||||||
|
let mut size = std::mem::size_of::<T>() 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<T: Copy + Default>(object: AudioObjectID, a: AudioObjectPropertyAddress) -> Option<T> {
|
||||||
|
let mut v = T::default();
|
||||||
|
let mut size = std::mem::size_of::<T>() 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<T: Copy + Default>(object: AudioObjectID, selector: u32) -> AudioResult<Vec<T>> {
|
unsafe fn get_array<T: Copy + Default>(object: AudioObjectID, selector: u32) -> AudioResult<Vec<T>> {
|
||||||
let a = addr(selector);
|
let a = addr(selector);
|
||||||
let mut size = 0u32;
|
let mut size = 0u32;
|
||||||
|
|||||||
+68
-14
@@ -5,16 +5,19 @@
|
|||||||
//! (see [`worker`]) so they may hold thread-affine handles (COM objects, the
|
//! (see [`worker`]) so they may hold thread-affine handles (COM objects, the
|
||||||
//! PulseAudio mainloop, CoreAudio taps) without being `Send`.
|
//! PulseAudio mainloop, CoreAudio taps) without being `Send`.
|
||||||
//!
|
//!
|
||||||
//! | OS | Mechanism | Per-app volume | Per-app mute |
|
//! | OS | Mechanism | Per-app volume | Per-app mute | Per-app device |
|
||||||
//! |---------|---------------------------------------------|----------------|--------------|
|
//! |---------|-----------------------------------------|----------------|--------------|----------------|
|
||||||
//! | Windows | WASAPI `IAudioSessionManager2` sessions | yes | yes |
|
//! | Windows | WASAPI `IAudioSessionManager2` sessions | yes | yes | yes |
|
||||||
//! | Linux | PulseAudio / PipeWire-pulse sink inputs | yes | yes |
|
//! | Linux | PulseAudio / PipeWire-pulse sink inputs | yes | yes | yes |
|
||||||
//! | macOS | Core Audio process taps (macOS 14.2+) | **no** | 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
|
//! System volume, system mute and switching the default output device work on all three.
|
||||||
//! app by creating a *muted process tap* on it, which silences that process while
|
//!
|
||||||
|
//! 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
|
//! 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;
|
mod mute;
|
||||||
pub mod worker;
|
pub mod worker;
|
||||||
@@ -55,12 +58,39 @@ pub struct AudioApp {
|
|||||||
pub muted: bool,
|
pub muted: bool,
|
||||||
/// Executable path for icon lookup, when known.
|
/// Executable path for icon lookup, when known.
|
||||||
pub exe_path: Option<PathBuf>,
|
pub exe_path: Option<PathBuf>,
|
||||||
|
/// [`OutputDevice::id`] this app is explicitly routed to; `None` = follows the system default.
|
||||||
|
pub device: Option<String>,
|
||||||
|
/// 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<f32>,
|
||||||
|
pub muted: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
pub struct Capabilities {
|
pub struct Capabilities {
|
||||||
pub per_app_volume: bool,
|
pub per_app_volume: bool,
|
||||||
pub per_app_mute: 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)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -68,7 +98,6 @@ pub enum AudioError {
|
|||||||
/// No running app has this key right now.
|
/// No running app has this key right now.
|
||||||
NotRunning(AppKey),
|
NotRunning(AppKey),
|
||||||
/// The platform can't do this (see the capability table above).
|
/// The platform can't do this (see the capability table above).
|
||||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
|
||||||
Unsupported(&'static str),
|
Unsupported(&'static str),
|
||||||
/// The OS needs a permission the user hasn't granted (macOS audio capture).
|
/// The OS needs a permission the user hasn't granted (macOS audio capture).
|
||||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
#[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`].
|
/// idle ones that aren't currently producing sound. One entry per [`AppKey`].
|
||||||
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>>;
|
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>>;
|
||||||
|
|
||||||
/// Set the volume of every session of `app` (0.0..=1.0).
|
/// Set the volume of every session of `app` (0.0..=1.0). Independent of the mute flag.
|
||||||
/// 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)]
|
|
||||||
fn set_app_volume(&mut self, app: &str, volume: f32) -> AudioResult<()>;
|
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
|
/// Mute/unmute every session of `app`. Uses the OS mixer's own mute flag, so the
|
||||||
@@ -151,6 +177,34 @@ pub trait AudioController {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Active output devices, default first is *not* guaranteed (check `is_default`).
|
||||||
|
fn output_devices(&mut self) -> AudioResult<Vec<OutputDevice>> {
|
||||||
|
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<MasterVolume> {
|
||||||
|
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).
|
/// Best-effort app icon. Default: none (UI shows a letter avatar).
|
||||||
fn app_icon(&mut self, _app: &AudioApp) -> Option<IconData> {
|
fn app_icon(&mut self, _app: &AudioApp) -> Option<IconData> {
|
||||||
None
|
None
|
||||||
|
|||||||
+3
-1
@@ -22,6 +22,8 @@ impl NullController {
|
|||||||
volume: Some(1.0),
|
volume: Some(1.0),
|
||||||
muted: *muted,
|
muted: *muted,
|
||||||
exe_path: None,
|
exe_path: None,
|
||||||
|
device: None,
|
||||||
|
routable: true,
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
mute_calls: 0,
|
mute_calls: 0,
|
||||||
@@ -39,7 +41,7 @@ impl AudioController for NullController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn capabilities(&self) -> Capabilities {
|
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<Vec<AudioApp>> {
|
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
|
||||||
|
|||||||
+295
-10
@@ -5,26 +5,44 @@
|
|||||||
//! active render device**, not just the default one, so apps routed to headphones
|
//! 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.
|
//! 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).
|
//! 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::collections::{BTreeMap, HashMap};
|
||||||
use std::ffi::c_void;
|
use std::ffi::c_void;
|
||||||
use std::os::windows::ffi::OsStrExt;
|
use std::os::windows::ffi::OsStrExt;
|
||||||
use std::path::{Path, PathBuf};
|
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::Foundation::{CloseHandle, S_OK};
|
||||||
use windows::Win32::Graphics::Gdi::{
|
use windows::Win32::Graphics::Gdi::{
|
||||||
DeleteObject, GetDC, GetDIBits, GetObjectW, ReleaseDC, BITMAP, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS,
|
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::{
|
use windows::Win32::Media::Audio::{
|
||||||
eRender, AudioSessionStateExpired, IAudioSessionControl2, IAudioSessionManager2, IMMDeviceEnumerator,
|
eConsole, eMultimedia, eRender, AudioSessionStateExpired, IAudioSessionControl2, IAudioSessionManager2, IMMDevice,
|
||||||
ISimpleAudioVolume, MMDeviceEnumerator, DEVICE_STATE_ACTIVE,
|
IMMDeviceEnumerator, ISimpleAudioVolume, MMDeviceEnumerator, DEVICE_STATE_ACTIVE,
|
||||||
};
|
};
|
||||||
use windows::Win32::Storage::FileSystem::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW};
|
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::{
|
use windows::Win32::System::Threading::{
|
||||||
OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
|
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 SYSTEM_SOUNDS_KEY: &str = "system-sounds";
|
||||||
const ICON_SIZE: u32 = 64;
|
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<IAudioPolicyConfigFactory> {
|
||||||
|
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 {
|
fn err(context: &str, e: windows::core::Error) -> AudioError {
|
||||||
AudioError::Backend(format!("{context}: {e}"))
|
AudioError::Backend(format!("{context}: {e}"))
|
||||||
}
|
}
|
||||||
@@ -62,6 +177,8 @@ impl Drop for ComGuard {
|
|||||||
pub struct WasapiController {
|
pub struct WasapiController {
|
||||||
enumerator: IMMDeviceEnumerator,
|
enumerator: IMMDeviceEnumerator,
|
||||||
procs: HashMap<u32, ProcInfo>,
|
procs: HashMap<u32, ProcInfo>,
|
||||||
|
device_names: HashMap<String, String>,
|
||||||
|
policy: Option<IAudioPolicyConfigFactory>,
|
||||||
_com: ComGuard,
|
_com: ComGuard,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,10 +189,55 @@ impl WasapiController {
|
|||||||
let guard = ComGuard;
|
let guard = ComGuard;
|
||||||
let enumerator: IMMDeviceEnumerator =
|
let enumerator: IMMDeviceEnumerator =
|
||||||
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).map_err(|e| err("MMDeviceEnumerator", e))?;
|
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<IMMDevice> {
|
||||||
|
unsafe { self.enumerator.GetDefaultAudioEndpoint(eRender, eMultimedia) }.map_err(|e| err("default device", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn endpoint_volume(&self) -> AudioResult<IAudioEndpointVolume> {
|
||||||
|
let device = self.default_device()?;
|
||||||
|
unsafe { device.Activate::<IAudioEndpointVolume>(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<String> {
|
||||||
|
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 {
|
fn proc_info(&mut self, pid: u32) -> ProcInfo {
|
||||||
if let Some(p) = self.procs.get(&pid) {
|
if let Some(p) = self.procs.get(&pid) {
|
||||||
return p.clone();
|
return p.clone();
|
||||||
@@ -160,7 +322,13 @@ impl AudioController for WasapiController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn capabilities(&self) -> Capabilities {
|
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<Vec<AudioApp>> {
|
fn list_audio_apps(&mut self) -> AudioResult<Vec<AudioApp>> {
|
||||||
@@ -181,14 +349,17 @@ impl AudioController for WasapiController {
|
|||||||
let mut apps: Vec<AudioApp> = grouped
|
let mut apps: Vec<AudioApp> = grouped
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(key, (pids, vols, muted))| {
|
.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)
|
("System Sounds".to_owned(), None)
|
||||||
} else {
|
} else {
|
||||||
let info = pids.iter().find_map(|p| self.procs.get(p)).cloned();
|
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))
|
info.map(|i| (i.name, i.path)).unwrap_or_else(|| (key.clone(), None))
|
||||||
};
|
};
|
||||||
let volume = Some(vols.iter().sum::<f32>() / vols.len().max(1) as f32);
|
let volume = Some(vols.iter().sum::<f32>() / 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();
|
.collect();
|
||||||
apps.sort_by_key(|a| a.name.to_lowercase());
|
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()) })
|
self.for_each_session_of(app, |s| unsafe { s.SetMute(muted, std::ptr::null()) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn output_devices(&mut self) -> AudioResult<Vec<OutputDevice>> {
|
||||||
|
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<MasterVolume> {
|
||||||
|
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<u32> = 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<IconData> {
|
fn app_icon(&mut self, app: &AudioApp) -> Option<IconData> {
|
||||||
exe_icon(app.exe_path.as_deref()?)
|
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<String> {
|
||||||
|
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<u16> {
|
fn wide(path: &Path) -> Vec<u16> {
|
||||||
path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
|
path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
|
||||||
}
|
}
|
||||||
@@ -337,3 +609,16 @@ unsafe fn hicon_to_rgba(icon: HICON) -> Option<IconData> {
|
|||||||
}
|
}
|
||||||
Some(IconData { width: w as u32, height: h as u32, rgba: buf })
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+122
-5
@@ -6,10 +6,16 @@
|
|||||||
//!
|
//!
|
||||||
//! The thread blocks on its channel when idle — zero CPU. The only periodic work is
|
//! 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.
|
//! 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::mute::ToggleOutcome;
|
||||||
use super::{create_controller, AudioApp, AudioError, Capabilities, IconData, MuteManager};
|
use super::{
|
||||||
use std::collections::HashSet;
|
create_controller, AudioApp, AudioController, AudioError, Capabilities, IconData, MasterVolume, MuteManager,
|
||||||
|
OutputDevice,
|
||||||
|
};
|
||||||
|
use std::collections::{HashSet, VecDeque};
|
||||||
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
||||||
use std::thread::JoinHandle;
|
use std::thread::JoinHandle;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -30,9 +36,43 @@ pub enum AudioCommand {
|
|||||||
RestoreAll {
|
RestoreAll {
|
||||||
from_hotkey: bool,
|
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<String>,
|
||||||
|
},
|
||||||
Shutdown,
|
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>) -> 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)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum AudioEvent {
|
pub enum AudioEvent {
|
||||||
Ready {
|
Ready {
|
||||||
@@ -41,6 +81,11 @@ pub enum AudioEvent {
|
|||||||
note: Option<&'static str>,
|
note: Option<&'static str>,
|
||||||
},
|
},
|
||||||
Apps(Vec<AudioApp>),
|
Apps(Vec<AudioApp>),
|
||||||
|
/// Output devices and system volume. `master` is `None` when unsupported/unavailable.
|
||||||
|
Output {
|
||||||
|
devices: Vec<OutputDevice>,
|
||||||
|
master: Option<MasterVolume>,
|
||||||
|
},
|
||||||
Icon {
|
Icon {
|
||||||
key: String,
|
key: String,
|
||||||
icon: IconData,
|
icon: IconData,
|
||||||
@@ -118,8 +163,9 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
|
|||||||
let mut mute = MuteManager::default();
|
let mut mute = MuteManager::default();
|
||||||
let mut icons_sent: HashSet<String> = HashSet::new();
|
let mut icons_sent: HashSet<String> = HashSet::new();
|
||||||
|
|
||||||
let publish_apps =
|
let caps = ctl.capabilities();
|
||||||
|ctl: &mut dyn super::AudioController, icons_sent: &mut HashSet<String>| match ctl.list_audio_apps() {
|
let publish_apps = |ctl: &mut dyn AudioController, icons_sent: &mut HashSet<String>| {
|
||||||
|
match ctl.list_audio_apps() {
|
||||||
Ok(apps) => {
|
Ok(apps) => {
|
||||||
for app in &apps {
|
for app in &apps {
|
||||||
if icons_sent.insert(app.key.clone()) {
|
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));
|
sink(AudioEvent::Apps(apps));
|
||||||
}
|
}
|
||||||
Err(e) => sink(AudioEvent::Error { message: e.to_string(), from_hotkey: false }),
|
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<AudioCommand> = VecDeque::new();
|
||||||
|
|
||||||
loop {
|
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) {
|
match rx.recv_timeout(ENFORCE_INTERVAL) {
|
||||||
Ok(cmd) => cmd,
|
Ok(cmd) => cmd,
|
||||||
Err(RecvTimeoutError::Timeout) => {
|
Err(RecvTimeoutError::Timeout) => {
|
||||||
@@ -148,6 +211,12 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
|
|||||||
} else {
|
} else {
|
||||||
rx.recv().unwrap_or(AudioCommand::Shutdown)
|
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 {
|
match cmd {
|
||||||
AudioCommand::Refresh => {
|
AudioCommand::Refresh => {
|
||||||
@@ -176,6 +245,24 @@ pub fn spawn(sink: impl Fn(AudioEvent) + Send + 'static) -> AudioHandle {
|
|||||||
}
|
}
|
||||||
publish_apps(ctl.as_mut(), &mut icons_sent);
|
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 => {
|
AudioCommand::Shutdown => {
|
||||||
if let Err(e) = mute.restore_all(ctl.as_mut()) {
|
if let Err(e) = mute.restore_all(ctl.as_mut()) {
|
||||||
log::warn!("restore on shutdown failed: {e}");
|
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");
|
.expect("spawn audio thread");
|
||||||
AudioHandle { tx, thread: Some(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<AudioCommand> =
|
||||||
|
[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> = [AudioCommand::Refresh].into_iter().collect();
|
||||||
|
assert!(matches!(coalesce(AudioCommand::SetMasterMute(true), &mut pending), AudioCommand::SetMasterMute(true)));
|
||||||
|
assert_eq!(pending.len(), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
-1
@@ -106,9 +106,31 @@ fn list_apps() {
|
|||||||
Ok(apps) => {
|
Ok(apps) => {
|
||||||
for a in apps {
|
for a in apps {
|
||||||
let vol = a.volume.map(|v| format!("{:>3.0}%", v * 100.0)).unwrap_or_else(|| " — ".into());
|
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}"),
|
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}"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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 ────────────────────────────────────────────────────────────
|
// ── Single instance ────────────────────────────────────────────────────────────
|
||||||
// A loopback-only socket doubles as lock and "show yourself" signal: launching HushKey
|
// 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.
|
// again just brings the running window up. Loopback binds don't trigger firewall prompts.
|
||||||
|
|||||||
@@ -39,3 +39,23 @@ pub fn icon_image(size: u32, state: IconState) -> slint::Image {
|
|||||||
let buf = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::clone_from_slice(&rgba, size, size);
|
let buf = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::clone_from_slice(&rgba, size, size);
|
||||||
slint::Image::from_rgba8(buf)
|
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> {
|
||||||
|
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
|
||||||
|
}
|
||||||
+1
-1
@@ -30,7 +30,7 @@ const BOTTOM_MARGIN: f64 = 110.0;
|
|||||||
/// Window-attribute hook: applied to every winit window Slint creates.
|
/// Window-attribute hook: applied to every winit window Slint creates.
|
||||||
pub fn window_attributes_hook(attrs: winit::window::WindowAttributes) -> winit::window::WindowAttributes {
|
pub fn window_attributes_hook(attrs: winit::window::WindowAttributes) -> winit::window::WindowAttributes {
|
||||||
if !NEXT_WINDOW_IS_TOAST.with(|f| f.replace(false)) {
|
if !NEXT_WINDOW_IS_TOAST.with(|f| f.replace(false)) {
|
||||||
return attrs;
|
return super::with_app_icons(attrs);
|
||||||
}
|
}
|
||||||
let attrs = attrs
|
let attrs = attrs
|
||||||
.with_active(false)
|
.with_active(false)
|
||||||
|
|||||||
+188
-19
@@ -1,7 +1,8 @@
|
|||||||
import { ListView, ScrollView, Palette } from "std-widgets.slint";
|
import { ListView, ScrollView, Palette } from "std-widgets.slint";
|
||||||
import { Theme } from "theme.slint";
|
import { Theme } from "theme.slint";
|
||||||
import {
|
import {
|
||||||
SpeakerIcon, ThemeIcon, IconButton, Tabs, Switch, ShortcutChip, SettingRow, Card, SectionLabel
|
SpeakerIcon, ThemeIcon, IconButton, Tabs, Switch, ShortcutChip, SettingRow, Card, SectionLabel,
|
||||||
|
VolumeSlider, DevicePicker
|
||||||
} from "widgets.slint";
|
} from "widgets.slint";
|
||||||
|
|
||||||
export { Toast } from "toast.slint";
|
export { Toast } from "toast.slint";
|
||||||
@@ -18,6 +19,8 @@ export struct AppRow {
|
|||||||
muted: bool,
|
muted: bool,
|
||||||
volume: float, // 0..1, < 0 when unknown
|
volume: float, // 0..1, < 0 when unknown
|
||||||
shortcut: string, // display label, "" when unbound
|
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 {
|
component Avatar inherits Rectangle {
|
||||||
@@ -71,11 +74,17 @@ component AppRowView inherits Rectangle {
|
|||||||
in property <AppRow> app;
|
in property <AppRow> app;
|
||||||
in property <bool> capturing;
|
in property <bool> capturing;
|
||||||
in property <bool> show-volume;
|
in property <bool> show-volume;
|
||||||
|
in property <bool> show-device;
|
||||||
|
in property <[string]> device-options;
|
||||||
callback toggle();
|
callback toggle();
|
||||||
callback capture();
|
callback capture();
|
||||||
callback clear();
|
callback clear();
|
||||||
|
callback volume-moved(float);
|
||||||
|
callback device-picked(int);
|
||||||
|
|
||||||
|
property <bool> has-volume: show-volume && app.running && app.volume >= 0;
|
||||||
|
property <bool> has-device: show-device && app.running && app.routable;
|
||||||
|
|
||||||
height: 64px;
|
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
background: hover.has-hover ? Theme.surface-hover : Theme.surface;
|
background: hover.has-hover ? Theme.surface-hover : Theme.surface;
|
||||||
border-width: 1px;
|
border-width: 1px;
|
||||||
@@ -84,9 +93,14 @@ component AppRowView inherits Rectangle {
|
|||||||
|
|
||||||
hover := TouchArea { }
|
hover := TouchArea { }
|
||||||
|
|
||||||
HorizontalLayout {
|
VerticalLayout {
|
||||||
padding-left: 12px;
|
padding-left: 12px;
|
||||||
padding-right: 10px;
|
padding-right: 10px;
|
||||||
|
padding-top: 12px;
|
||||||
|
padding-bottom: 12px;
|
||||||
|
spacing: 8px;
|
||||||
|
|
||||||
|
HorizontalLayout {
|
||||||
spacing: 12px;
|
spacing: 12px;
|
||||||
alignment: stretch;
|
alignment: stretch;
|
||||||
|
|
||||||
@@ -111,19 +125,6 @@ component AppRowView inherits Rectangle {
|
|||||||
color: root.app.muted ? Theme.danger : Theme.text-faint;
|
color: root.app.muted ? Theme.danger : Theme.text-faint;
|
||||||
overflow: elide;
|
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 {
|
VerticalLayout {
|
||||||
alignment: center;
|
alignment: center;
|
||||||
@@ -146,6 +147,113 @@ component AppRowView inherits Rectangle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 <float> volume; // 0..1, < 0 when the device has no volume control
|
||||||
|
in property <bool> muted;
|
||||||
|
in property <bool> show-volume;
|
||||||
|
in property <bool> show-device;
|
||||||
|
in property <[string]> devices;
|
||||||
|
in property <int> device-index;
|
||||||
|
callback toggle-mute();
|
||||||
|
callback volume-moved(float);
|
||||||
|
callback device-picked(int);
|
||||||
|
|
||||||
|
property <bool> 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;
|
||||||
|
MuteButton {
|
||||||
|
muted: root.muted;
|
||||||
|
label: "system volume";
|
||||||
|
clicked => { root.toggle-mute(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
VerticalLayout {
|
||||||
|
alignment: center;
|
||||||
|
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); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
component MuteAllCard inherits Rectangle {
|
component MuteAllCard inherits Rectangle {
|
||||||
@@ -248,8 +356,8 @@ component MuteAllCard inherits Rectangle {
|
|||||||
export component MainWindow inherits Window {
|
export component MainWindow inherits Window {
|
||||||
title: "HushKey";
|
title: "HushKey";
|
||||||
icon: root.app-icon;
|
icon: root.app-icon;
|
||||||
preferred-width: 460px;
|
preferred-width: 480px;
|
||||||
preferred-height: 660px;
|
preferred-height: 720px;
|
||||||
min-width: 400px;
|
min-width: 400px;
|
||||||
min-height: 480px;
|
min-height: 480px;
|
||||||
background: Theme.bg;
|
background: Theme.bg;
|
||||||
@@ -268,6 +376,14 @@ export component MainWindow inherits Window {
|
|||||||
in property <string> backend;
|
in property <string> backend;
|
||||||
in property <string> platform-note;
|
in property <string> platform-note;
|
||||||
in property <bool> show-volume: true;
|
in property <bool> show-volume: true;
|
||||||
|
in property <bool> show-app-device;
|
||||||
|
in property <bool> show-master-volume;
|
||||||
|
in property <bool> show-output-devices;
|
||||||
|
in property <[string]> output-devices; // names, for the system picker
|
||||||
|
in property <[string]> app-device-options; // "System default" + names
|
||||||
|
in property <int> default-device-index;
|
||||||
|
in property <float> master-volume: -1;
|
||||||
|
in property <bool> master-muted;
|
||||||
in property <string> config-path;
|
in property <string> config-path;
|
||||||
in property <string> version;
|
in property <string> version;
|
||||||
in property <string> hotkey-hint;
|
in property <string> hotkey-hint;
|
||||||
@@ -289,6 +405,12 @@ export component MainWindow inherits Window {
|
|||||||
callback open-config-dir();
|
callback open-config-dir();
|
||||||
callback refresh();
|
callback refresh();
|
||||||
callback dismiss-status();
|
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 => {
|
init => {
|
||||||
Theme.dark = root.dark;
|
Theme.dark = root.dark;
|
||||||
@@ -370,6 +492,18 @@ export component MainWindow inherits Window {
|
|||||||
clear(t) => { root.clear-shortcut(t); }
|
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 {
|
if root.platform-note != "": Rectangle {
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
background: Theme.accent-soft;
|
background: Theme.accent-soft;
|
||||||
@@ -427,7 +561,11 @@ export component MainWindow inherits Window {
|
|||||||
app: row;
|
app: row;
|
||||||
capturing: root.capturing == row.key;
|
capturing: root.capturing == row.key;
|
||||||
show-volume: root.show-volume;
|
show-volume: root.show-volume;
|
||||||
|
show-device: root.show-app-device;
|
||||||
|
device-options: root.app-device-options;
|
||||||
toggle => { root.toggle-app(row.key); }
|
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); }
|
capture => { root.begin-capture(row.key); }
|
||||||
clear => { root.clear-shortcut(row.key); }
|
clear => { root.clear-shortcut(row.key); }
|
||||||
}
|
}
|
||||||
@@ -498,11 +636,22 @@ export component MainWindow inherits Window {
|
|||||||
VerticalLayout {
|
VerticalLayout {
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
spacing: 6px;
|
spacing: 6px;
|
||||||
|
HorizontalLayout {
|
||||||
|
spacing: 6px;
|
||||||
|
alignment: start;
|
||||||
Text {
|
Text {
|
||||||
text: "HushKey " + root.version;
|
text: "HushKey " + root.version;
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: Theme.text;
|
color: Theme.text;
|
||||||
|
vertical-alignment: center;
|
||||||
|
}
|
||||||
|
Text {
|
||||||
|
text: "by X4Lo";
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: Theme.text-muted;
|
||||||
|
vertical-alignment: center;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Text {
|
Text {
|
||||||
text: "Audio backend: " + root.backend;
|
text: "Audio backend: " + root.backend;
|
||||||
@@ -519,6 +668,26 @@ export component MainWindow inherits Window {
|
|||||||
HorizontalLayout {
|
HorizontalLayout {
|
||||||
alignment: start;
|
alignment: start;
|
||||||
padding-top: 4px;
|
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 {
|
Rectangle {
|
||||||
height: 30px;
|
height: 30px;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
@@ -540,7 +709,7 @@ export component MainWindow inherits Window {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Text {
|
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;
|
font-size: 11px;
|
||||||
color: Theme.text-faint;
|
color: Theme.text-faint;
|
||||||
wrap: word-wrap;
|
wrap: word-wrap;
|
||||||
|
|||||||
@@ -258,3 +258,194 @@ export component SectionLabel inherits Text {
|
|||||||
letter-spacing: 0.8px;
|
letter-spacing: 0.8px;
|
||||||
color: Theme.text-faint;
|
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 <float> value; // 0..1
|
||||||
|
in property <bool> enabled: true;
|
||||||
|
in property <bool> dimmed; // muted: grey fill
|
||||||
|
in property <string> label;
|
||||||
|
callback moved(float); // 0..1, fires continuously while dragging
|
||||||
|
|
||||||
|
property <float> drag-value;
|
||||||
|
property <float> shown: touch.pressed ? drag-value : clamp(value, 0, 1);
|
||||||
|
property <length> 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 <int> selected; // index into options, -1 = none
|
||||||
|
in property <string> label; // accessibility label
|
||||||
|
in property <bool> enabled: true;
|
||||||
|
in property <length> popup-width: 260px;
|
||||||
|
callback picked(int);
|
||||||
|
|
||||||
|
property <string> 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); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user