diff --git a/CHANGELOG.md b/CHANGELOG.md index 70439a8f..cf6c9088 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,10 @@ release is checked here and released on by hand. boot's gpg-agent ends after the keyring setup, and session programs keep fewer malloc arenas (tcballard). +- The ring/silent switch's helper is a small C program instead of Python: + about 9 MiB more free memory, and it waits longer between retries while no + audio output is there (tcballard). + ### Desktop - The power, lock and sleep daemon is a small C program instead of Python: diff --git a/Makefile b/Makefile index 7c9a4604..379c109f 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ # make install DESTDIR= OMARCHY= DBUS_NEXT= # # The compiles are the on-screen keyboard (wvkbd with this repository's -# patches), the startup cursor helper (wtype) and the power daemon +# patches), the startup cursor helper (wtype), the mute-switch helper and the power daemon # (omarchy-powerd, against libsystemd's sd-bus: the recipe's makedepends); # desktop/install-tree puts every file in place. @@ -15,13 +15,17 @@ CC ?= cc CFLAGS ?= -O2 PKG_CONFIG ?= pkg-config -all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd +all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd $(BUILD)/omarchy-mute-switch $(BUILD)/omarchy-powerd: desktop/configuration/powerd.c mkdir -p $(BUILD) $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 -DHAVE_SD_BUS $< \ $$($(PKG_CONFIG) --cflags --libs libsystemd) -lpthread -lm $(LDFLAGS) -o $@ +$(BUILD)/omarchy-mute-switch: desktop/configuration/mute-switch.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -std=c99 desktop/configuration/mute-switch.c $(LDFLAGS) -o $@ + $(BUILD)/wvkbd-mobintl: @test -d "$(WVKBD)" || { echo 'Set WVKBD to the wvkbd v0.20 source' >&2; exit 1; } @grep -q preferred_buffer_scale /usr/include/wayland-client-protocol.h || \ diff --git a/desktop/configuration/mute-switch b/desktop/configuration/mute-switch deleted file mode 100755 index ebeefed2..00000000 --- a/desktop/configuration/mute-switch +++ /dev/null @@ -1,331 +0,0 @@ -#!/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. 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') -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: - 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 switch 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/configuration/mute-switch.c b/desktop/configuration/mute-switch.c new file mode 100644 index 00000000..ce957086 --- /dev/null +++ b/desktop/configuration/mute-switch.c @@ -0,0 +1,591 @@ +/* + * omarchy-mute-switch: follow the hardware ring/silent switch (KEY_MUTE on + * gpio-keys) and forward Mute keys from external keyboards. + * + * The kernel reports the side switch (iPhone, older iPads) as KEY_MUTE of the + * gpio-keys input device, held down on silent and released on ring. While this + * helper follows a switch, $XDG_RUNTIME_DIR/omarchy-mute-switch holds its PID + * so omarchy-volume mute-key leaves the mute alone and external keyboards' + * Mute keys are toggled here instead. Without a switch it exits 0 at once. + * + * Build: cc -O2 -Wall -Wextra -std=c99 mute-switch.c -o omarchy-mute-switch + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define KEY_BYTES ((KEY_MAX / 8) + 1) +#define MAX_DEVICES 32 +#define SETTLE_MS 300 +#define RETRY_MS 2000 +#define MAX_RETRY_MS 60000 +#define KEYS_SCAN_MS 10000 +#define IDLE_WAIT_MS 5000 +#define CMD_TIMEOUT_MS 10000 + +static volatile sig_atomic_t g_running = 1; +static char g_last_err[512]; + +static void handle_signal(int sig) { + (void)sig; + g_running = 0; +} + +static void log_msg(const char *fmt, ...) { + va_list ap; + fputs("omarchy-mute-switch: ", stderr); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); + fflush(stderr); +} + +static int64_t monotonic_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + +static bool read_text(const char *path, char *buf, size_t size) { + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) + return false; + ssize_t n = read(fd, buf, size - 1); + close(fd); + if (n < 0) + return false; + buf[n] = '\0'; + while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r' || + buf[n - 1] == ' ' || buf[n - 1] == '\t')) { + buf[--n] = '\0'; + } + return true; +} + +/* + * Check whether a sysfs capabilities/key bitmap (space-separated hex words of + * kernel unsigned long width, most-significant word first) has bit `code`. + */ +static bool has_key_bit(const char *caps, unsigned int code) { + const unsigned int word_bits = (unsigned int)(sizeof(unsigned long) * 8); + unsigned long words[64]; + size_t nwords = 0; + + const char *p = caps; + while (*p && nwords < sizeof(words) / sizeof(words[0])) { + while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') + p++; + if (!*p) + break; + char *end = NULL; + errno = 0; + unsigned long val = strtoul(p, &end, 16); + if (end == p || errno != 0) + return false; + words[nwords++] = val; + p = end; + } + if (nwords == 0) + return false; + + size_t word_from_lsb = code / word_bits; + unsigned int bit = code % word_bits; + if (word_from_lsb >= nwords) + return false; + size_t idx = nwords - 1 - word_from_lsb; + return ((words[idx] >> bit) & 1UL) != 0; +} + +struct dev_entry { + int fd; + char path[128]; +}; + +static int cmp_event_name(const void *a, const void *b) { + const char *sa = *(const char *const *)a; + const char *sb = *(const char *const *)b; + size_t la = strlen(sa), lb = strlen(sb); + if (la != lb) + return (la < lb) ? -1 : 1; + return strcmp(sa, sb); +} + +static void scan_input_devices(const char *input_root, + char switches[][128], size_t *nswitches, + char keys[][128], size_t *nkeys) { + *nswitches = 0; + *nkeys = 0; + + DIR *dir = opendir(input_root); + if (!dir) + return; + + char *names[256]; + size_t nnames = 0; + struct dirent *ent; + while ((ent = readdir(dir)) != NULL && nnames < 256) { + if (strncmp(ent->d_name, "event", 5) == 0) { + names[nnames++] = strdup(ent->d_name); + } + } + closedir(dir); + + qsort(names, nnames, sizeof(names[0]), cmp_event_name); + + for (size_t i = 0; i < nnames; i++) { + char p_name[PATH_MAX], p_caps[PATH_MAX], p_phys[PATH_MAX]; + char name[256], caps[1024], phys[256]; + + snprintf(p_name, sizeof(p_name), "%s/%s/device/name", input_root, names[i]); + snprintf(p_caps, sizeof(p_caps), "%s/%s/device/capabilities/key", input_root, names[i]); + snprintf(p_phys, sizeof(p_phys), "%s/%s/device/phys", input_root, names[i]); + + if (read_text(p_name, name, sizeof(name)) && + read_text(p_caps, caps, sizeof(caps)) && + has_key_bit(caps, KEY_MUTE)) { + if (!read_text(p_phys, phys, sizeof(phys))) + phys[0] = '\0'; + bool is_sw = (strcmp(name, "gpio-keys") == 0) || + (strncmp(phys, "gpio-keys/", 10) == 0); + if (is_sw && *nswitches < MAX_DEVICES) { + snprintf(switches[*nswitches], 128, "/dev/input/%s", names[i]); + (*nswitches)++; + } else if (!is_sw && *nkeys < MAX_DEVICES) { + snprintf(keys[*nkeys], 128, "/dev/input/%s", names[i]); + (*nkeys)++; + } + } + free(names[i]); + } +} + +static bool is_key_down(int fd, bool *out_down) { + unsigned char bits[KEY_BYTES]; + memset(bits, 0, sizeof(bits)); + if (ioctl(fd, EVIOCGKEY(sizeof(bits)), bits) < 0) + return false; + *out_down = ((bits[KEY_MUTE / 8] >> (KEY_MUTE % 8)) & 1) != 0; + return true; +} + +static int run_cmd(char *const argv[], char *err_buf, size_t err_size) { + int errpipe[2] = {-1, -1}; + if (err_buf && err_size > 0) { + err_buf[0] = '\0'; + if (pipe(errpipe) < 0) { + errpipe[0] = errpipe[1] = -1; + } + } + + pid_t pid = fork(); + if (pid < 0) { + if (errpipe[0] >= 0) { close(errpipe[0]); close(errpipe[1]); } + return -1; + } + if (pid == 0) { + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + dup2(devnull, STDOUT_FILENO); + if (errpipe[1] < 0) + dup2(devnull, STDERR_FILENO); + if (devnull > STDERR_FILENO) + close(devnull); + } + if (errpipe[1] >= 0) { + dup2(errpipe[1], STDERR_FILENO); + close(errpipe[0]); + close(errpipe[1]); + } + execvp(argv[0], argv); + _exit(127); + } + + if (errpipe[1] >= 0) + close(errpipe[1]); + + size_t err_len = 0; + int64_t deadline = monotonic_ms() + CMD_TIMEOUT_MS; + int status = 0; + bool exited = false; + + if (errpipe[0] >= 0) { + int fl = fcntl(errpipe[0], F_GETFL, 0); + if (fl >= 0) + fcntl(errpipe[0], F_SETFL, fl | O_NONBLOCK); + } + + while (!exited) { + if (errpipe[0] >= 0) { + char tmp[256]; + ssize_t n; + while ((n = read(errpipe[0], tmp, sizeof(tmp))) > 0) { + if (err_len + 1 < err_size) { + size_t copy = (size_t)n; + if (err_len + copy >= err_size) + copy = err_size - 1 - err_len; + memcpy(err_buf + err_len, tmp, copy); + err_len += copy; + err_buf[err_len] = '\0'; + } + } + } + pid_t w = waitpid(pid, &status, WNOHANG); + if (w == pid) { + exited = true; + break; + } + if (w < 0 && errno != EINTR) + break; + if (monotonic_ms() >= deadline) { + kill(pid, SIGKILL); + waitpid(pid, &status, 0); + exited = true; + status = -1; + break; + } + struct timespec ts = {0, 20000000}; /* 20 ms */ + nanosleep(&ts, NULL); + } + + if (errpipe[0] >= 0) { + char tmp[256]; + ssize_t n; + while ((n = read(errpipe[0], tmp, sizeof(tmp))) > 0) { + if (err_len + 1 < err_size) { + size_t copy = (size_t)n; + if (err_len + copy >= err_size) + copy = err_size - 1 - err_len; + memcpy(err_buf + err_len, tmp, copy); + err_len += copy; + err_buf[err_len] = '\0'; + } + } + close(errpipe[0]); + while (err_len > 0 && (err_buf[err_len - 1] == '\n' || err_buf[err_len - 1] == '\r')) + err_buf[--err_len] = '\0'; + } + + if (!exited || status < 0) + return -1; + return WIFEXITED(status) ? WEXITSTATUS(status) : 1; +} + +static bool set_mute(bool muted, bool quiet) { + char *osd_argv[] = {"omarchy-volume", muted ? "mute-on" : "mute-off", NULL}; + char *plain_argv[] = {"wpctl", "set-mute", "@DEFAULT_AUDIO_SINK@", muted ? "1" : "0", NULL}; + char *const *tries[2]; + int ntries = 0; + + if (!quiet) + tries[ntries++] = osd_argv; + tries[ntries++] = plain_argv; + + char err[512] = ""; + char last_err[512] = ""; + for (int i = 0; i < ntries; i++) { + if (run_cmd(tries[i], err, sizeof(err)) == 0) { + g_last_err[0] = '\0'; + return true; + } + if (err[0]) { + snprintf(last_err, sizeof(last_err), "%s: %s", tries[i][0], err); + } + } + if (last_err[0] && strcmp(last_err, g_last_err) != 0) { + log_msg("%s", last_err); + snprintf(g_last_err, sizeof(g_last_err), "%s", last_err); + } + return false; +} + +static bool toggle_mute(void) { + char *osd_argv[] = {"omarchy-volume", "mute-toggle", NULL}; + char *plain_argv[] = {"wpctl", "set-mute", "@DEFAULT_AUDIO_SINK@", "toggle", NULL}; + char err[256] = ""; + if (run_cmd(osd_argv, err, sizeof(err)) == 0) + return true; + return run_cmd(plain_argv, err, sizeof(err)) == 0; +} + +static bool flag_paths(char *flag, size_t fsz, char *tmp, size_t tsz) { + const char *rt = getenv("XDG_RUNTIME_DIR"); + if (!rt || !*rt) + return false; + snprintf(flag, fsz, "%s/omarchy-mute-switch", rt); + snprintf(tmp, tsz, "%s/omarchy-mute-switch.new", rt); + return true; +} + +static void raise_flag(void) { + char flag[PATH_MAX], tmp[PATH_MAX]; + if (!flag_paths(flag, sizeof(flag), tmp, sizeof(tmp))) + return; + int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + if (fd < 0) + return; + char buf[32]; + int n = snprintf(buf, sizeof(buf), "%ld\n", (long)getpid()); + if (n > 0) { + ssize_t w = write(fd, buf, (size_t)n); + (void)w; + } + close(fd); + if (rename(tmp, flag) < 0) + unlink(tmp); +} + +static void lower_flag(void) { + char flag[PATH_MAX], tmp[PATH_MAX], buf[32]; + if (!flag_paths(flag, sizeof(flag), tmp, sizeof(tmp))) + return; + if (read_text(flag, buf, sizeof(buf))) { + char self[32]; + snprintf(self, sizeof(self), "%ld", (long)getpid()); + if (strcmp(buf, self) == 0) + unlink(flag); + } +} + +static bool compositor_alive(pid_t pid) { + if (pid <= 0) + return true; + if (kill(pid, 0) == 0) + return true; + return errno != ESRCH; +} + +static void close_list(struct dev_entry *list, size_t *count) { + for (size_t i = 0; i < *count; i++) + close(list[i].fd); + *count = 0; +} + +int main(void) { + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = handle_signal; + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + + const char *input_root = getenv("OMARCHY_INPUT_ROOT"); + if (!input_root || !*input_root) + input_root = "/sys/class/input"; + + const char *pid_env = getenv("LABWC_PID"); + pid_t compositor = (pid_env && *pid_env) ? (pid_t)strtol(pid_env, NULL, 10) : 0; + + struct dev_entry switches[MAX_DEVICES], keyboards[MAX_DEVICES]; + size_t nswitches = 0, nkeyboards = 0; + + bool found_once = false; + int applied = -1; /* -1 = none yet, 0 = ring, 1 = silent */ + int64_t due = -1; /* -1 = not scheduled */ + unsigned int failures = 0; + int64_t next_scan = 0, next_keys = 0; + + while (g_running && compositor_alive(compositor)) { + int64_t now = monotonic_ms(); + + if (nswitches == 0 && now >= next_scan) { + char sw_paths[MAX_DEVICES][128], kb_paths[MAX_DEVICES][128]; + size_t nsw = 0, nkb = 0; + scan_input_devices(input_root, sw_paths, &nsw, kb_paths, &nkb); + for (size_t i = 0; i < nsw && nswitches < MAX_DEVICES; i++) { + int fd = open(sw_paths[i], O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (fd >= 0) { + switches[nswitches].fd = fd; + memcpy(switches[nswitches].path, sw_paths[i], sizeof(switches[nswitches].path)); + nswitches++; + } else { + log_msg("%s: %s", sw_paths[i], strerror(errno)); + } + } + if (nswitches > 0) { + log_msg("following %s", switches[0].path); + found_once = true; + raise_flag(); + due = now; + } else if (!found_once) { + log_msg("no hardware mute switch"); + return 0; + } else { + next_scan = now + RETRY_MS; + } + } + + if (nswitches > 0 && now >= next_keys) { + char sw_paths[MAX_DEVICES][128], kb_paths[MAX_DEVICES][128]; + size_t nsw = 0, nkb = 0; + scan_input_devices(input_root, sw_paths, &nsw, kb_paths, &nkb); + for (size_t i = 0; i < nkb && nkeyboards < MAX_DEVICES; i++) { + bool known = false; + for (size_t j = 0; j < nkeyboards; j++) { + if (strcmp(keyboards[j].path, kb_paths[i]) == 0) { + known = true; + break; + } + } + if (!known) { + int fd = open(kb_paths[i], O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (fd >= 0) { + keyboards[nkeyboards].fd = fd; + memcpy(keyboards[nkeyboards].path, kb_paths[i], sizeof(keyboards[nkeyboards].path)); + log_msg("Mute key of %s", kb_paths[i]); + nkeyboards++; + } + } + } + next_keys = now + KEYS_SCAN_MS; + } + + int timeout = IDLE_WAIT_MS; + if (nswitches > 0 && due >= 0) { + int64_t rem = due - now; + if (rem < 0) rem = 0; + if (rem < timeout) timeout = (int)rem; + } + + if (nswitches == 0) { + struct timespec ts = {timeout / 1000, (timeout % 1000) * 1000000L}; + nanosleep(&ts, NULL); + continue; + } + + struct pollfd pfds[MAX_DEVICES * 2]; + size_t npfds = 0; + for (size_t i = 0; i < nswitches; i++) { + pfds[npfds].fd = switches[i].fd; + pfds[npfds].events = POLLIN; + pfds[npfds].revents = 0; + npfds++; + } + for (size_t i = 0; i < nkeyboards; i++) { + pfds[npfds].fd = keyboards[i].fd; + pfds[npfds].events = POLLIN; + pfds[npfds].revents = 0; + npfds++; + } + + int ready = poll(pfds, (nfds_t)npfds, timeout); + bool lost = false; + + if (ready > 0) { + for (size_t i = 0; i < nswitches; i++) { + if (!(pfds[i].revents & (POLLIN | POLLERR | POLLHUP))) + continue; + struct input_event evs[64]; + ssize_t n = read(switches[i].fd, evs, sizeof(evs)); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) + continue; + log_msg("%s: %s", switches[i].path, strerror(errno)); + lost = true; + break; + } + if (n == 0) { + lost = true; + break; + } + size_t count = (size_t)n / sizeof(evs[0]); + int64_t t = monotonic_ms(); + for (size_t k = 0; k < count; k++) { + if ((evs[k].type == EV_KEY && evs[k].code == KEY_MUTE && + (evs[k].value == 0 || evs[k].value == 1)) || + (evs[k].type == EV_SYN && evs[k].code == SYN_DROPPED)) { + due = t + SETTLE_MS; + failures = 0; + } + } + } + + for (size_t i = 0; i < nkeyboards; ) { + short rev = pfds[nswitches + i].revents; + if (!(rev & (POLLIN | POLLERR | POLLHUP))) { + i++; + continue; + } + struct input_event evs[64]; + ssize_t n = read(keyboards[i].fd, evs, sizeof(evs)); + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + i++; + continue; + } + if (n <= 0) { + log_msg("gone: %s", keyboards[i].path); + close(keyboards[i].fd); + keyboards[i] = keyboards[--nkeyboards]; + pfds[nswitches + i] = pfds[nswitches + nkeyboards]; + continue; + } + size_t count = (size_t)n / sizeof(evs[0]); + for (size_t k = 0; k < count; k++) { + if (evs[k].type == EV_KEY && evs[k].code == KEY_MUTE && evs[k].value == 1) + toggle_mute(); + } + i++; + } + } + + now = monotonic_ms(); + if (!lost && due >= 0 && now >= due) { + due = -1; + bool muted = false; + for (size_t i = 0; i < nswitches; i++) { + bool d = false; + if (!is_key_down(switches[i].fd, &d)) { + log_msg("reading the switch: %s", strerror(errno)); + lost = true; + break; + } + if (d) + muted = true; + } + if (!lost && (int)muted != applied) { + bool quiet = (applied < 0); + if (set_mute(muted, quiet)) { + applied = muted ? 1 : 0; + failures = 0; + log_msg("%s", muted ? "silent: muted" : "ring: unmuted"); + } else { + unsigned int shift = failures < 6 ? failures : 6; + int64_t delay = (int64_t)RETRY_MS << shift; + if (delay > MAX_RETRY_MS) + delay = MAX_RETRY_MS; + failures++; + due = now + delay; + } + } + } + + if (lost) { + close_list(switches, &nswitches); + lower_flag(); + next_scan = monotonic_ms() + RETRY_MS; + } + } + + close_list(switches, &nswitches); + close_list(keyboards, &nkeyboards); + lower_flag(); + return 0; +} diff --git a/desktop/install-tree b/desktop/install-tree index f3ac5a6e..5122ccbe 100755 --- a/desktop/install-tree +++ b/desktop/install-tree @@ -19,7 +19,7 @@ here=$(cd "$(dirname "$0")" && pwd) project=$(dirname "$here") shell=$here/shell config=$here/configuration omarchy=$root/usr/share/omarchy -for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/omarchy-powerd" "$upstream/themes" "$upstream/bin" \ +for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/omarchy-mute-switch" "$build/omarchy-powerd" "$upstream/themes" "$upstream/bin" \ "$upstream/themes/jade-horse/colors.toml" "$upstream/icons/papercraft" "$upstream/applications/foot.desktop" "$upstream/default/hypr/toggles/bar-glassy.lua" \ "$upstream/default/i18n/en/cli.json" "$upstream/install/helpers/as-root.sh" "$upstream/install/helpers/browser-policy.sh" \ "$upstream/default/chromium/policies/omarchy.json" "$upstream/default/firefox/policies.json" "$upstream/config/chromium-flags.conf" \ @@ -107,11 +107,13 @@ for set in "$omarchy"/icons/*/; do if [[ -f $set/btop.svg.tpl && ! -e $set/omactivity.svg.tpl ]]; then ln -s btop.svg.tpl "$set/omactivity.svg.tpl"; fi done -# The keyboard, the startup cursor helper, and the power daemon. +# The keyboard, the startup cursor helper, the power daemon and the hardware +# mute-switch helper. put "$build/wvkbd-mobintl" "$omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state" 755 put "$build/wtype" "$root/usr/libexec/omarchy-wtype" 755 put "$build/wtype.LICENSE" "$root/usr/share/licenses/omarchy-wtype/LICENSE" put "$build/omarchy-powerd" "$root/usr/libexec/omarchy-powerd" 755 +put "$build/omarchy-mute-switch" "$root/usr/libexec/omarchy-mute-switch" 755 # The Bluetooth helper's D-Bus library, from its wheel. (cd "$dbus_next" && find dbus_next -type f -name '*.py' | LC_ALL=C sort) | while read -r file; do @@ -171,7 +173,6 @@ $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/release/audit.py b/release/audit.py index 80345243..bda4c3b1 100644 --- a/release/audit.py +++ b/release/audit.py @@ -18,6 +18,7 @@ # The compiled helpers of the omarchy-a package, of the root's architecture. HELPERS = {'usr/libexec/omarchy-wtype': 'startup cursor helper', 'usr/libexec/omarchy-powerd': 'power, lock and sleep daemon', + 'usr/libexec/omarchy-mute-switch': 'mute switch helper', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state': 'on-screen keyboard'} def private_firmware(orchard=None): diff --git a/tests/package_tree.py b/tests/package_tree.py index 456e7e58..b2a7bd19 100644 --- a/tests/package_tree.py +++ b/tests/package_tree.py @@ -32,7 +32,7 @@ def inputs(base): """BUILD, OMARCHY and DBUS_NEXT for install-tree, under BASE.""" build, upstream, wheel = base / 'build', base / 'omarchy', base / 'wheel' build.mkdir() - for name in ('wvkbd-mobintl', 'wtype', 'omarchy-powerd'): + for name in ('wvkbd-mobintl', 'wtype', 'omarchy-powerd', 'omarchy-mute-switch'): (build / name).write_bytes(elf()) (build / 'wtype.LICENSE').write_text('MIT\n') (upstream / 'themes/jade-horse/backgrounds').mkdir(parents=True) diff --git a/tests/test_mute_switch.py b/tests/test_mute_switch.py index 5395ea27..43674219 100644 --- a/tests/test_mute_switch.py +++ b/tests/test_mute_switch.py @@ -1,220 +1,78 @@ -"""desktop/configuration/mute-switch: the output's mute follows the side switch, with no hardware access.""" -import importlib.machinery -import importlib.util +"""desktop/configuration/mute-switch.c: native C mute-switch helper tests.""" import os from pathlib import Path import shutil -import struct import subprocess +import sys 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, 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', '/dev/input/event11']) - 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']])) +SOURCE = PROJECT / 'desktop/configuration/mute-switch.c' + + +def fake_input_device(root: Path, event: str, name: str, key_caps: str, phys: str = '') -> None: + dev = root / event / 'device' + (dev / 'capabilities').mkdir(parents=True) + (dev / 'name').write_text(name + '\n', encoding='utf-8') + (dev / 'capabilities' / 'key').write_text(key_caps + '\n', encoding='utf-8') + if phys: + (dev / 'phys').write_text(phys + '\n', encoding='utf-8') + + +@unittest.skipUnless(shutil.which('cc'), 'C compiler needed to test mute-switch.c') +# mute-switch.c builds against Linux headers (linux/input.h), which a Mac +# lacks, so the binary is tested on Linux only. +@unittest.skipUnless(sys.platform.startswith('linux'), 'mute-switch.c needs Linux headers') +class MuteSwitchBinary(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._tmp = tempfile.TemporaryDirectory() + cls.binary = Path(cls._tmp.name) / 'omarchy-mute-switch' + subprocess.run( + ['cc', '-O2', '-Wall', '-Wextra', '-Werror', '-std=c99', str(SOURCE), '-o', str(cls.binary)], + check=True, + ) + + @classmethod + def tearDownClass(cls): + cls._tmp.cleanup() + + def test_without_a_switch_exits_zero_and_leaves_no_flag(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + inp = root / 'input' + rt = root / 'runtime' + inp.mkdir() + rt.mkdir() + # Keyboard with KEY_MUTE (bit 113) and gpio-keys without KEY_MUTE: neither is a switch. + fake_input_device(inp, 'event0', 'gpio-keys', '0 0 0 0', phys='gpio-keys/input0') + fake_input_device(inp, 'event1', 'USB Keyboard', '2000000000000 0', phys='usb-1/input0') + env = dict(os.environ, XDG_RUNTIME_DIR=str(rt), OMARCHY_INPUT_ROOT=str(inp), LABWC_PID='') + res = subprocess.run([str(self.binary)], env=env, capture_output=True, text=True, timeout=5) + self.assertEqual(res.returncode, 0, res.stderr) + self.assertIn('no hardware mute switch', res.stderr) + self.assertEqual(os.listdir(rt), []) + + def test_bitmap_detection_and_backoff_logic_in_source(self): + text = SOURCE.read_text(encoding='utf-8') + self.assertIn('sizeof(unsigned long) * 8', text) + self.assertIn('EVIOCGKEY', text) + self.assertIn('MAX_RETRY_MS', text) + self.assertIn('KEYS_SCAN_MS', text) + self.assertIn('IDLE_WAIT_MS', text) 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() + makefile = (PROJECT / 'Makefile').read_text(encoding='utf-8') + self.assertIn('$(BUILD)/omarchy-mute-switch', makefile) + install = (PROJECT / 'desktop/install-tree').read_text(encoding='utf-8') + self.assertIn('put "$build/omarchy-mute-switch" "$root/usr/libexec/omarchy-mute-switch" 755', install) + autostart = (PROJECT / 'desktop/shell/default/labwc/autostart').read_text(encoding='utf-8') 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() + rc = (PROJECT / 'desktop/shell/labwc-rc.xml').read_text(encoding='utf-8') block = rc[rc.index(''):] self.assertIn('command="omarchy-volume mute-key"', block[:block.index('')]) self.assertNotIn('mute-toggle', rc) @@ -223,21 +81,20 @@ def test_the_package_stages_it_and_the_session_starts_it(self): 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) + rc.write_text(text, encoding='utf-8') 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 + return rc.read_text(encoding='utf-8') if rc.exists() else None def test_the_shipped_binding_becomes_mute_key(self): - shipped = (PROJECT / 'desktop/shell/labwc-rc.xml').read_text() + shipped = (PROJECT / 'desktop/shell/labwc-rc.xml').read_text(encoding='utf-8') old = shipped.replace('omarchy-volume mute-key', 'omarchy-volume mute-toggle') self.assertNotEqual(old, shipped) migrated = self.migrate(old) diff --git a/tests/test_package.py b/tests/test_package.py index 1bd886be..b37e5e8e 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -377,6 +377,7 @@ def test_changed_files_links_modes_and_a_missing_install_step_fail(self): def test_the_compiled_helpers_are_of_the_roots_architecture(self): self.assertEqual(set(audit.HELPERS), {'usr/libexec/omarchy-wtype', 'usr/libexec/omarchy-powerd', + 'usr/libexec/omarchy-mute-switch', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state'}) from release.architecture import check_elf check_elf(elf('aarch64'), 'aarch64')