From b6443076318cf8839093f3e85a1f3f57aceb525e Mon Sep 17 00:00:00 2001 From: ricktav <82380971+ricktav@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:06:02 +0100 Subject: [PATCH 1/4] Audio: the side mute switch mutes while it is on silent The kernel reports the ring/silent switch (mainline Apple device trees) as gpio-keys' KEY_MUTE, held down while on silent. labwc's XF86AudioMute binding toggled the mute and repeated while the key was held, so the mute flickered on and off for seconds with the OSD, again at every boot and resume, and flipping the switch back toggled instead of following it. omarchy-mute-switch (/usr/libexec, from the session's autostart) finds a gpio-keys device with KEY_MUTE, sets the default output's mute to the switch's position at login (quietly) and follows it with the volume OSD (omarchy-volume mute-on|mute-off). Each change is read back from the switch (EVIOCGKEY) after a short settle, so the release and press the kernel reports around a suspend change nothing. It exits without such a switch, looks for a lost one again, and ends with labwc. The Mute key binding becomes omarchy-volume mute-key, which toggles only while no switch is followed (the helper's pid in $XDG_RUNTIME_DIR). labwc cannot tell the switch from a keyboard's Mute key, so on such a device the helper also follows the Mute keys of the other input devices (Bluetooth or USB keyboards, also ones that connect later): a press toggles the mute with the OSD, repeats change nothing. A migration rewrites the shipped binding in existing users' rc.xml. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SFMaVf5sMxs7xEyPFZWGEj --- desktop/configuration/mute-switch | 324 +++++++++++++++++++++++++ desktop/install-tree | 1 + desktop/shell/bin/omarchy-volume | 30 ++- desktop/shell/default/labwc/autostart | 2 + desktop/shell/labwc-rc.xml | 6 +- desktop/shell/migrations/1795508927.sh | 12 + docs/tablet-sensors.md | 6 + tests/test_mute_switch.py | 258 ++++++++++++++++++++ tests/test_package_staging.py | 1 + tests/test_volume_keys.py | 41 +++- 10 files changed, 667 insertions(+), 14 deletions(-) create mode 100755 desktop/configuration/mute-switch create mode 100644 desktop/shell/migrations/1795508927.sh create mode 100644 tests/test_mute_switch.py diff --git a/desktop/configuration/mute-switch b/desktop/configuration/mute-switch new file mode 100755 index 00000000..9f9ce8b0 --- /dev/null +++ b/desktop/configuration/mute-switch @@ -0,0 +1,324 @@ +#!/usr/bin/python3 +"""The side mute switch (ring/silent): the sound output's mute follows it. + +The kernel reports the switch (iPhone, older iPads; Apple's device trees in +mainline) as KEY_MUTE of the gpio-keys input device, held down while the +switch is on silent and released on ring. labwc would take it for a Mute key +and toggle the mute on every repeat while it is held. Here the default output +is muted while the switch is on silent and unmuted on ring: quietly at the +start of the session, with the volume OSD (omarchy-volume mute-on|mute-off) +when the switch is moved. + +While it follows a switch, $XDG_RUNTIME_DIR/omarchy-mute-switch holds its +pid: omarchy-volume mute-key (labwc's XF86AudioMute) leaves the mute alone +then, as labwc cannot tell the switch from a keyboard's Mute key. The Mute +keys of the other input devices (a Bluetooth or USB keyboard, also one that +connects later) are followed here instead: each press toggles the mute, with +the OSD, and their repeats change nothing. Without a switch it exits at once, +and labwc's binding toggles. A switch that goes away is looked for again +every few seconds. It ends with the compositor (LABWC_PID). +""" +import fcntl +import os +from pathlib import Path +import select +import signal +import struct +import subprocess +import sys +import time + +INPUT = Path('/sys/class/input') +# The input devices whose KEY_MUTE is a switch, not a key: mainline's Apple +# device trees put the side switch in gpio-keys. A keyboard's Mute key is in +# its own device, and stays labwc's. +SWITCH_DEVICES = ('gpio-keys',) +EV_SYN, SYN_DROPPED, EV_KEY, KEY_MUTE = 0, 3, 1, 113 +# struct input_event: the time is two longs, of the kernel's width. +EVENT = struct.Struct('llHHi') +KEY_BYTES = 96 # KEY_CNT / 8 +EVIOCGKEY = 2 << 30 | KEY_BYTES << 16 | ord('E') << 8 | 0x18 # _IOC(_IOC_READ, 'E', 0x18, len) +SETTLE = 0.3 # seconds after the last change before the switch is read back +RETRY = 2.0 + + +def log(*args): + print('omarchy-mute-switch:', *args, file=sys.stderr, flush=True) + + +def has_key(capabilities_key, code, width=None): + """Whether an input device's sysfs capabilities/key bitmap has key CODE.""" + # Hex words of the kernel's long, most significant first. + width = width or struct.calcsize('L') * 8 + bits = 0 + for word in capabilities_key.split(): + bits = bits << width | int(word, 16) + return bool(bits >> code & 1) + + +def find_switches(root=INPUT, width=None): + """/dev/input/eventN of every input device that is a mute switch.""" + return find_mute(root, width)[0] + + +def find_keys(root=INPUT, width=None): + """/dev/input/eventN of every other input device with a Mute key: keyboards.""" + return find_mute(root, width)[1] + + +def find_mute(root=INPUT, width=None): + """The input devices with KEY_MUTE: (the switches, the keys).""" + found, keys_found = [], [] + for device in sorted(root.glob('event*'), key=lambda path: (len(path.name), path.name)): + try: + name = (device / 'device/name').read_text().strip() + keys = (device / 'device/capabilities/key').read_text() + except OSError: + continue + try: + if has_key(keys, KEY_MUTE, width): + (found if name in SWITCH_DEVICES else keys_found).append(f'/dev/input/{device.name}') + except ValueError: + continue + return found, keys_found + + +def is_down(fd): + """Whether KEY_MUTE is down (the switch on silent), as the kernel has it now.""" + bits = bytearray(KEY_BYTES) + fcntl.ioctl(fd, EVIOCGKEY, bits) + return bool(bits[KEY_MUTE // 8] >> KEY_MUTE % 8 & 1) + + +class Follower: + """When to read the switch, and what to do with what it reads. + + Every change of KEY_MUTE is read back from the switch (EVIOCGKEY) SETTLE + seconds after the last one, and the mute is set only when that position + differs from the one last set. When the machine suspends, the input core + releases every key held down, and gpio-keys reports the switch again when + it resumes: a switch on silent gives a release, then a press, both read + after the resume (processes are frozen before the devices suspend and + thawed after they resume, and the monotonic clock stands still in + between). Read back together, they are the position already set: no + unmute, no OSD. A bouncing contact settles the same way. Repeats (value 2) + are no change of position. + """ + + def __init__(self, settle=SETTLE, retry=RETRY): + self.settle, self.retry = settle, retry + self.applied = None # the mute last set; None before the first + self.due = 0.0 # when to read the switch: at once at the start + + def feed(self, data, now): + """The events in evdev bytes.""" + whole = len(data) // EVENT.size * EVENT.size + for _, _, kind, code, value in EVENT.iter_unpack(data[:whole]): + if (kind == EV_KEY and code == KEY_MUTE and value in (0, 1)) or (kind == EV_SYN and code == SYN_DROPPED): + self.due = now + self.settle + + def wait(self, now): + """Seconds until the switch is to be read, or None.""" + return None if self.due is None else max(0.0, self.due - now) + + def decide(self, muted): + """What to do with the position read when due: None, or (muted, quiet).""" + self.due = None + if muted == self.applied: + return None + return muted, self.applied is None # the first is the session's start: no OSD + + def done(self, muted): + self.applied = muted + + def failed(self, now): + self.due = now + self.retry + + +def presses(data): + """How many times a Mute key was pressed in these evdev bytes (not its repeats).""" + whole = len(data) // EVENT.size * EVENT.size + return sum(1 for _, _, kind, code, value in EVENT.iter_unpack(data[:whole]) + if kind == EV_KEY and code == KEY_MUTE and value == 1) + + +def toggle_mute(): + """A keyboard's Mute key: toggle the default output's mute, with the OSD.""" + for argv in (['omarchy-volume', 'mute-toggle'], ['wpctl', 'set-mute', '@DEFAULT_AUDIO_SINK@', 'toggle']): + try: + if subprocess.run(argv, stdin=subprocess.DEVNULL, timeout=10).returncode == 0: + return True + except (OSError, subprocess.SubprocessError) as error: + log(f'{argv[0]}: {error}') + return False + + +def set_mute(muted, quiet): + """Mute or unmute the default output; with the OSD unless QUIET.""" + plain = ['wpctl', 'set-mute', '@DEFAULT_AUDIO_SINK@', '1' if muted else '0'] + tries = [plain] if quiet else [['omarchy-volume', 'mute-on' if muted else 'mute-off'], plain] + for argv in tries: + try: + if subprocess.run(argv, stdin=subprocess.DEVNULL, timeout=10).returncode == 0: + return True + except (OSError, subprocess.SubprocessError) as error: + log(f'{argv[0]}: {error}') + return False + + +def flag_path(): + runtime = os.environ.get('XDG_RUNTIME_DIR') + return Path(runtime) / 'omarchy-mute-switch' if runtime else None + + +def raise_flag(): + flag = flag_path() + if flag: + try: + flag.with_name(flag.name + '.new').write_text(f'{os.getpid()}\n') + os.replace(flag.with_name(flag.name + '.new'), flag) + except OSError as error: + log(f'{flag}: {error}') + + +def lower_flag(): + flag = flag_path() + try: + if flag and flag.read_text().strip() == str(os.getpid()): + flag.unlink() + except OSError: + pass + + +def alive(pid): + if not pid: + return True + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except OSError: + pass + return True + + +def main(): + compositor = int(os.environ.get('LABWC_PID') or 0) + running = True + + def stop(*_): + nonlocal running + running = False + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGINT, stop) + + devices = {} # fd: path, the switches + keyboards = {} # fd: path, the other devices with a Mute key + follower = Follower() + found_once, next_scan, next_keys = False, 0.0, 0.0 + + def close_all(): + for fd in devices: + os.close(fd) + devices.clear() + + def close_keyboards(): + for fd in keyboards: + os.close(fd) + keyboards.clear() + + def follow_keyboards(): + # Keyboards come and go (Bluetooth): new ones are opened at every look. + known = set(keyboards.values()) + for path in find_keys(): + if path not in known: + try: + keyboards[os.open(path, os.O_RDONLY | os.O_NONBLOCK)] = path + log('Mute key of', path) + except OSError as error: + log(f'{path}: {error}') + + try: + while running and alive(compositor): + now = time.monotonic() + if not devices and now >= next_scan: + for path in find_switches(): + try: + devices[os.open(path, os.O_RDONLY | os.O_NONBLOCK)] = path + except OSError as error: + log(f'{path}: {error}') + if devices: + log('following', ', '.join(devices.values())) + found_once = True + raise_flag() + follower.due = now # read the switch as it is now + elif not found_once: + log('no hardware mute switch') + return 0 + else: + next_scan = now + RETRY + if devices and now >= next_keys: + follow_keyboards() + next_keys = now + RETRY + wait = follower.wait(now) if devices else None + timeout = 1.0 if wait is None else min(1.0, wait) + if not devices: + time.sleep(timeout) + continue + lost = False + for fd in select.select(list(devices) + list(keyboards), [], [], timeout)[0]: + if fd in keyboards: + try: + data = os.read(fd, EVENT.size * 64) + except BlockingIOError: + continue + except OSError: + data = b'' + if not data: # gone (disconnected): found again when it comes back + log('gone:', keyboards.pop(fd)) + os.close(fd) + continue + for _ in range(presses(data)): + toggle_mute() + continue + try: + data = os.read(fd, EVENT.size * 64) + except BlockingIOError: + continue + except OSError as error: + log(f'{devices[fd]}: {error}') + lost = True + break + if not data: + lost = True + break + follower.feed(data, time.monotonic()) + now = time.monotonic() + if not lost and follower.wait(now) == 0.0: + try: + muted = any(is_down(fd) for fd in devices) + except OSError as error: + log(f'reading the switch: {error}') + lost = True + else: + action = follower.decide(muted) + if action: + if set_mute(*action): + follower.done(action[0]) + log('silent: muted' if action[0] else 'ring: unmuted') + else: + follower.failed(now) + if lost: + # Gone (unbound, reloaded): look for it again in a while. + close_all() + lower_flag() + next_scan = time.monotonic() + RETRY + finally: + close_all() + close_keyboards() + lower_flag() + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/desktop/install-tree b/desktop/install-tree index c15b48dc..bf99e03e 100755 --- a/desktop/install-tree +++ b/desktop/install-tree @@ -129,6 +129,7 @@ $config/first-theme usr/libexec/arch-ipad-first-theme 755 $config/scale-output usr/libexec/arch-ipad-scale-output 755 $config/auto-brightness usr/libexec/arch-ipad-auto-brightness 755 $config/rotate-output usr/libexec/arch-ipad-rotate-output 755 +$config/mute-switch usr/libexec/omarchy-mute-switch 755 $config/j120-speaker-map usr/libexec/omarchy-j120-speaker-map 755 $config/j120-speakers.conf usr/share/omarchy/j120-speakers.conf 644 $config/touch-output usr/libexec/arch-ipad-touch-output 755 diff --git a/desktop/shell/bin/omarchy-volume b/desktop/shell/bin/omarchy-volume index 1b1befb8..634945ca 100755 --- a/desktop/shell/bin/omarchy-volume +++ b/desktop/shell/bin/omarchy-volume @@ -4,6 +4,20 @@ set -u # labwc runs key bindings without the session's OMARCHY_PATH (labwc-autostart's). export OMARCHY_PATH=${OMARCHY_PATH:-/usr/share/omarchy} +# labwc's XF86AudioMute. A hardware mute switch (the side switch: gpio-keys' +# KEY_MUTE, held down while on silent) is omarchy-mute-switch's while that +# follows it ($XDG_RUNTIME_DIR/omarchy-mute-switch holds its pid): the mute +# follows the switch, and the key, which is the switch and repeats while held, +# changes nothing here. labwc cannot tell it from a keyboard's Mute key, so +# omarchy-mute-switch toggles for those itself (mute-toggle). Without a switch +# this toggles. +if [[ ${1:-} == mute-key ]]; then + if pid=$(cat "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/omarchy-mute-switch" 2>/dev/null) && + [[ $pid =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then + exit 0 + fi + set -- mute-toggle +fi # The volume in whole percent, from "Volume: 0.45 [MUTED]". percent() { awk '{ printf "%d", $2 * 100 + 0.5 }' <<< "$1"; } state=$(wpctl get-volume @DEFAULT_AUDIO_SINK@) || exit 1 @@ -12,16 +26,18 @@ percent=$(percent "$state") case ${1:-} in raise) percent=$(( percent / 5 * 5 + 5 )) ;; lower) percent=$(( (percent + 4) / 5 * 5 - 5 )) ;; - mute-toggle) ;; - *) echo 'Usage: omarchy-volume raise|lower|mute-toggle' >&2; exit 2 ;; + # mute-on and mute-off: the side switch (omarchy-mute-switch). + mute-toggle|mute-on|mute-off) ;; + *) echo 'Usage: omarchy-volume raise|lower|mute-toggle|mute-on|mute-off|mute-key' >&2; exit 2 ;; esac (( percent > 100 )) && percent=100 (( percent < 0 )) && percent=0 -if [[ $1 == mute-toggle ]]; then - wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle -else - wpctl set-volume @DEFAULT_AUDIO_SINK@ "$percent%" -fi || exit 1 +case $1 in + mute-toggle) wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle ;; + mute-on) wpctl set-mute @DEFAULT_AUDIO_SINK@ 1 ;; + mute-off) wpctl set-mute @DEFAULT_AUDIO_SINK@ 0 ;; + *) wpctl set-volume @DEFAULT_AUDIO_SINK@ "$percent%" ;; +esac || exit 1 state=$(wpctl get-volume @DEFAULT_AUDIO_SINK@) || exit 0 percent=$(percent "$state") icon=volume-high diff --git a/desktop/shell/default/labwc/autostart b/desktop/shell/default/labwc/autostart index b718d96f..c4434ac8 100755 --- a/desktop/shell/default/labwc/autostart +++ b/desktop/shell/default/labwc/autostart @@ -15,6 +15,8 @@ rm -f "$XDG_RUNTIME_DIR/omarchy-overview-open" systemctl --user import-environment WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE > "$XDG_RUNTIME_DIR/arch-ipad-user-env.log" 2>&1 # Sensor policy follows the compositor lifetime; it stays off until enabled. /usr/libexec/arch-ipad-auto-brightness > "$XDG_RUNTIME_DIR/arch-ipad-auto-brightness.log" 2>&1 & +# The output's mute follows the side mute switch; exits without one. +/usr/libexec/omarchy-mute-switch > "$XDG_RUNTIME_DIR/omarchy-mute-switch.log" 2>&1 & # Keep the theme-coloured keyboard resident but hidden until the user taps Show. export OMARCHY_PATH=/usr/share/omarchy printf '0\n' > "$XDG_RUNTIME_DIR/omarchy-keyboard-visible" diff --git a/desktop/shell/labwc-rc.xml b/desktop/shell/labwc-rc.xml index 08739264..4b4ab37a 100644 --- a/desktop/shell/labwc-rc.xml +++ b/desktop/shell/labwc-rc.xml @@ -45,7 +45,9 @@ + Brightness is in the Control Center. The side mute switch is + omarchy-mute-switch's, and so are keyboards' Mute keys on such a + device: mute-key toggles only without one. --> @@ -53,7 +55,7 @@ - + diff --git a/desktop/shell/migrations/1795508927.sh b/desktop/shell/migrations/1795508927.sh new file mode 100644 index 00000000..df18c356 --- /dev/null +++ b/desktop/shell/migrations/1795508927.sh @@ -0,0 +1,12 @@ +echo "The side mute switch mutes the sound while it is on silent" + +# labwc's Mute key binding (XF86AudioMute) toggled the mute, and the side +# switch, held down while on silent, repeats it. omarchy-volume mute-key leaves +# the mute to omarchy-mute-switch on a device with the switch and toggles +# elsewhere. An existing ~/.config/labwc/rc.xml gets it where the binding is +# as shipped; labwc reads it at its next start, the next login. +rc="$HOME/.config/labwc/rc.xml" +if [[ -f $rc ]] && grep -q 'command="omarchy-volume mute-toggle"' "$rc"; then + sed '//{n;s|||;}' "$rc" > "$rc.new" + mv -- "$rc.new" "$rc" +fi diff --git a/docs/tablet-sensors.md b/docs/tablet-sensors.md index 18070171..fc017b0d 100644 --- a/docs/tablet-sensors.md +++ b/docs/tablet-sensors.md @@ -22,3 +22,9 @@ Both fresh desktop staging and the public-root builder include the helper and it Host checks cover the retained light policy, switch state, missing power daemon, stale-value/dark-panel refusal, manual pause, actual socket writes, rotation debounce/lock/unlock and compositor exit, plus staging and public-root inclusion. Physical lux response, all four orientation directions, touch mapping and power-button/idle/sleep coexistence still need a device run. + +## Side mute switch + +The kernel reports the ring/silent switch (iPhone, older iPads) as `KEY_MUTE` of the `gpio-keys` input device, held down while the switch is on silent. `omarchy-mute-switch` (`/usr/libexec`, started by the session's autostart) mutes the default output while the switch is on silent and unmutes it on ring: quietly at login, with the volume OSD (`omarchy-volume mute-on|mute-off`) when the switch is moved. A suspend and resume, which the kernel reports as a release and a press, changes nothing. Without such a switch it exits at once; it ends with labwc. Logs are in `$XDG_RUNTIME_DIR/omarchy-mute-switch.log`. + +Labwc's Mute key runs `omarchy-volume mute-key`, which toggles the mute only while no switch is followed (`$XDG_RUNTIME_DIR/omarchy-mute-switch` names the helper's pid). Labwc cannot tell the switch from a keyboard's Mute key, so on a device with the switch the helper follows the Mute keys of the other input devices too (a Bluetooth or USB keyboard, also one that connects later; it looks for new ones every 2 s): each press toggles the mute with the OSD (`omarchy-volume mute-toggle`), repeats change nothing. diff --git a/tests/test_mute_switch.py b/tests/test_mute_switch.py new file mode 100644 index 00000000..7e88b476 --- /dev/null +++ b/tests/test_mute_switch.py @@ -0,0 +1,258 @@ +"""desktop/configuration/mute-switch: the output's mute follows the side switch, with no hardware access.""" +import importlib.machinery +import importlib.util +import os +from pathlib import Path +import shutil +import struct +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +PROJECT = Path(__file__).resolve().parents[1] +loader = importlib.machinery.SourceFileLoader('mute_switch', str(PROJECT / 'desktop/configuration/mute-switch')) +spec = importlib.util.spec_from_loader(loader.name, loader) +m = importlib.util.module_from_spec(spec) +loader.exec_module(m) + +KEY_VOLUMEDOWN, KEY_VOLUMEUP, KEY_POWER, KEY_HOMEPAGE = 114, 115, 116, 172 + + +def capabilities(codes, width=64): + """A sysfs capabilities/key bitmap as the kernel prints it: hex longs, most significant first.""" + bits = sum(1 << code for code in codes) + words = [] + while bits: + words.append(bits & (1 << width) - 1) + bits >>= width + return ' '.join(f'{word:x}' for word in reversed(words or [0])) + '\n' + + +def event(kind, code, value): + return m.EVENT.pack(0, 0, kind, code, value) + + +def key(value): + return event(m.EV_KEY, m.KEY_MUTE, value) + + +SYN = event(m.EV_SYN, 0, 0) + + +class Detection(unittest.TestCase): + def test_the_bitmap_is_read_in_the_kernels_word_width(self): + codes = (m.KEY_MUTE, KEY_VOLUMEDOWN, KEY_VOLUMEUP, KEY_POWER, KEY_HOMEPAGE) + for width in (32, 64): + with self.subTest(width=width): + text = capabilities(codes, width) + self.assertTrue(m.has_key(text, m.KEY_MUTE, width)) + self.assertFalse(m.has_key(text, 112, width)) + self.assertFalse(m.has_key(capabilities((KEY_VOLUMEUP, KEY_POWER), width), m.KEY_MUTE, width)) + self.assertFalse(m.has_key('0\n', m.KEY_MUTE, 64)) + + def test_only_gpio_keys_with_key_mute_is_a_switch(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + + def device(name, label, codes): + (root / name / 'device/capabilities').mkdir(parents=True) + (root / name / 'device/name').write_text(label + '\n') + (root / name / 'device/capabilities/key').write_text(capabilities(codes)) + device('event0', 'gpio-keys', (m.KEY_MUTE, KEY_VOLUMEDOWN, KEY_VOLUMEUP, KEY_POWER)) + device('event1', 'Apple Inc. Magic Keyboard', (m.KEY_MUTE, KEY_VOLUMEUP)) # a key, not a switch + device('event2', 'gpio-keys', (KEY_POWER, KEY_HOMEPAGE)) # an iPad without the switch + device('event10', 'gpio-keys', (m.KEY_MUTE,)) + (root / 'event3').mkdir() # gone while scanned + self.assertEqual(m.find_switches(root, 64), ['/dev/input/event0', '/dev/input/event10']) + self.assertEqual(m.find_switches(root / 'none', 64), []) + self.assertEqual(m.find_keys(root, 64), ['/dev/input/event1']) + + def test_the_switch_state_ioctl(self): + self.assertEqual(m.EVIOCGKEY, 0x80604518) # EVIOCGKEY(96): KEY_CNT bits + self.assertEqual(m.EVENT.size, struct.calcsize('l') * 2 + 8) + + +class Following(unittest.TestCase): + def test_the_start_is_read_at_once_and_set_quietly(self): + follower = m.Follower() + self.assertEqual(follower.wait(100.0), 0.0) + self.assertEqual(follower.decide(True), (True, True)) + follower.done(True) + self.assertIsNone(follower.wait(100.0)) + follower = m.Follower() + self.assertEqual(follower.decide(False), (False, True)) + + def test_a_move_is_read_back_after_it_settles_and_shown(self): + follower = m.Follower(settle=0.3) + follower.decide(False), follower.done(False) + follower.feed(key(1) + SYN, 10.0) + self.assertAlmostEqual(follower.wait(10.1), 0.2) + self.assertEqual(follower.decide(True), (True, False)) # not quiet: the OSD + follower.done(True) + follower.feed(key(0) + SYN, 20.0) + self.assertEqual(follower.decide(False), (False, False)) + + def test_repeats_and_other_keys_are_no_change(self): + follower = m.Follower() + follower.decide(True), follower.done(True) + follower.feed((key(2) + SYN) * 20 + event(m.EV_KEY, KEY_VOLUMEUP, 1) + SYN, 10.0) + self.assertIsNone(follower.wait(10.0)) + + def test_a_suspend_and_resume_on_silent_neither_unmutes_nor_shows(self): + # The input core releases the held key at suspend, gpio-keys presses it at resume. + follower = m.Follower(settle=0.3) + follower.decide(True), follower.done(True) + follower.feed(key(0) + SYN, 50.0) + follower.feed(key(1) + SYN, 50.001) + self.assertGreater(follower.wait(50.1), 0) # nothing yet: the release is not acted on + self.assertIsNone(follower.decide(True)) # the switch, read back: still silent + + def test_a_bouncing_contact_waits_for_the_last_change(self): + follower = m.Follower(settle=0.3) + follower.decide(False), follower.done(False) + for at, value in ((10.0, 1), (10.1, 0), (10.2, 1)): + follower.feed(key(value), at) + self.assertAlmostEqual(follower.wait(10.4), 0.1) + + def test_dropped_events_read_the_switch_again(self): + follower = m.Follower() + follower.decide(False), follower.done(False) + follower.feed(event(m.EV_SYN, m.SYN_DROPPED, 0), 10.0) + self.assertIsNotNone(follower.wait(10.0)) + + def test_a_failure_is_tried_again(self): + follower = m.Follower(retry=2.0) + self.assertEqual(follower.decide(True), (True, True)) + follower.failed(5.0) + self.assertEqual(follower.wait(5.0), 2.0) + self.assertEqual(follower.decide(True), (True, True)) # still quiet: nothing was set yet + + def test_a_partial_read_is_ignored(self): + follower = m.Follower() + follower.decide(False), follower.done(False) + follower.feed(key(1)[:-3], 10.0) + self.assertIsNone(follower.wait(10.0)) + + +class Setting(unittest.TestCase): + def run_with(self, results, muted, quiet): + calls = [] + + def run(argv, **_): + calls.append(argv) + return subprocess.CompletedProcess(argv, results.pop(0)) + with patch.object(m.subprocess, 'run', side_effect=run): + return m.set_mute(muted, quiet), calls + + def test_quiet_is_wpctl_and_a_move_is_omarchy_volume(self): + self.assertEqual(self.run_with([0], True, True), + (True, [['wpctl', 'set-mute', '@DEFAULT_AUDIO_SINK@', '1']])) + self.assertEqual(self.run_with([0], False, False), (True, [['omarchy-volume', 'mute-off']])) + + def test_without_the_osd_the_mute_is_still_set(self): + ok, calls = self.run_with([1, 0], True, False) + self.assertTrue(ok) + self.assertEqual(calls, [['omarchy-volume', 'mute-on'], ['wpctl', 'set-mute', '@DEFAULT_AUDIO_SINK@', '1']]) + self.assertFalse(self.run_with([1, 1], True, False)[0]) + + +class KeyboardMute(unittest.TestCase): + """A keyboard's Mute key on a device with the switch: labwc leaves it alone, the helper toggles.""" + + def test_each_press_counts_and_repeats_and_releases_do_not(self): + self.assertEqual(m.presses(key(1) + SYN + key(2) + key(2) + key(0) + SYN), 1) + self.assertEqual(m.presses(key(1) + key(0) + key(1) + key(0)), 2) + self.assertEqual(m.presses(event(m.EV_KEY, KEY_VOLUMEUP, 1) + SYN), 0) + self.assertEqual(m.presses(key(1)[:10]), 0) # a partial read + + def toggle_with(self, results): + calls = [] + + def run(argv, **_): + calls.append(argv) + return subprocess.CompletedProcess(argv, results.pop(0)) + with patch.object(m.subprocess, 'run', side_effect=run): + return m.toggle_mute(), calls + + def test_a_press_toggles_with_the_osd(self): + self.assertEqual(self.toggle_with([0]), (True, [['omarchy-volume', 'mute-toggle']])) + + def test_without_the_osd_it_still_toggles(self): + self.assertEqual(self.toggle_with([1, 0]), + (True, [['omarchy-volume', 'mute-toggle'], ['wpctl', 'set-mute', '@DEFAULT_AUDIO_SINK@', 'toggle']])) + + +class Session(unittest.TestCase): + def test_without_a_switch_it_exits_and_leaves_no_flag(self): + with tempfile.TemporaryDirectory() as runtime, \ + patch.dict(os.environ, {'XDG_RUNTIME_DIR': runtime, 'LABWC_PID': ''}), \ + patch.object(m, 'find_switches', return_value=[]), \ + patch.object(m.signal, 'signal'), patch.object(m, 'log'): + self.assertEqual(m.main(), 0) + self.assertEqual(os.listdir(runtime), []) + + def test_the_flag_names_this_process_and_goes_with_it(self): + with tempfile.TemporaryDirectory() as runtime, patch.dict(os.environ, {'XDG_RUNTIME_DIR': runtime}): + m.raise_flag() + flag = Path(runtime) / 'omarchy-mute-switch' + self.assertEqual(flag.read_text(), f'{os.getpid()}\n') + m.lower_flag() + self.assertFalse(flag.exists()) + flag.write_text('1\n') # another's: left alone + m.lower_flag() + self.assertTrue(flag.exists()) + + def test_the_package_stages_it_and_the_session_starts_it(self): + install = (PROJECT / 'desktop/install-tree').read_text() + self.assertIn('$config/mute-switch usr/libexec/omarchy-mute-switch 755', install) + autostart = (PROJECT / 'desktop/shell/default/labwc/autostart').read_text() + self.assertIn('/usr/libexec/omarchy-mute-switch > "$XDG_RUNTIME_DIR/omarchy-mute-switch.log" 2>&1 &', + autostart) + rc = (PROJECT / 'desktop/shell/labwc-rc.xml').read_text() + block = rc[rc.index(''):] + self.assertIn('command="omarchy-volume mute-key"', block[:block.index('')]) + self.assertNotIn('mute-toggle', rc) + + +MIGRATION = PROJECT / 'desktop/shell/migrations/1795508927.sh' + + +@unittest.skipUnless(shutil.which('bash'), 'bash is required') +class Migration(unittest.TestCase): + def migrate(self, text): + with tempfile.TemporaryDirectory() as home: + rc = Path(home) / '.config/labwc/rc.xml' + if text is not None: + rc.parent.mkdir(parents=True) + rc.write_text(text) + result = subprocess.run(['bash', '-euo', 'pipefail', str(MIGRATION)], capture_output=True, text=True, + env={'PATH': os.environ['PATH'], 'HOME': home}, timeout=30) + self.assertEqual(result.returncode, 0, result.stderr) + return rc.read_text() if rc.exists() else None + + def test_the_shipped_binding_becomes_mute_key(self): + shipped = (PROJECT / 'desktop/shell/labwc-rc.xml').read_text() + old = shipped.replace('omarchy-volume mute-key', 'omarchy-volume mute-toggle') + self.assertNotEqual(old, shipped) + migrated = self.migrate(old) + self.assertIn('', migrated) + self.assertNotIn('mute-toggle', migrated) + self.assertEqual(migrated, old.replace('mute-toggle', 'mute-key')) + self.assertEqual(self.migrate(migrated), migrated) + + def test_a_users_own_bindings_are_left_alone(self): + own = ('\n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + ' \n' + '\n') + self.assertEqual(self.migrate(own), own) + self.assertIsNone(self.migrate(None)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_package_staging.py b/tests/test_package_staging.py index 1b50177c..de4b0c18 100644 --- a/tests/test_package_staging.py +++ b/tests/test_package_staging.py @@ -92,6 +92,7 @@ def test_trusted_ui_fallback_theme_and_tmpfiles_are_staged(self): self.assertFalse((skel / '.bash_profile').exists()) self.assertTrue(mode(target / 'usr/libexec/arch-ipad-rotate-output') & 0o111) self.assertTrue(mode(target / 'usr/libexec/arch-ipad-touch-output') & 0o111) + self.assertEqual(mode(target / 'usr/libexec/omarchy-mute-switch'), 0o755) # The user's defaults, and the same files where omarchy-refresh-config takes them from. for name in ('labwc/rc.xml', 'labwc/autostart', 'foot/foot.ini', 'omarchy-ipad/shell.json'): self.assertEqual((skel / '.config' / name).read_bytes(), (omarchy / 'config' / name).read_bytes(), name) diff --git a/tests/test_volume_keys.py b/tests/test_volume_keys.py index 94a0f1a0..c50bcf19 100644 --- a/tests/test_volume_keys.py +++ b/tests/test_volume_keys.py @@ -10,9 +10,16 @@ class VolumeKeys(unittest.TestCase): - def run_keys(self, action, volume='0.45'): - """Run omarchy-volume ACTION at VOLUME; returns (exit code, the calls it made).""" + def run_keys(self, action, volume='0.45', switch=None): + """Run omarchy-volume ACTION at VOLUME; returns (exit code, the calls it made). + + SWITCH: what $XDG_RUNTIME_DIR/omarchy-mute-switch holds (omarchy-mute-switch's pid), if anything. + """ with tempfile.TemporaryDirectory() as directory: + runtime = Path(directory) / 'runtime' + runtime.mkdir() + if switch is not None: + (runtime / 'omarchy-mute-switch').write_text(switch) bin_dir, log, level = Path(directory), Path(directory) / 'calls', Path(directory) / 'level' level.write_text(volume) (bin_dir / 'omarchy-shell').write_text(f'#!/bin/sh\necho "shell $*" >> {log}\n') @@ -26,9 +33,10 @@ def run_keys(self, action, volume='0.45'): """) for name in ('omarchy-shell', 'wpctl'): (bin_dir / name).chmod(0o755) - env = {**os.environ, 'PATH': f'{bin_dir}:/usr/bin:/bin'} + env = {**os.environ, 'PATH': f'{bin_dir}:/usr/bin:/bin', 'XDG_RUNTIME_DIR': str(runtime)} result = subprocess.run(['bash', str(SCRIPT), action], env=env, capture_output=True, text=True) - return result.returncode, [line for line in log.read_text().splitlines() if 'get-volume' not in line] + calls = log.read_text().splitlines() if log.exists() else [] + return result.returncode, [line for line in calls if 'get-volume' not in line] def test_steps_land_on_multiples_of_5(self): for action, volume, expected in (('raise', '0.45', '50%'), ('raise', '0.12', '15%'), @@ -45,9 +53,32 @@ def test_mute_toggles(self): code, calls = self.run_keys('mute-toggle') self.assertEqual(calls[0], 'wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle') + def test_the_mute_switch_sets_the_mute_with_the_osd(self): + for action, value in (('mute-on', '1'), ('mute-off', '0')): + with self.subTest(action=action): + code, calls = self.run_keys(action) + self.assertEqual(code, 0) + self.assertEqual(calls[0], f'wpctl set-mute @DEFAULT_AUDIO_SINK@ {value}') + self.assertTrue(calls[-1].startswith('shell -q shell summon omarchy.osd ')) + + def test_the_mute_key_toggles_only_without_a_followed_switch(self): + code, calls = self.run_keys('mute-key') + self.assertEqual(calls[0], 'wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle') + # omarchy-mute-switch follows the side switch: the key (the switch itself) changes nothing. + code, calls = self.run_keys('mute-key', switch=f'{os.getpid()}\n') + self.assertEqual((code, calls), (0, [])) + # One that is gone, or a flag that names no process, is no switch followed. + dead = subprocess.Popen(['true']) + dead.wait() + for flag in (f'{dead.pid}\n', 'garbage\n', ''): + with self.subTest(flag=flag): + code, calls = self.run_keys('mute-key', switch=flag) + self.assertEqual(calls[0], 'wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle') + def test_the_volume_keys_are_bound_to_volume(self): rc = (PROJECT / 'desktop/shell/labwc-rc.xml').read_text() - for key, action in (('XF86AudioRaiseVolume', 'raise'), ('XF86AudioLowerVolume', 'lower')): + for key, action in (('XF86AudioRaiseVolume', 'raise'), ('XF86AudioLowerVolume', 'lower'), + ('XF86AudioMute', 'mute-key')): block = rc[rc.index(f''):] self.assertIn(f'omarchy-volume {action}', block[:block.index('')]) From 102e5ec9ca2108714a6ba18cfe06342c8cd93eb9 Mon Sep 17 00:00:00 2001 From: ricktav <82380971+ricktav@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:14:47 +0100 Subject: [PATCH 2/4] Changelog: the side mute switch Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SFMaVf5sMxs7xEyPFZWGEj --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index edc364d2..04dfddaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ is missing or empty. - All iPads: a Smart Cover that closes or opens while the system is busy is no longer missed, and a cover whose driver comes up late is followed too. +- iPhone and iPads with a ring/silent switch: the switch mutes the sound + while it is on silent and unmutes it on ring, with the volume indicator. + Before, it toggled the mute on and off for several seconds, and again + after every wake. A keyboard's Mute key still toggles the mute. ## [0.3.4] - 2026-11-24 From e5414b601d5345c5b2338268860dfc7aa06ce097 Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Tue, 24 Nov 2026 19:07:52 +0800 Subject: [PATCH 3/4] Audio: the mute switch is also found in a gpio-keys node with a label gpio-keys names its input device after the device tree node's label when it has one, so a labelled node would not be called gpio-keys and its side switch would be taken for a keyboard's Mute key. The driver always sets phys to gpio-keys/input0: a device with that phys is a switch too. Assisted-by: LLM --- desktop/configuration/mute-switch | 13 ++++++++++--- tests/test_mute_switch.py | 9 +++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/desktop/configuration/mute-switch b/desktop/configuration/mute-switch index 9f9ce8b0..ebeefed2 100755 --- a/desktop/configuration/mute-switch +++ b/desktop/configuration/mute-switch @@ -30,9 +30,11 @@ import time INPUT = Path('/sys/class/input') # The input devices whose KEY_MUTE is a switch, not a key: mainline's Apple -# device trees put the side switch in gpio-keys. A keyboard's Mute key is in -# its own device, and stays labwc's. +# device trees put the side switch in gpio-keys. The driver names its device +# after the node's label, if it has one, and always sets this phys. A +# keyboard's Mute key is in its own device, and stays labwc's. SWITCH_DEVICES = ('gpio-keys',) +SWITCH_PHYS = 'gpio-keys/' EV_SYN, SYN_DROPPED, EV_KEY, KEY_MUTE = 0, 3, 1, 113 # struct input_event: the time is two longs, of the kernel's width. EVENT = struct.Struct('llHHi') @@ -75,9 +77,14 @@ def find_mute(root=INPUT, width=None): keys = (device / 'device/capabilities/key').read_text() except OSError: continue + try: + phys = (device / 'device/phys').read_text().strip() + except OSError: + phys = '' + switch = name in SWITCH_DEVICES or phys.startswith(SWITCH_PHYS) try: if has_key(keys, KEY_MUTE, width): - (found if name in SWITCH_DEVICES else keys_found).append(f'/dev/input/{device.name}') + (found if switch else keys_found).append(f'/dev/input/{device.name}') except ValueError: continue return found, keys_found diff --git a/tests/test_mute_switch.py b/tests/test_mute_switch.py index 7e88b476..5395ea27 100644 --- a/tests/test_mute_switch.py +++ b/tests/test_mute_switch.py @@ -55,16 +55,21 @@ def test_only_gpio_keys_with_key_mute_is_a_switch(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) - def device(name, label, codes): + def device(name, label, codes, phys=None): (root / name / 'device/capabilities').mkdir(parents=True) (root / name / 'device/name').write_text(label + '\n') (root / name / 'device/capabilities/key').write_text(capabilities(codes)) + if phys is not None: + (root / name / 'device/phys').write_text(phys + '\n') device('event0', 'gpio-keys', (m.KEY_MUTE, KEY_VOLUMEDOWN, KEY_VOLUMEUP, KEY_POWER)) device('event1', 'Apple Inc. Magic Keyboard', (m.KEY_MUTE, KEY_VOLUMEUP)) # a key, not a switch device('event2', 'gpio-keys', (KEY_POWER, KEY_HOMEPAGE)) # an iPad without the switch device('event10', 'gpio-keys', (m.KEY_MUTE,)) + # A gpio-keys node with a label: the driver names the device after it. + device('event11', 'Buttons', (m.KEY_MUTE, KEY_POWER), phys='gpio-keys/input0') (root / 'event3').mkdir() # gone while scanned - self.assertEqual(m.find_switches(root, 64), ['/dev/input/event0', '/dev/input/event10']) + self.assertEqual(m.find_switches(root, 64), + ['/dev/input/event0', '/dev/input/event10', '/dev/input/event11']) self.assertEqual(m.find_switches(root / 'none', 64), []) self.assertEqual(m.find_keys(root, 64), ['/dev/input/event1']) From 834319a071e8c96bc658ddb2f4943709d7add831 Mon Sep 17 00:00:00 2001 From: Henrik Klee Date: Tue, 24 Nov 2026 19:07:52 +0800 Subject: [PATCH 4/4] Changelog: iPhones and iPads with the mute switch Assisted-by: LLM --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04dfddaf..3b6ed684 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,7 @@ is missing or empty. - All iPads: a Smart Cover that closes or opens while the system is busy is no longer missed, and a cover whose driver comes up late is followed too. -- iPhone and iPads with a ring/silent switch: the switch mutes the sound +- iPhones and iPads with a ring/silent switch: the switch mutes the sound while it is on silent and unmutes it on ring, with the volume indicator. Before, it toggled the mute on and off for several seconds, and again after every wake. A keyboard's Mute key still toggles the mute.