///| 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 }