From 68912f6d646ad5ff0a5e8c6af36c66edf0d840cb Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sat, 28 Nov 2026 20:01:58 -0800 Subject: [PATCH] Audio: hardware volume keys, chandra-ctl volume, and an OSD pill - Map VolumeUp, VolumeDown, and Mute keys to wpctl (PipeWire) or pactl, run asynchronously so the compositor never blocks - Hold a volume key to repeat it; volume keys also work while the screen is off, without waking it - Keep volume keys as the shutter when chandra-camera has focus; Mute still toggles system audio - Add `chandra-ctl volume [up|down|mute|unmute|toggle|PCT|status]` and a transient Volume OSD - Add volume-up, volume-down, and volume-mute entries to the shortcut table --- compositor/app/app.mbt | 2 + compositor/app/pkg.generated.mbti | 3 + compositor/host/compositor.mbt | 38 ++ compositor/host/control.mbt | 30 ++ compositor/host/shortcuts.mbt | 21 ++ compositor/host/shortcuts_test.mbt | 3 + compositor/host/volume.mbt | 560 +++++++++++++++++++++++++++++ compositor/host/volume_test.mbt | 232 ++++++++++++ compositor/shell/shortcuts.mbt | 7 + docs/handset.md | 11 + session/chandra-ctl | 3 +- 11 files changed, 909 insertions(+), 1 deletion(-) create mode 100644 compositor/host/volume.mbt create mode 100644 compositor/host/volume_test.mbt diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index b4c3a30..b5ae6f2 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -383,6 +383,7 @@ pub fn run(args : Array[String]) -> Int { fds.push(pfd) } fds.append(comp.auth_fds()) // polkit asking for a password, and its helper + fds.append(comp.volume_fds()) // active audio volume commands fds.append(comp.shell.launch_fds()) // launched apps' monitors reporting an exit ignore(@sys.wait_readable(fds, comp.wake_timeout(idle.timeout()))) } else { @@ -404,6 +405,7 @@ pub fn run(args : Array[String]) -> Int { let wait_fds = comp.server.wait_fds() wait_fds.append(comp.control_fds()) // chandra-ctl wait_fds.append(comp.auth_fds()) // polkit asking for a password, and its helper + wait_fds.append(comp.volume_fds()) // active audio volume commands wait_fds.append(comp.shell.launch_fds()) // launched apps' monitors reporting an exit match nested { Some(n) => { diff --git a/compositor/app/pkg.generated.mbti b/compositor/app/pkg.generated.mbti index 6d39a93..37af04d 100644 --- a/compositor/app/pkg.generated.mbti +++ b/compositor/app/pkg.generated.mbti @@ -7,6 +7,9 @@ pub fn run(Array[String]) -> Int32 // Errors // Types and methods +type IdleClock + +type Pacer // Type aliases diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 9b10b2f..a610623 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -331,6 +331,16 @@ pub(all) struct ChandraCompositor { /// Output rotation (`0=0`, `1=90 CW`, `2=180 flip`, `3=270 CW`) and pending backend switch. mut rotation : Int mut pending_rotation : Int? + /// Audio volume control and OSD (volume.mbt). + mut vol_run : VolRun? + vol_queue : Array[(VolCmd, Bool)] + mut vol_osd : VolOsd? + mut vol_pct : Int + mut vol_muted : Bool + mut vol_repeat_key : UInt + mut vol_repeat_action : @shell.ShortcutAction? + mut vol_repeat_next_ms : UInt64 + mut vol_runner : ((VolCmd) -> (Int, Bool)?)? } ///| @@ -485,6 +495,15 @@ pub fn ChandraCompositor::new( osk_pointer_grab: false, rotation: initial_rotation_from_env(), pending_rotation: None, + vol_run: None, + vol_queue: [], + vol_osd: None, + vol_pct: 0, + vol_muted: false, + vol_repeat_key: 0U, + vol_repeat_action: None, + vol_repeat_next_ms: 0UL, + vol_runner: None, } // Client popups (menus) are placed to stay on screen: the server asks for the output's // rectangle relative to the parent's content origin when it applies constraint adjustment. @@ -634,6 +653,7 @@ pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit { release_snapshot(win.surface) } self.stop_control() + self.volume_shutdown() self.auth_shutdown() self.shell.shutdown() match self.settings_portal { @@ -751,6 +771,7 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit { self.auth_tick() self.face_window_tick() self.control_tick() + self.volume_tick() self.shell.launch_tick() let events = self.server.poll_events() for ev in events { @@ -1067,6 +1088,8 @@ pub fn ChandraCompositor::wake_timeout(self : ChandraCompositor, idle_ms : Int) let d = if g >= 0 && (d < 0 || g < d) { g } else { d } let l = self.shell.launch_wake_ms(now) let d = if l >= 0 && (d < 0 || l < d) { l } else { d } + let v = self.volume_wake_ms(now) + let d = if v >= 0 && (d < 0 || v < d) { v } else { d } if d >= 0 && d < idle_ms { d } else { @@ -1282,6 +1305,7 @@ fn ChandraCompositor::build_scene( panel_ops.append(self.auth_ops()) panel_ops.append(self.auth_notice_ops()) panel_ops.append(self.osk_ops()) + panel_ops.append(self.volume_ops()) self.frames_built = self.frames_built + 1 self.run_shell_actions() // The wallpaper (the first ops) is cached by the renderer; the desktop card after it changes. @@ -2211,12 +2235,22 @@ fn ChandraCompositor::handle_input_inner( self.note_activity(@sys.monotonic_ms()) } else { self.manual_screen_off = true + self.stop_volume_repeat() } } return } _ => () } + if self.manual_screen_off || self.screen_off { + match ev { + Key(code, pressed) => + if self.handle_screen_off_volume_key(code, pressed) { + return + } + _ => () + } + } if self.manual_screen_off { return } @@ -2235,6 +2269,10 @@ fn ChandraCompositor::dispatch_input_inner( time_ms : UInt, ) -> Unit { match ev { + Key(code, false) => + if code == self.vol_repeat_key { + self.stop_volume_repeat() + } Modifiers(dep, lat, lock, group) => { self.mods_latched = lat self.mods_locked = lock diff --git a/compositor/host/control.mbt b/compositor/host/control.mbt index ef78d21..3a1c3cc 100644 --- a/compositor/host/control.mbt +++ b/compositor/host/control.mbt @@ -302,6 +302,7 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin "rotate [cw|ccw|flip|0|90|180|270|status] rotate or flip the display", "screen [on|off|toggle|status] blank or wake the display", "brightness [PCT|status] read or set display backlight percent (5..100)", + "volume [up|down|mute|unmute|toggle|PCT|status] read or adjust audio volume", "osk [on|off|toggle|status] enable, disable, or query the on-screen keyboard", "refresh schedule a full frame redraw", "status report geometry, rotation, screen power, brightness, pointer, OSK", @@ -548,6 +549,35 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin } } } + "volume" => { + let arg = if words.length() >= 2 { words[1] } else { "status" } + if words.length() > 2 { + return (["error usage: volume [up|down|mute|unmute|toggle|PCT|status]"], false) + } + let (cmd, show_osd) : (VolCmd, Bool) = match arg { + "status" => (VolCmd::Query, false) + "up" => (VolCmd::Up, !(self.screen_off || self.manual_screen_off)) + "down" => (VolCmd::Down, !(self.screen_off || self.manual_screen_off)) + "mute" => (VolCmd::SetMute(true), !(self.screen_off || self.manual_screen_off)) + "unmute" => (VolCmd::SetMute(false), !(self.screen_off || self.manual_screen_off)) + "toggle" => (VolCmd::MuteToggle, !(self.screen_off || self.manual_screen_off)) + _ => + match parse_int_opt(arg) { + Some(v) if v >= 0 => + (VolCmd::SetPercent(v), !(self.screen_off || self.manual_screen_off)) + _ => + return ( + ["error usage: volume [up|down|mute|unmute|toggle|PCT|status]"], + false, + ) + } + } + match self.run_volume_control(cmd, show_osd) { + Ok((pct, muted)) => + (["ok " + pct.to_string() + (if muted { " muted" } else { "" })], true) + Err(msg) => (["error " + msg], false) + } + } "settings" => { let arg = if words.length() >= 2 { words[1] } else { "session" } if words.length() > 2 { diff --git a/compositor/host/shortcuts.mbt b/compositor/host/shortcuts.mbt index ad195cd..f9d451a 100644 --- a/compositor/host/shortcuts.mbt +++ b/compositor/host/shortcuts.mbt @@ -75,6 +75,9 @@ fn ChandraCompositor::capture_key(self : ChandraCompositor, code : UInt, pressed /// modifiers. True when the key was used (neither it nor its release reaches a client). fn ChandraCompositor::shortcut_key(self : ChandraCompositor, code : UInt, pressed : Bool) -> Bool { if !pressed { + if code == self.vol_repeat_key { + self.stop_volume_repeat() + } if self.sc_swallow.contains(code) { self.sc_swallow.retain(c => c != code) return true @@ -99,6 +102,21 @@ fn ChandraCompositor::shortcut_key(self : ChandraCompositor, code : UInt, presse Some(_) => false None => false } + Some(VolumeUp | VolumeDown as act) => + if self.camera_takes_volume_keys() { + false + } else { + self.sc_swallow.push(code) + self.super_solo = false + self.trigger_volume_shortcut(act, code, true) + true + } + Some(VolumeMute) => { + self.sc_swallow.push(code) + self.super_solo = false + self.trigger_volume_shortcut(VolumeMute, code, true) + true + } Some(action) => { self.sc_swallow.push(code) self.run_shortcut(action) @@ -136,6 +154,9 @@ pub fn ChandraCompositor::run_shortcut(self : ChandraCompositor, action : @shell RecordWindow => self.toggle_recording(ShotMode::WindowUnderCursor) DockApps => ignore(self.open_dock_app(1)) EmojiPicker => self.toggle_emoji_picker() + VolumeUp => self.enqueue_volume(VolCmd::Up, !(self.screen_off || self.manual_screen_off)) + VolumeDown => self.enqueue_volume(VolCmd::Down, !(self.screen_off || self.manual_screen_off)) + VolumeMute => self.enqueue_volume(VolCmd::MuteToggle, !(self.screen_off || self.manual_screen_off)) } } diff --git a/compositor/host/shortcuts_test.mbt b/compositor/host/shortcuts_test.mbt index 4f4ad3e..320dc0d 100644 --- a/compositor/host/shortcuts_test.mbt +++ b/compositor/host/shortcuts_test.mbt @@ -37,6 +37,9 @@ test "the default shortcuts are the compositor's long-standing combos" { ("dock-apps", "Super+1"), ("overview", "Super+W"), ("emoji-picker", "Super+Period"), + ("volume-up", "VolumeUp"), + ("volume-down", "VolumeDown"), + ("volume-mute", "Mute"), ] let sc = @shell.Shortcuts::defaults() assert_eq(@shell.shortcut_table.length(), want.length()) diff --git a/compositor/host/volume.mbt b/compositor/host/volume.mbt new file mode 100644 index 0000000..b20f436 --- /dev/null +++ b/compositor/host/volume.mbt @@ -0,0 +1,560 @@ +///| Hardware audio volume control and OSD for Chandra. +/// +/// Maps `KEY_VOLUMEUP` (115), `KEY_VOLUMEDOWN` (114), and `KEY_MUTE` (113) via +/// `compositor/shell/shortcuts.mbt` to async PipeWire (`wpctl`) or PulseAudio (`pactl`) +/// invocations over `@sys.spawn_socket`, with hold-to-repeat, screen-off operation, +/// `chandra-camera` shutter pass-through, and an on-screen volume pill. + +///| Volume command sent to the host audio mixer (`wpctl` or `pactl`). +pub(all) enum VolCmd { + Up + Down + MuteToggle + SetMute(Bool) + SetPercent(Int) + Query +} derive(Eq, Debug) + +///| Active asynchronous mixer subprocess reading stdout on `fd`. +pub(all) struct VolRun { + fd : Int + buf : Array[Byte] + show_osd : Bool +} + +///| Transient volume OSD state shown near the top center of the screen. +pub(all) struct VolOsd { + pct : Int + muted : Bool + until : UInt64 +} + +///| Step size per volume press/repeat in percent. +let vol_step_pct : Int = 5 + +///| How long the volume OSD stays on screen. +let vol_osd_ms : UInt64 = 1800UL + +///| Initial hold delay and subsequent repeat interval while holding a volume key. +let vol_repeat_delay_ms : UInt64 = 400UL + +///| +let vol_repeat_interval_ms : UInt64 = 90UL + +///| Clamp a volume percentage into `[lo, hi]`. +fn clamp_vol_pct(v : Int, lo : Int, hi : Int) -> Int { + if v < lo { + lo + } else if v > hi { + hi + } else { + v + } +} + +///| Check whether a UTF-16 code unit is an ASCII digit. +fn is_ascii_digit(c : UInt16) -> Bool { + c >= '0' && c <= '9' +} + +///| Numeric value of an ASCII digit UTF-16 code unit. +fn ascii_digit(c : UInt16) -> Int { + c.to_int() - '0'.to_int() +} + +///| Parse `wpctl get-volume` output like `"Volume: 0.65"`, `"Volume: 0.00 [MUTED]"`, `"Volume: 1.25"`, `"Volume: 0.506"`. +fn parse_wpctl_volume(text : String) -> (Int, Bool)? { + let idx = match text.find("Volume:") { + Some(i) => i + None => return None + } + let mut i = idx + 7 + let n = text.length() + while i < n && (text[i] == ' ' || text[i] == '\t') { + i = i + 1 + } + let mut int_part = 0 + let mut saw_digit = false + while i < n && is_ascii_digit(text[i]) { + saw_digit = true + int_part = int_part * 10 + ascii_digit(text[i]) + if int_part > 1000 { + int_part = 1000 + } + i = i + 1 + } + let mut frac_pct = 0 + let mut round_up = false + if i < n && text[i] == '.' { + i = i + 1 + let mut frac_pos = 0 + while i < n && is_ascii_digit(text[i]) { + saw_digit = true + let d = ascii_digit(text[i]) + if frac_pos == 0 { + frac_pct = frac_pct + d * 10 + } else if frac_pos == 1 { + frac_pct = frac_pct + d + } else if frac_pos == 2 && d >= 5 { + round_up = true + } + frac_pos = frac_pos + 1 + i = i + 1 + } + } + if !saw_digit { + return None + } + let raw_pct = int_part * 100 + frac_pct + (if round_up { 1 } else { 0 }) + let muted = text.contains("[MUTED]") + Some((clamp_vol_pct(raw_pct, 0, 150), muted)) +} + +///| Parse `pactl get-sink-volume` + `pactl get-sink-mute` output. +fn parse_pactl_volume(text : String) -> (Int, Bool)? { + let pct_idx = match text.find("%") { + Some(i) => i + None => return None + } + let mut start = pct_idx + while start > 0 && is_ascii_digit(text[start - 1]) { + start = start - 1 + } + if start == pct_idx { + return None + } + let mut pct = 0 + for i = start; i < pct_idx; i = i + 1 { + pct = pct * 10 + ascii_digit(text[i]) + if pct > 1000 { + pct = 1000 + } + } + let muted = text.to_lower().contains("mute: yes") + Some((clamp_vol_pct(pct, 0, 150), muted)) +} + +///| Parse `wpctl get-volume` or `pactl get-sink-volume`/`get-sink-mute` stdout into `(pct, muted)`. +pub fn parse_volume_output(text : String) -> (Int, Bool)? { + match parse_wpctl_volume(text) { + Some(v) => Some(v) + None => parse_pactl_volume(text) + } +} + +///| Build a single-line shell command (no embedded newlines, since `mp_spawn_socket` splits on `\n`). +fn vol_shell_cmd(cmd : VolCmd) -> String? { + let step = vol_step_pct.to_string() + if @sys.has_exe("wpctl") { + let s = match cmd { + Up => + "wpctl set-mute @DEFAULT_AUDIO_SINK@ 0 && wpctl set-volume -l 1.0 @DEFAULT_AUDIO_SINK@ " + + step + + "%+ && wpctl get-volume @DEFAULT_AUDIO_SINK@" + Down => + "wpctl set-volume @DEFAULT_AUDIO_SINK@ " + + step + + "%- && wpctl get-volume @DEFAULT_AUDIO_SINK@" + MuteToggle => + "wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle && wpctl get-volume @DEFAULT_AUDIO_SINK@" + SetMute(m) => + "wpctl set-mute @DEFAULT_AUDIO_SINK@ " + + (if m { "1" } else { "0" }) + + " && wpctl get-volume @DEFAULT_AUDIO_SINK@" + SetPercent(p) => + "wpctl set-volume @DEFAULT_AUDIO_SINK@ " + + clamp_vol_pct(p, 0, 150).to_string() + + "% && wpctl get-volume @DEFAULT_AUDIO_SINK@" + Query => "wpctl get-volume @DEFAULT_AUDIO_SINK@" + } + return Some(s) + } + if @sys.has_exe("pactl") { + let s = match cmd { + Up => + "pactl set-sink-mute @DEFAULT_SINK@ 0 && pactl set-sink-volume @DEFAULT_SINK@ +" + + step + + "% && v=$(pactl get-sink-volume @DEFAULT_SINK@ | awk -F/ 'NR==1{gsub(/[^0-9]/,\"\",$2); print $2}'); [ -n \"$v\" ] && [ \"$v\" -gt 100 ] && pactl set-sink-volume @DEFAULT_SINK@ 100%; pactl get-sink-volume @DEFAULT_SINK@; pactl get-sink-mute @DEFAULT_SINK@" + Down => + "pactl set-sink-volume @DEFAULT_SINK@ -" + + step + + "% && pactl get-sink-volume @DEFAULT_SINK@; pactl get-sink-mute @DEFAULT_SINK@" + MuteToggle => + "pactl set-sink-mute @DEFAULT_SINK@ toggle && pactl get-sink-volume @DEFAULT_SINK@; pactl get-sink-mute @DEFAULT_SINK@" + SetMute(m) => + "pactl set-sink-mute @DEFAULT_SINK@ " + + (if m { "1" } else { "0" }) + + " && pactl get-sink-volume @DEFAULT_SINK@; pactl get-sink-mute @DEFAULT_SINK@" + SetPercent(p) => + "pactl set-sink-volume @DEFAULT_SINK@ " + + clamp_vol_pct(p, 0, 150).to_string() + + "% && pactl get-sink-volume @DEFAULT_SINK@; pactl get-sink-mute @DEFAULT_SINK@" + Query => "pactl get-sink-volume @DEFAULT_SINK@; pactl get-sink-mute @DEFAULT_SINK@" + } + return Some(s) + } + None +} + +///| Update cached volume state and optionally display the Volume OSD. +fn ChandraCompositor::apply_volume_result( + self : ChandraCompositor, + pct : Int, + muted : Bool, + show_osd : Bool, +) -> Unit { + self.vol_pct = clamp_vol_pct(pct, 0, 150) + self.vol_muted = muted + if show_osd && !self.screen_off && !self.manual_screen_off { + self.vol_osd = Some({ pct: self.vol_pct, muted, until: @sys.monotonic_ms() + vol_osd_ms }) + self.damage.mark_full() + self.frame_changed = true + } +} + +///| Spawn `cmd` asynchronously on a socket pair so the compositor never blocks. +fn ChandraCompositor::start_volume_cmd( + self : ChandraCompositor, + cmd : VolCmd, + show_osd : Bool, +) -> Unit { + let script = match vol_shell_cmd(cmd) { + Some(s) => s + None => return + } + let fd = @sys.spawn_socket(["/bin/sh", "-c", script]) + if fd >= 0 { + self.vol_run = Some({ fd, buf: [], show_osd }) + } +} + +///| Run a volume command via the test hook (synchronously) or async subprocess queue. +fn ChandraCompositor::enqueue_volume( + self : ChandraCompositor, + cmd : VolCmd, + show_osd : Bool, +) -> Unit { + match self.vol_runner { + Some(runner) => { + match runner(cmd) { + Some((pct, muted)) => self.apply_volume_result(pct, muted, show_osd) + None => () + } + return + } + None => () + } + match self.vol_run { + None => self.start_volume_cmd(cmd, show_osd) + Some(_) => + if self.vol_queue.length() < 16 { + self.vol_queue.push((cmd, show_osd)) + } + } +} + +///| Run a volume command synchronously (for `chandra-ctl volume ...`), returning `Ok((pct, muted))`. +pub fn ChandraCompositor::run_volume_control( + self : ChandraCompositor, + cmd : VolCmd, + show_osd : Bool, +) -> Result[(Int, Bool), String] { + match self.vol_runner { + Some(runner) => + match runner(cmd) { + Some((pct, muted)) => { + self.apply_volume_result(pct, muted, show_osd) + return Ok((self.vol_pct, self.vol_muted)) + } + None => return Err("audio mixer failed") + } + None => () + } + let script = match vol_shell_cmd(cmd) { + Some(s) => s + None => return Err("no audio mixer (wpctl or pactl)") + } + let fd = @sys.spawn_socket(["/bin/sh", "-c", script]) + if fd < 0 { + return Err("could not start audio mixer") + } + let raw : Array[Byte] = [] + let chunk : FixedArray[Byte] = FixedArray::make(2048, b'\x00') + let deadline = @sys.monotonic_ms() + 1000UL + let mut eof = false + while !eof && @sys.monotonic_ms() < deadline { + let rem = (deadline - @sys.monotonic_ms()).to_int() + let wait = if rem > 50 { 50 } else if rem < 1 { 1 } else { rem } + if @sys.poll_read(fd, wait) > 0 { + while @sys.poll_read(fd, 0) > 0 { + let (n, extra) = @sys.recvmsg_fd(fd, chunk, chunk.length()) + if extra >= 0 { + @sys.close_fd(extra) + } + if n == -1 { + break + } + if n <= 0 { + eof = true + break + } + for i = 0; i < n; i = i + 1 { + raw.push(chunk[i]) + } + if raw.length() > 65536 { + eof = true + break + } + } + } + } + @sys.close_fd(fd) + let text = @utf8.decode_lossy(Bytes::from_array(raw)) + match parse_volume_output(text) { + Some((pct, muted)) => { + self.apply_volume_result(pct, muted, show_osd) + Ok((self.vol_pct, self.vol_muted)) + } + None => Err("audio mixer failed") + } +} + +///| Poll active volume command, drain queued commands, drive hold-to-repeat, and expire the OSD. +pub fn ChandraCompositor::volume_tick(self : ChandraCompositor) -> Unit { + match self.vol_run { + Some(r) => { + let chunk : FixedArray[Byte] = FixedArray::make(2048, b'\x00') + let mut eof = false + while @sys.poll_read(r.fd, 0) > 0 { + let (n, extra) = @sys.recvmsg_fd(r.fd, chunk, chunk.length()) + if extra >= 0 { + @sys.close_fd(extra) + } + if n == -1 { + break + } + if n <= 0 { + eof = true + break + } + for i = 0; i < n; i = i + 1 { + r.buf.push(chunk[i]) + } + if r.buf.length() > 65536 { + eof = true + break + } + } + if eof { + @sys.close_fd(r.fd) + self.vol_run = None + let text = @utf8.decode_lossy(Bytes::from_array(r.buf)) + match parse_volume_output(text) { + Some((pct, muted)) => self.apply_volume_result(pct, muted, r.show_osd) + None => { + let msg = text.trim(chars=" \r\n\t").to_string() + if msg.length() > 0 { + @sys.log("volume: mixer output error: " + msg) + } + } + } + } + } + None => () + } + if self.vol_run is None && self.vol_queue.length() > 0 { + let (next_cmd, show_osd) = self.vol_queue.remove(0) + self.start_volume_cmd(next_cmd, show_osd) + } + let now = @sys.monotonic_ms() + if self.vol_repeat_key != 0U && now >= self.vol_repeat_next_ms { + self.vol_repeat_next_ms = now + vol_repeat_interval_ms + if self.vol_queue.length() < 4 { + let show_osd = !(self.screen_off || self.manual_screen_off) + match self.vol_repeat_action { + Some(VolumeUp) => self.enqueue_volume(VolCmd::Up, show_osd) + Some(VolumeDown) => self.enqueue_volume(VolCmd::Down, show_osd) + _ => self.stop_volume_repeat() + } + } + } + match self.vol_osd { + Some(o) => + if now >= o.until { + self.vol_osd = None + self.damage.mark_full() + self.frame_changed = true + } + None => () + } +} + +///| File descriptors the idle main loop must wake on for active volume commands. +pub fn ChandraCompositor::volume_fds(self : ChandraCompositor) -> Array[Int] { + match self.vol_run { + Some(r) => [r.fd] + None => [] + } +} + +///| Shortest remaining wait in ms for volume repeat or OSD expiry, or -1 if idle. +pub fn ChandraCompositor::volume_wake_ms(self : ChandraCompositor, now : UInt64) -> Int { + let mut best = -1 + let consider = fn(target : UInt64) { + let rem = if target > now { (target - now).to_int() } else { 0 } + if best < 0 || rem < best { + best = rem + } + } + if self.vol_repeat_key != 0U { + consider(self.vol_repeat_next_ms) + } + match self.vol_osd { + Some(o) => consider(o.until) + None => () + } + best +} + +///| Whether the volume OSD is currently visible. +pub fn ChandraCompositor::volume_osd_shown(self : ChandraCompositor) -> Bool { + self.vol_osd is Some(_) +} + +///| Cached `(percent, muted)` volume state. +pub fn ChandraCompositor::volume_state(self : ChandraCompositor) -> (Int, Bool) { + (self.vol_pct, self.vol_muted) +} + +///| Clean up any active mixer subprocess and timers on shutdown. +pub fn ChandraCompositor::volume_shutdown(self : ChandraCompositor) -> Unit { + match self.vol_run { + Some(r) => @sys.close_fd(r.fd) + None => () + } + self.vol_run = None + self.vol_queue.clear() + self.stop_volume_repeat() +} + +///| True when `chandra-camera` holds foreground focus so hardware volume buttons act as the shutter. +fn ChandraCompositor::camera_takes_volume_keys(self : ChandraCompositor) -> Bool { + if self.screen_off || + self.manual_screen_off || + self.auth is Some(_) || + self.emoji_ui is Some(_) || + self.shot is Some(_) || + self.shot_edit is Some(_) || + self.shell.popup_open() || + self.overview is Some(_) || + self.switcher_on || + self.shell.shortcut_capturing() >= 0 || + self.held_mods() != 0U { + return false + } + match self.kbd_win { + Some(wid) => + match self.windows.get(wid) { + Some(win) => win.app_id == "chandra-camera" + None => false + } + None => false + } +} + +///| Stop repeating a held volume button. +pub fn ChandraCompositor::stop_volume_repeat(self : ChandraCompositor) -> Unit { + self.vol_repeat_key = 0U + self.vol_repeat_action = None + self.vol_repeat_next_ms = 0UL +} + +///| Execute a volume shortcut action and arm hold-to-repeat for VolumeUp / VolumeDown. +fn ChandraCompositor::trigger_volume_shortcut( + self : ChandraCompositor, + action : @shell.ShortcutAction, + code : UInt, + show_osd : Bool, +) -> Unit { + match action { + VolumeUp => { + self.enqueue_volume(VolCmd::Up, show_osd) + self.vol_repeat_key = code + self.vol_repeat_action = Some(VolumeUp) + self.vol_repeat_next_ms = @sys.monotonic_ms() + vol_repeat_delay_ms + } + VolumeDown => { + self.enqueue_volume(VolCmd::Down, show_osd) + self.vol_repeat_key = code + self.vol_repeat_action = Some(VolumeDown) + self.vol_repeat_next_ms = @sys.monotonic_ms() + vol_repeat_delay_ms + } + VolumeMute => { + self.stop_volume_repeat() + self.enqueue_volume(VolCmd::MuteToggle, show_osd) + } + _ => () + } +} + +///| Handle hardware volume buttons while the display is blanked without waking the screen. +fn ChandraCompositor::handle_screen_off_volume_key( + self : ChandraCompositor, + code : UInt, + pressed : Bool, +) -> Bool { + if !pressed { + if code == self.vol_repeat_key { + self.stop_volume_repeat() + return true + } + return false + } + match self.shell.shortcuts.lookup({ mods: 0U, key: code }) { + Some(VolumeUp | VolumeDown | VolumeMute as act) => { + self.trigger_volume_shortcut(act, code, false) + true + } + _ => false + } +} + +///| Draw ops for the floating Volume OSD pill near top-center. +fn ChandraCompositor::volume_ops(self : ChandraCompositor) -> Array[@scene.DrawOp] { + if self.screen_off || self.manual_screen_off { + return [] + } + let o = match self.vol_osd { + Some(v) => v + None => return [] + } + let p = self.theme.palette + let fs = self.theme.font_size + let w = (self.output_w - 32).min(240).max(140) + let h = 56 + let x = (self.output_w - w) / 2 + let y = 28 + let r = 14 + let card = @scene.Rect::new(x, y, w, h) + let ops : Array[@scene.DrawOp] = [ + @scene.DrawOp::FillRect(card, p.surface_popup, r), + @scene.DrawOp::StrokeRect(card, p.border, 1, r), + ] + let title = if o.muted { "Muted" } else { "Volume" } + let val_text = if o.muted && o.pct == 0 { "Muted" } else { o.pct.to_string() + "%" } + let text_col = if o.muted { p.foreground_muted } else { p.foreground } + ops.push(@scene.DrawOp::Text(x + 14, y + 18, title, fs, text_col, @scene.TextAlign::Left, true)) + ops.push(@scene.DrawOp::Text(x + w - 14, y + 18, val_text, fs, text_col, @scene.TextAlign::Right, true)) + let bar_x = x + 14 + let bar_y = y + 36 + let bar_w = w - 28 + let bar_h = 8 + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(bar_x, bar_y, bar_w, bar_h), p.surface_hover, 4)) + let clamped = clamp_vol_pct(o.pct, 0, 100) + let fill_w = bar_w * clamped / 100 + if fill_w > 0 { + let fill_col = if o.muted { p.foreground_muted } else { p.accent } + ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(bar_x, bar_y, fill_w, bar_h), fill_col, 4)) + } + ops +} diff --git a/compositor/host/volume_test.mbt b/compositor/host/volume_test.mbt new file mode 100644 index 0000000..1045b8a --- /dev/null +++ b/compositor/host/volume_test.mbt @@ -0,0 +1,232 @@ +///| Hardware volume keys, async/sync mixer control, Volume OSD, screen-off routing, +/// and chandra-camera shutter pass-through. + +///| Install an in-memory mock mixer on `comp` and return the recorded commands. +fn attach_mock_mixer( + comp : @host.ChandraCompositor, + init_pct? : Int = 50, + init_muted? : Bool = false, +) -> Array[@host.VolCmd] { + let cmds : Array[@host.VolCmd] = [] + let pct : Ref[Int] = { val: init_pct } + let muted : Ref[Bool] = { val: init_muted } + comp.vol_runner = Some(fn(cmd : @host.VolCmd) { + cmds.push(cmd) + match cmd { + Up => { + muted.val = false + let next = pct.val + 5 + pct.val = if next > 100 { 100 } else { next } + } + Down => { + let next = pct.val - 5 + pct.val = if next < 0 { 0 } else { next } + } + MuteToggle => muted.val = !muted.val + SetMute(m) => muted.val = m + SetPercent(p) => pct.val = if p < 0 { 0 } else if p > 150 { 150 } else { p } + Query => () + } + Some((pct.val, muted.val)) + }) + cmds +} + +///| +test "parse_volume_output handles wpctl and pactl output" { + assert_eq(@host.parse_volume_output("Volume: 0.65\n"), Some((65, false))) + assert_eq(@host.parse_volume_output("Volume: 0.00 [MUTED]\n"), Some((0, true))) + assert_eq(@host.parse_volume_output("Volume: 1.00\n"), Some((100, false))) + assert_eq(@host.parse_volume_output("Volume: 1.25\n"), Some((125, false))) + assert_eq(@host.parse_volume_output("Volume: 0.506\n"), Some((51, false))) + assert_eq(@host.parse_volume_output("Volume: 0.504\n"), Some((50, false))) + assert_eq(@host.parse_volume_output("Volume: 1.99\n"), Some((150, false))) + let pa_ok = "Volume: front-left: 32768 / 50% / -18.06 dB, front-right: 32768 / 50% / -18.06 dB\nMute: no\n" + assert_eq(@host.parse_volume_output(pa_ok), Some((50, false))) + let pa_muted = "Volume: front-left: 49152 / 75% / -7.50 dB\nMute: yes\n" + assert_eq(@host.parse_volume_output(pa_muted), Some((75, true))) + assert_eq(@host.parse_volume_output(""), None) + assert_eq(@host.parse_volume_output("error no sink"), None) + assert_eq(@host.parse_volume_output("Volume: abc"), None) +} + +///| +test "volume keys update state, show Volume OSD, and keep has_timed_work false" { + let comp = new_comp("vol-osd") + let cmds = attach_mock_mixer(comp, init_pct=50, init_muted=false) + + comp.handle_input(@nested.InputEvent::Key(115U, true), 1U) + comp.handle_input(@nested.InputEvent::Key(115U, false), 2U) + assert_eq(cmds, [@host.VolCmd::Up]) + assert_eq(comp.volume_state(), (55, false)) + assert_true(comp.volume_osd_shown()) + assert_false(comp.has_timed_work()) + let wake = comp.wake_timeout(5000) + assert_true(wake >= 0 && wake <= 1800) + + let scene = comp.compose_scene().unwrap() + assert_true(scene.panel_ops.iter().any(op => match op { + @scene.DrawOp::Text(_, _, s, _, _, _, _) => s == "Volume" || s == "55%" + _ => false + })) + + comp.handle_input(@nested.InputEvent::Key(114U, true), 3U) + comp.handle_input(@nested.InputEvent::Key(114U, false), 4U) + assert_eq(comp.volume_state(), (50, false)) + + comp.handle_input(@nested.InputEvent::Key(113U, true), 5U) + comp.handle_input(@nested.InputEvent::Key(113U, false), 6U) + assert_eq(comp.volume_state(), (50, true)) + assert_eq(cmds, [@host.VolCmd::Up, @host.VolCmd::Down, @host.VolCmd::MuteToggle]) + + let muted_scene = comp.compose_scene().unwrap() + assert_true(muted_scene.panel_ops.iter().any(op => match op { + @scene.DrawOp::Text(_, _, s, _, _, _, _) => s == "Muted" + _ => false + })) + comp.vol_osd = Some({ pct: 50, muted: true, until: 0UL }) + comp.volume_tick() + assert_false(comp.volume_osd_shown()) + assert_eq(comp.volume_wake_ms(@sys.monotonic_ms()), -1) + comp.close() +} + +///| +test "volume hold-to-repeat arms on press and clears on release" { + let comp = new_comp("vol-repeat") + let cmds = attach_mock_mixer(comp, init_pct=30, init_muted=false) + + comp.handle_input(@nested.InputEvent::Key(115U, true), 10U) + assert_eq(comp.vol_repeat_key, 115U) + assert_eq(comp.vol_repeat_action, Some(@shell.ShortcutAction::VolumeUp)) + assert_eq(cmds.length(), 1) + + // Force repeat deadline to be due and step: should enqueue a repeat Up step. + comp.vol_repeat_next_ms = @sys.monotonic_ms() + comp.volume_tick() + assert_eq(cmds, [@host.VolCmd::Up, @host.VolCmd::Up]) + assert_eq(comp.volume_state(), (40, false)) + + // Release clears hold-to-repeat immediately. + comp.handle_input(@nested.InputEvent::Key(115U, false), 20U) + assert_eq(comp.vol_repeat_key, 0U) + assert_eq(comp.vol_repeat_action, None) + comp.close() +} + +///| +test "volume keys work while screen is off without waking it or showing OSD" { + let comp = new_comp("vol-screenoff") + let cmds = attach_mock_mixer(comp, init_pct=40, init_muted=false) + + // Manual screen-off (power button / chandra-ctl screen off). + comp.set_manual_screen_off(true) + assert_true(comp.manual_screen_off) + comp.handle_input(@nested.InputEvent::Key(115U, true), 10U) + comp.handle_input(@nested.InputEvent::Key(115U, false), 11U) + comp.handle_input(@nested.InputEvent::Key(114U, true), 12U) + comp.handle_input(@nested.InputEvent::Key(114U, false), 13U) + comp.handle_input(@nested.InputEvent::Key(113U, true), 14U) + comp.handle_input(@nested.InputEvent::Key(113U, false), 15U) + assert_true(comp.manual_screen_off) + assert_false(comp.volume_osd_shown()) + assert_eq(cmds, [@host.VolCmd::Up, @host.VolCmd::Down, @host.VolCmd::MuteToggle]) + + // Idle screen-off (`screen_off = true` without `manual_screen_off`). + comp.set_manual_screen_off(false) + comp.screen_off = true + let saved_input_ms = comp.last_input_ms + comp.handle_input(@nested.InputEvent::Key(115U, true), 20U) + comp.handle_input(@nested.InputEvent::Key(115U, false), 21U) + assert_true(comp.screen_off) + assert_eq(comp.last_input_ms, saved_input_ms) + assert_false(comp.volume_osd_shown()) + assert_eq(cmds.length(), 4) + comp.close() +} + +///| +test "volume keys pass through to focused chandra-camera but are handled for other apps" { + let socket_path = "/tmp/wayland-moon-volcam-" + @sys.getpid().to_string() + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.ChandraCompositor::new(socket_path, theme, 1280, 720).unwrap() + let cmds = attach_mock_mixer(comp, init_pct=50, init_muted=false) + + let (cam, cam_shm, cam_surf, cam_xdg, _cam_tl, _cam_deco) = open_and_configure_client( + comp, socket_path, "Camera", "chandra-camera", + ) + commit_shm_frame(comp, cam, cam_shm, cam_surf, cam_xdg, 1UL) + let cam_reg = 2U + let cam_seat = bind_global(cam, cam_reg, "wl_seat", 7U) + let cam_kbd = cam.alloc_id() + let wk1 = @wayland.WireWriter::new() + wk1.u32(cam_kbd) + cam.send(wk1.finish_msg(cam_seat, 1U)) + for _i = 0; _i < 5; _i = _i + 1 { + comp.step() + @sys.sleep_ms(2) + } + ignore(drain_msgs(cam)) + + // Camera is focused: VolumeUp & VolumeDown pass through to its wl_keyboard (shutter). + comp.handle_input(@nested.InputEvent::Key(115U, true), 10U) + comp.handle_input(@nested.InputEvent::Key(115U, false), 11U) + comp.handle_input(@nested.InputEvent::Key(114U, true), 12U) + comp.handle_input(@nested.InputEvent::Key(114U, false), 13U) + assert_eq(cmds, []) + let cam_msgs = drain_msgs(cam) + assert_true(has_msg(cam_msgs, cam_kbd, 3U)) // wl_keyboard.key reached chandra-camera + + // Mute still toggles system audio even while camera is focused. + comp.handle_input(@nested.InputEvent::Key(113U, true), 14U) + comp.handle_input(@nested.InputEvent::Key(113U, false), 15U) + assert_eq(cmds, [@host.VolCmd::MuteToggle]) + + // Open another app (`foot`) which takes focus: VolumeUp/Down now control system audio. + let (foot, foot_shm, foot_surf, foot_xdg, _foot_tl, _foot_deco) = open_and_configure_client( + comp, socket_path, "foot", "foot", + ) + commit_shm_frame(comp, foot, foot_shm, foot_surf, foot_xdg, 1UL) + let foot_seat = bind_global(foot, 2U, "wl_seat", 7U) + let foot_kbd = foot.alloc_id() + let wk2 = @wayland.WireWriter::new() + wk2.u32(foot_kbd) + foot.send(wk2.finish_msg(foot_seat, 1U)) + for _i = 0; _i < 5; _i = _i + 1 { + comp.step() + @sys.sleep_ms(2) + } + ignore(drain_msgs(foot)) + + comp.handle_input(@nested.InputEvent::Key(115U, true), 20U) + comp.handle_input(@nested.InputEvent::Key(115U, false), 21U) + assert_eq(cmds, [@host.VolCmd::MuteToggle, @host.VolCmd::Up]) + assert_false(has_msg(drain_msgs(foot), foot_kbd, 3U)) + comp.close() +} + +///| +test "control_command volume subcommands adjust and query volume" { + let comp = new_comp("vol-ctl") + let cmds = attach_mock_mixer(comp, init_pct=50, init_muted=false) + + assert_eq(comp.control_command("volume status"), (["ok 50"], true)) + assert_eq(comp.control_command("volume up"), (["ok 55"], true)) + assert_true(comp.volume_osd_shown()) + assert_eq(comp.control_command("volume down"), (["ok 50"], true)) + assert_eq(comp.control_command("volume mute"), (["ok 50 muted"], true)) + assert_eq(comp.control_command("volume unmute"), (["ok 50"], true)) + assert_eq(comp.control_command("volume toggle"), (["ok 50 muted"], true)) + assert_eq(comp.control_command("volume 75"), (["ok 75 muted"], true)) + assert_eq(comp.control_command("volume unmute"), (["ok 75"], true)) + assert_eq( + comp.control_command("volume nope"), + (["error usage: volume [up|down|mute|unmute|toggle|PCT|status]"], false), + ) + assert_eq( + comp.control_command("volume -5"), + (["error usage: volume [up|down|mute|unmute|toggle|PCT|status]"], false), + ) + assert_eq(cmds.length(), 8) + comp.close() +} diff --git a/compositor/shell/shortcuts.mbt b/compositor/shell/shortcuts.mbt index 6a2ad12..dc0dcbe 100644 --- a/compositor/shell/shortcuts.mbt +++ b/compositor/shell/shortcuts.mbt @@ -58,6 +58,10 @@ pub(all) enum ShortcutAction { DockApps /// The emoji picker (compositor/host/emoji_picker.mbt), like Windows' Win+. EmojiPicker + /// Hardware/media audio volume keys (compositor/host/volume.mbt). + VolumeUp + VolumeDown + VolumeMute } derive(Eq, Debug) ///| One row of the shortcut table. @@ -88,6 +92,9 @@ pub let shortcut_table : Array[ShortcutDef] = [ { id: "dock-apps", label: "Open dock app 1-9", action: DockApps, default_text: "Super+1" }, { id: "overview", label: "Overview of all windows", action: Overview, default_text: "Super+W" }, { id: "emoji-picker", label: "Emoji picker", action: EmojiPicker, default_text: "Super+Period" }, + { id: "volume-up", label: "Volume up", action: VolumeUp, default_text: "VolumeUp" }, + { id: "volume-down", label: "Volume down", action: VolumeDown, default_text: "VolumeDown" }, + { id: "volume-mute", label: "Mute audio", action: VolumeMute, default_text: "Mute" }, ] ///| evdev code -> key name, for the keys a combo can end in (US layout names). diff --git a/docs/handset.md b/docs/handset.md index 6259525..a3834a7 100644 --- a/docs/handset.md +++ b/docs/handset.md @@ -42,6 +42,17 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux - **Power key blank/wake:** Pressing `KEY_POWER` (`116`) in [`compositor/host/compositor.mbt`](../compositor/host/compositor.mbt) toggles manual screen blanking (`DPMS` off/on + touch cancellation in [`compositor/kms/kms_stub.c`](../compositor/kms/kms_stub.c)) while ignoring stray touches during blanking. Also controllable via `chandra-ctl screen [on|off|toggle|status]`. (Set `HandlePowerKey=ignore` in `/etc/systemd/logind.conf.d/` so `logind` does not power off immediately.) - **Settings Brightness slider:** [`compositor/shell/backlight.mbt`](../compositor/shell/backlight.mbt) reads `/sys/class/backlight/` (`ae94000.dsi.0`, `CHANDRA_BACKLIGHT` override) and writes changes via sysfs or `org.freedesktop.login1.Session.SetBrightness`. When a backlight device exists, **Settings > Power > Brightness** shows a `-` / slider / `+` control (`5%..100%`), also accessible via `chandra-ctl brightness [PCT|status]`. +## Audio & Volume Buttons + +- **Audio stack (PipeWire + WirePlumber + OnePlus 6T UCM2):** `pipewire`, `wireplumber`, `pipewire-pulse`, and `pipewire-alsa` drive the OnePlus 6T (`fajita`) ALSA UCM2 `HiFi` profile (`Speaker`, `Headphones`, `Mic1`/`Mic2`, `Headset`), with Qualcomm buffer tuning from `51-qcom.conf`. +- **Hardware volume keys:** [`compositor/host/volume.mbt`](../compositor/host/volume.mbt) binds `VolumeUp` (`KEY_VOLUMEUP` / `115`), `VolumeDown` (`KEY_VOLUMEDOWN` / `114`), and `Mute` (`KEY_MUTE` / `113`) in [`compositor/shell/shortcuts.mbt`](../compositor/shell/shortcuts.mbt) to async `wpctl` (with `pactl` fallback) commands: + - `5%` step per press, unmuting on volume up and capping hardware button increases at `100%`. + - Hold-to-repeat after `400 ms` (`90 ms` cadence) until key release. + - Works while the display is blanked (`screen_off` / `manual_screen_off`) without waking the screen. + - Passes `VolumeUp` / `VolumeDown` straight through to `chandra-camera` when it is the active foreground window (with no modal/popup/modifier) so the hardware buttons keep acting as the camera shutter. + - Shows a floating top-center Volume OSD pill (`1.8 s`) when the screen is on, and exposes `chandra-ctl volume [up|down|mute|unmute|toggle|PCT|status]`. +- **Mixer GUI (`moonmix`):** [`org.latha.moonmix`](https://git.site.latha.org/geordi/moonmix) provides a GTK4 + `libwireplumber` volume mixer (Playback, Recording, Output Devices, Input Devices) integrated into the launcher. + ## Face Unlock (`libcamera`) - On phones whose MIPI sensors (`imx371`, `imx519`, `imx376`) require `libcamera` SoftISP rather than raw V4L2 nodes, [`face/chandra-face`](../face/chandra-face) supports `libcamera:` entries via `python-libcamera` and applies `libcamera.properties.Rotation`. [`face/install.py`](../face/install.py) supports `--system-python` to run with system `python-opencv` + `python-numpy` on `aarch64`, and [`face/polkit-agent-helper.conf`](../face/polkit-agent-helper.conf) grants `char-video4linux`, `char-media`, and `char-dma_heap` access to polkit's helper sandbox. diff --git a/session/chandra-ctl b/session/chandra-ctl index 2206ede..27e2c56 100755 --- a/session/chandra-ctl +++ b/session/chandra-ctl @@ -13,6 +13,7 @@ chandra-ctl rotate [ARG] rotate/flip display (cw, ccw, flip, 0, 90, 180, 270, status) chandra-ctl screen [ARG] turn display off/on (on, off, toggle, status) chandra-ctl brightness [ARG] get/set backlight brightness percent (5..100, status) + chandra-ctl volume [ARG] get/set audio volume (up, down, mute, unmute, toggle, PCT, status) chandra-ctl osk [ARG] enable/disable/query on-screen keyboard (on, off, toggle, status) chandra-ctl status report display size, rotation, screen power, brightness, pointer, OSK chandra-ctl refresh schedule a full frame redraw @@ -32,7 +33,7 @@ import os import socket import sys -USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | screen [ARG] | brightness [ARG] | osk [ARG] | status | refresh | settings [TAB] | auth-demo [MODE] | auth-status | help}" +USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | screen [ARG] | brightness [ARG] | volume [ARG] | osk [ARG] | status | refresh | settings [TAB] | auth-demo [MODE] | auth-status | help}" def runtime_dir():