From 71674ba540a73661daf473ceb81624c887bef0c5 Mon Sep 17 00:00:00 2001 From: Tom Ballard Date: Wed, 2 Dec 2026 08:19:15 +0000 Subject: [PATCH] Port arch-ipad-rotate-output daemon to C99 Replaces the Python 3 desktop/configuration/rotate-output daemon with a zero-dependency C99 binary (desktop/configuration/rotate-output.c, ~40 KB ELF, ~0.5 MiB RSS). Preserves the exact debounced orientation state machine, accelerometer mount-matrix & turning-rate detector, wlr-randr output selection and speaker-transform publishing, monitor-sensor restart logic, and discovery exit behavior. Assisted-by: LLM --- CHANGELOG.md | 2 + Makefile | 6 +- desktop/configuration/rotate-output | 325 ------- desktop/configuration/rotate-output.c | 1254 +++++++++++++++++++++++++ desktop/install-tree | 6 +- release/audit.py | 3 +- tests/package_tree.py | 2 +- tests/test_package.py | 1 + tests/test_rotate_output.py | 133 ++- 9 files changed, 1383 insertions(+), 349 deletions(-) delete mode 100644 desktop/configuration/rotate-output create mode 100644 desktop/configuration/rotate-output.c diff --git a/CHANGELOG.md b/CHANGELOG.md index 19ead836..62ad2c58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ release is checked here and released on by hand. ### Desktop +- Screen rotation daemon (`arch-ipad-rotate-output`) is now a C binary instead + of Python, reducing resident memory on devices with an accelerometer. - iPhone X: the desktop starts at the size it has under iOS, instead of everything drawn at a third of it. diff --git a/Makefile b/Makefile index 02f07514..1bc13abd 100644 --- a/Makefile +++ b/Makefile @@ -14,7 +14,11 @@ CC ?= cc CFLAGS ?= -O2 PKG_CONFIG ?= pkg-config -all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype +all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/arch-ipad-rotate-output + +$(BUILD)/arch-ipad-rotate-output: desktop/configuration/rotate-output.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 $< $(LDFLAGS) -lm -o $@ $(BUILD)/wvkbd-mobintl: @test -d "$(WVKBD)" || { echo 'Set WVKBD to the wvkbd v0.20 source' >&2; exit 1; } diff --git a/desktop/configuration/rotate-output b/desktop/configuration/rotate-output deleted file mode 100644 index 284ca368..00000000 --- a/desktop/configuration/rotate-output +++ /dev/null @@ -1,325 +0,0 @@ -#!/usr/bin/python3 -"""Debounced iio-sensor-proxy rotation with a persistent user lock. - -Only a sustained orientation is applied. Repeated identical sensor messages do -not reset the deadline; undefined/flat readings cancel a pending transition. -A cooldown prevents rapid flips back. Unlock applies the latest stable reading. -A quick half turn becomes one 180 degree change instead of two of 90: a settled -reading waits a little longer while the tablet is still being turned, or while -gravity already points at another orientation than the one reported (the -sensor proxy reports the final orientation up to a second late). -""" -import collections -import glob -import json -import math -import os -from pathlib import Path -import selectors -import signal -import re -import subprocess -import time - -TRANSFORMS = {'normal': 'normal', 'bottom-up': '180', 'left-up': '90', 'right-up': '270'} -J120_SPEAKERS = Path('/sys/firmware/devicetree/base/sound-speaker-transport') - - -class Orientation: - def __init__(self, settle=0.4, cooldown=0.75, hold=0.6, lag=1.2): - self.settle = settle - self.cooldown = cooldown - self.hold = hold # longest extra wait while the tablet is still turning - self.lag = lag # longest extra wait for the report to catch up with gravity - self.pending = None - self.since = 0.0 - self.applied = None - self.last_apply = float('-inf') - - def observe(self, value, now): - value = value if value in TRANSFORMS else None - if value != self.pending: - self.pending, self.since = value, now - - def waiting(self): - return self.pending is not None and self.pending != self.applied - - def ready(self, now, locked=False, turning=False, facing=None): - if (locked or self.pending is None or self.pending == self.applied - or now - self.since < self.settle or now - self.last_apply < self.cooldown): - return None - if turning and now - self.since < self.settle + self.hold: - return None - if facing not in (None, self.pending) and now - self.since < self.settle + self.lag: - return None - return self.pending - - def committed(self, value, now): - self.applied, self.last_apply = value, now - - -class Turning: - """Whether the tablet is still being turned in the plane of its screen. - - From the accelerometer's raw gravity vector, read only while a change is - pending. Lying flat gives no usable angle and never delays a rotation. - """ - def __init__(self, directory, speed=40.0, window=0.25): - self.directory = directory - self.speed = speed # degrees per second - self.window = window - self.samples = collections.deque() - self.facing = None - self.disagreed = 0 - self.matrix = self.read_mount_matrix(directory) - - @staticmethod - def read_mount_matrix(directory): - candidates = [] - # Match iio-sensor-proxy's udev override before using kernel metadata. - try: - result = subprocess.run( - ['udevadm', 'info', '--query=property', '--path', str(Path(directory).resolve())], - stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, - timeout=1, check=True) - candidates.extend(line.split('=', 1)[1] for line in result.stdout.splitlines() - if line.startswith('ACCEL_MOUNT_MATRIX=')) - except (OSError, subprocess.SubprocessError): - pass - for name in ('mount_matrix', 'in_accel_mount_matrix', 'in_mount_matrix'): - try: - candidates.append(Path(directory, name).read_text()) - except OSError: - pass - for text in candidates: - try: - rows = [[float(cell) for cell in row.split(',')] for row in text.split(';')] - if len(rows) == 3 and all(len(row) == 3 and any(row) - and all(map(math.isfinite, row)) for row in rows): - return rows[:2] - except ValueError: - pass - return [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]] - - def read(self): - return [int(Path(self.directory, f'in_accel_{axis}_raw').read_text()) for axis in 'xyz'] - - def sample(self, now): - try: - x, y, z = self.read() - except (OSError, ValueError): - self.samples.clear() - return - length = math.sqrt(x * x + y * y + z * z) - if not length or math.hypot(x, y) < 0.25 * length: - self.forget() - return - # The orientation gravity points at now, as iio-sensor-proxy names it - # after the mount matrix, with no hysteresis and no delay. - across, along = (row[0] * x + row[1] * y + row[2] * z for row in self.matrix) - if abs(along) >= abs(across): - self.facing = 'normal' if along < 0 else 'bottom-up' - else: - self.facing = 'right-up' if across < 0 else 'left-up' - self.samples.append((now, math.degrees(math.atan2(y, x)))) - while now - self.samples[0][0] > self.window: - self.samples.popleft() - - def forget(self): - self.samples.clear() - self.facing = None - - def judged(self, applied): - """Stop comparing on a board where gravity and the reports never agree.""" - if self.facing is not None: - self.disagreed = 0 if self.facing == applied else self.disagreed + 1 - - def trusted_facing(self): - return self.facing if self.disagreed < 3 else None - - def turning(self): - if len(self.samples) < 2: - return False - (start, first), (end, last) = self.samples[0], self.samples[-1] - if end - start < 0.1: - return False - change = abs((last - first + 180) % 360 - 180) - return change / (end - start) > self.speed - - -def orientation(line): - # New monitor-sensor versions append a separate ', tilt: face-up' field. - # Only the orientation token belongs to the rotation state machine. - match = re.search(r'orientation(?: changed)?:\s*([a-z-]+)(?=[,\s)]|$)', line) - return match.group(1) if match else None - - -def trace(message): - if os.environ.get('ORCHARD_ROTATION_TRACE') == '1': - print(f'rotation trace t={time.monotonic():.3f} {message}', flush=True) - - -def internal_output(outputs): - return next((name for name in outputs if name.startswith(('eDP-', 'DSI-', 'LVDS-'))), - outputs[0] if len(outputs) == 1 else None) - - -def publish_speaker_transform(path, transform): - try: - staging = path.with_suffix('.new') - staging.write_text(transform + '\n') - staging.replace(path) - except OSError as error: - print(f'speaker transform update failed: {error}', flush=True) - - -def seed_speaker_transform(path): - # A locked rotation may never make a new request during this session. - try: - result = subprocess.check_output(['wlr-randr', '--json'], text=True, timeout=3) - transforms = {output['name']: output['transform'] for output in json.loads(result) - if output.get('enabled')} - transform = transforms.get(internal_output(list(transforms))) - if transform in TRANSFORMS.values(): - publish_speaker_transform(path, transform) - except (OSError, ValueError, subprocess.SubprocessError) as error: - print(f'speaker transform query failed: {error}', flush=True) - - -def apply(value, speaker_transform=None): - started = time.monotonic() - trace(f'output query start orientation={value}') - result = subprocess.run(['wlr-randr'], capture_output=True, text=True, timeout=3, check=True) - # Prefer the internal panel, never arbitrarily rotate an external monitor. - outputs = [line.split()[0] for line in result.stdout.splitlines() if line and not line[0].isspace()] - output = internal_output(outputs) - if output is None: - return False - queried = time.monotonic() - trace(f'output query done ms={(queried - started) * 1000:.0f}; request {TRANSFORMS[value]}') - subprocess.run(['wlr-randr', '--output', output, '--transform', TRANSFORMS[value]], - check=True, timeout=4) - trace(f'output request done ms={(time.monotonic() - queried) * 1000:.0f}') - if speaker_transform is not None: - publish_speaker_transform(speaker_transform, TRANSFORMS[value]) - print(f'rotation applied: {output} {value} -> {TRANSFORMS[value]}', flush=True) - return True - - -def main(): - lock = Path(os.environ.get('XDG_CONFIG_HOME', str(Path.home() / '.config'))) / 'omarchy/rotation-lock' - state = Orientation(float(os.environ.get('ROTATE_SETTLE', '.4')), - float(os.environ.get('ROTATE_COOLDOWN', '.75'))) - parent = int(os.environ.get('LABWC_PID', '0')) - runtime = os.environ.get('XDG_RUNTIME_DIR') - speaker_transform = None - if runtime and J120_SPEAKERS.is_dir(): - speaker_transform = Path(runtime) / 'omarchy-j120-speaker-transform' - seed_speaker_transform(speaker_transform) - sensors = glob.glob(os.environ.get('ROTATE_ACCEL', '/sys/bus/iio/devices/iio:device*') + '/in_accel_x_raw') - motion = Turning(os.path.dirname(sensors[0])) if sensors else None - discovery_timeout = float(os.environ.get('ROTATE_DISCOVERY_TIMEOUT', '15')) - started = time.monotonic() - saw_proxy = False - selector = selectors.DefaultSelector() - def start_monitor(): - process = subprocess.Popen(['monitor-sensor', '--accel'], stdout=subprocess.PIPE) - os.set_blocking(process.stdout.fileno(), False) - selector.register(process.stdout, selectors.EVENT_READ) - return process - def stop_monitor(process): - process.terminate() - try: - process.wait(timeout=2) - except subprocess.TimeoutExpired: - process.kill() - process.wait() - process.stdout.close() - monitor = start_monitor() - restart_at = None - running = True - def stop(*_): - nonlocal running - running = False - signal.signal(signal.SIGTERM, stop) - signal.signal(signal.SIGINT, stop) - buffered = b'' - eof = False - try: - while running: - if parent: - try: - os.kill(parent, 0) - except ProcessLookupError: - break - wait_s = 0.1 if (state.waiting() or eof) else 1.0 - for key, _ in selector.select(wait_s): - data = os.read(key.fd, 8192) - if not data: - eof = True - selector.unregister(key.fd) - continue - buffered += data - while b'\n' in buffered: - line, buffered = buffered.split(b'\n', 1) - decoded = line.decode(errors='replace') - if '=== No accelerometer' in decoded and not sensors: - print('rotation: no accelerometer; exiting', flush=True) - running = False - break - if '=== Has accelerometer' in decoded or 'iio-sensor-proxy appeared' in decoded: - saw_proxy = True - value = orientation(decoded) - if value is not None: - saw_proxy = True - trace(f'sensor orientation={value}') - state.observe(value, time.monotonic()) - now = time.monotonic() - if not running: - break - if not sensors and not saw_proxy and discovery_timeout > 0 and now - started >= discovery_timeout: - print('rotation: no accelerometer or iio-sensor-proxy after discovery window; exiting', flush=True) - break - if motion: - if state.waiting(): - motion.sample(now) - else: - motion.forget() - value = state.ready(now, lock.exists(), bool(motion and motion.turning()), - motion.trusted_facing() if motion else None) - if value is not None: - trace(f'stable orientation={value} waited_ms={(now - state.since) * 1000:.0f}') - try: - if apply(value, speaker_transform): - state.committed(value, now) - if motion: - motion.judged(value) - except (OSError, subprocess.SubprocessError) as error: - print(f'rotation failed: {error}', flush=True) - state.last_apply = now # bounded retry; never mark failure applied - if eof: - # No accelerated apply on EOF: wait out any pending stability window. - if not (lock.exists() or state.pending is None or state.pending == state.applied - or now - state.since > state.settle + state.cooldown + 5): - continue - if not parent: - break - # Inside a session the sensor reader may end (iio-sensor-proxy - # not up yet at login, or restarted). Rotation must not stay - # dead until the next login: start it again, at most every 2 s. - if restart_at is None: - print('rotation: monitor-sensor ended; restarting', flush=True) - restart_at = now + 2 - elif now >= restart_at: - stop_monitor(monitor) - monitor = start_monitor() - buffered, eof, restart_at = b'', False, None - else: - time.sleep(.1) - finally: - selector.close() - stop_monitor(monitor) - - -if __name__ == '__main__': - main() diff --git a/desktop/configuration/rotate-output.c b/desktop/configuration/rotate-output.c new file mode 100644 index 00000000..c08228b2 --- /dev/null +++ b/desktop/configuration/rotate-output.c @@ -0,0 +1,1254 @@ +/* Debounced iio-sensor-proxy rotation with a persistent user lock. + * + * Only a sustained orientation is applied. Repeated identical sensor messages do + * not reset the deadline; undefined/flat readings cancel a pending transition. + * A cooldown prevents rapid flips back. Unlock applies the latest stable reading. + * A quick half turn becomes one 180 degree change instead of two of 90: a settled + * reading waits a little longer while the tablet is still being turned, or while + * gravity already points at another orientation than the one reported (the + * sensor proxy reports the final orientation up to a second late). + */ + +#define _POSIX_C_SOURCE 200809L +#define _DEFAULT_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +#define J120_SPEAKERS "/sys/firmware/devicetree/base/sound-speaker-transport" + +static volatile sig_atomic_t g_running = 1; + +static void handle_signal(int sig) +{ + (void)sig; + g_running = 0; +} + +static double monotonic_now(void) +{ + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) + return 0.0; + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static void sleep_ms(int ms) +{ + struct timespec ts; + ts.tv_sec = ms / 1000; + ts.tv_nsec = (long)(ms % 1000) * 1000000L; + while (nanosleep(&ts, &ts) == -1 && errno == EINTR) + ; +} + +static bool trace_enabled(void) +{ + const char *v = getenv("ORCHARD_ROTATION_TRACE"); + return v && strcmp(v, "1") == 0; +} + +#define TRACE(fmt, ...) do { \ + if (trace_enabled()) { \ + printf("rotation trace t=%.3f " fmt "\n", monotonic_now(), ##__VA_ARGS__); \ + fflush(stdout); \ + } \ +} while (0) + +/* -------------------------------------------------------------------------- + * Orientations & transforms + * -------------------------------------------------------------------------- */ + +enum orient { + ORIENT_NONE = 0, + ORIENT_NORMAL, + ORIENT_BOTTOM_UP, + ORIENT_LEFT_UP, + ORIENT_RIGHT_UP, +}; + +static enum orient parse_known_orient(const char *s) +{ + if (!s) + return ORIENT_NONE; + if (strcmp(s, "normal") == 0) + return ORIENT_NORMAL; + if (strcmp(s, "bottom-up") == 0) + return ORIENT_BOTTOM_UP; + if (strcmp(s, "left-up") == 0) + return ORIENT_LEFT_UP; + if (strcmp(s, "right-up") == 0) + return ORIENT_RIGHT_UP; + return ORIENT_NONE; +} + +static const char *orient_name(enum orient o) +{ + switch (o) { + case ORIENT_NORMAL: return "normal"; + case ORIENT_BOTTOM_UP: return "bottom-up"; + case ORIENT_LEFT_UP: return "left-up"; + case ORIENT_RIGHT_UP: return "right-up"; + default: return NULL; + } +} + +static const char *orient_transform(enum orient o) +{ + switch (o) { + case ORIENT_NORMAL: return "normal"; + case ORIENT_BOTTOM_UP: return "180"; + case ORIENT_LEFT_UP: return "90"; + case ORIENT_RIGHT_UP: return "270"; + default: return NULL; + } +} + +static bool is_valid_transform(const char *t) +{ + return t && (strcmp(t, "normal") == 0 || strcmp(t, "180") == 0 || + strcmp(t, "90") == 0 || strcmp(t, "270") == 0); +} + +/* Match: orientation(?: changed)?:\s*([a-z-]+)(?=[,\s)]|$) */ +static bool extract_orientation_token(const char *line, char *out, size_t cap) +{ + const char *p = line; + while ((p = strstr(p, "orientation")) != NULL) { + const char *q = p + 11; + if (strncmp(q, " changed", 8) == 0) + q += 8; + if (*q != ':') { + p += 11; + continue; + } + q++; + while (*q && isspace((unsigned char)*q)) + q++; + const char *start = q; + while (*q && ((*q >= 'a' && *q <= 'z') || *q == '-')) + q++; + if (q > start && (*q == '\0' || *q == ',' || *q == ')' || + isspace((unsigned char)*q))) { + size_t len = (size_t)(q - start); + if (len >= cap) + len = cap - 1; + memcpy(out, start, len); + out[len] = '\0'; + return true; + } + p += 11; + } + return false; +} + +/* -------------------------------------------------------------------------- + * Orientation state machine + * -------------------------------------------------------------------------- */ + +struct orientation_state { + double settle; + double cooldown; + double hold; + double lag; + enum orient pending; + double since; + enum orient applied; + double last_apply; +}; + +static void orientation_init(struct orientation_state *s, + double settle, double cooldown, double hold, double lag) +{ + s->settle = settle; + s->cooldown = cooldown; + s->hold = hold; + s->lag = lag; + s->pending = ORIENT_NONE; + s->since = 0.0; + s->applied = ORIENT_NONE; + s->last_apply = -INFINITY; +} + +static void orientation_observe(struct orientation_state *s, enum orient value, double now) +{ + if (value != s->pending) { + s->pending = value; + s->since = now; + } +} + +static bool orientation_waiting(const struct orientation_state *s) +{ + return s->pending != ORIENT_NONE && s->pending != s->applied; +} + +static enum orient orientation_ready(const struct orientation_state *s, double now, + bool locked, bool turning, enum orient facing) +{ + if (locked || s->pending == ORIENT_NONE || s->pending == s->applied || + now - s->since < s->settle || now - s->last_apply < s->cooldown) + return ORIENT_NONE; + if (turning && now - s->since < s->settle + s->hold) + return ORIENT_NONE; + if (facing != ORIENT_NONE && facing != s->pending && + now - s->since < s->settle + s->lag) + return ORIENT_NONE; + return s->pending; +} + +static void orientation_committed(struct orientation_state *s, enum orient value, double now) +{ + s->applied = value; + s->last_apply = now; +} + +/* -------------------------------------------------------------------------- + * Subprocess helper with timeout + * -------------------------------------------------------------------------- */ + +static int run_cmd_capture(char *const argv[], double timeout_s, + char **out_buf, size_t *out_len) +{ + int pipefd[2] = { -1, -1 }; + if (out_buf && pipe(pipefd) < 0) + return -1; + + pid_t pid = fork(); + if (pid < 0) { + if (out_buf) { + close(pipefd[0]); + close(pipefd[1]); + } + return -1; + } + if (pid == 0) { + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + dup2(devnull, STDERR_FILENO); + if (!out_buf) + dup2(devnull, STDOUT_FILENO); + if (devnull > STDERR_FILENO) + close(devnull); + } + if (out_buf) { + close(pipefd[0]); + dup2(pipefd[1], STDOUT_FILENO); + if (pipefd[1] > STDERR_FILENO) + close(pipefd[1]); + } + execvp(argv[0], argv); + _exit(127); + } + + if (out_buf) + close(pipefd[1]); + + double deadline = monotonic_now() + timeout_s; + bool timed_out = false; + char *buf = NULL; + size_t cap = 0, len = 0; + + if (out_buf) { + int flags = fcntl(pipefd[0], F_GETFL, 0); + if (flags >= 0) + fcntl(pipefd[0], F_SETFL, flags | O_NONBLOCK); + cap = 8192; + buf = malloc(cap); + if (!buf) { + close(pipefd[0]); + kill(pid, SIGKILL); + waitpid(pid, NULL, 0); + return -1; + } + for (;;) { + double rem = deadline - monotonic_now(); + if (rem <= 0.0) { + timed_out = true; + break; + } + struct pollfd pfd = { .fd = pipefd[0], .events = POLLIN }; + int r = poll(&pfd, 1, (int)(rem * 1000.0) + 1); + if (r < 0) { + if (errno == EINTR) + continue; + break; + } + if (r == 0) { + timed_out = true; + break; + } + bool eof = false; + for (;;) { + if (len + 4096 > cap) { + if (cap >= 1024 * 1024) { + eof = true; + break; + } + cap *= 2; + char *nb = realloc(buf, cap); + if (!nb) { + eof = true; + break; + } + buf = nb; + } + ssize_t n = read(pipefd[0], buf + len, cap - 1 - len); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) + break; + if (errno == EINTR) + continue; + eof = true; + break; + } + if (n == 0) { + eof = true; + break; + } + len += (size_t)n; + } + if (eof) + break; + } + close(pipefd[0]); + buf[len] = '\0'; + } + + int status = 0; + if (timed_out) { + kill(pid, SIGKILL); + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) + ; + free(buf); + return -1; + } + + for (;;) { + pid_t w = waitpid(pid, &status, WNOHANG); + if (w == pid) + break; + if (w < 0) { + if (errno == EINTR) + continue; + free(buf); + return -1; + } + if (monotonic_now() >= deadline) { + kill(pid, SIGKILL); + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) + ; + free(buf); + return -1; + } + sleep_ms(10); + } + + if (out_buf) { + *out_buf = buf; + if (out_len) + *out_len = len; + } + return (WIFEXITED(status) && WEXITSTATUS(status) == 0) ? 0 : -1; +} + +/* -------------------------------------------------------------------------- + * Turning / accelerometer gravity detector + * -------------------------------------------------------------------------- */ + +#define MAX_SAMPLES 64 + +struct accel_sample { + double t; + double angle; +}; + +struct turning_state { + char directory[PATH_MAX]; + double speed; + double window; + struct accel_sample samples[MAX_SAMPLES]; + int sample_count; + enum orient facing; + int disagreed; + double matrix[2][3]; +}; + +static bool parse_mount_matrix_str(const char *text, double out[2][3]) +{ + double rows[3][3]; + const char *p = text; + for (int r = 0; r < 3; r++) { + bool any_nonzero = false; + for (int c = 0; c < 3; c++) { + while (*p && isspace((unsigned char)*p)) + p++; + char *end = NULL; + double v = strtod(p, &end); + if (end == p || !isfinite(v)) + return false; + rows[r][c] = v; + if (v != 0.0) + any_nonzero = true; + p = end; + while (*p && isspace((unsigned char)*p)) + p++; + if (c < 2) { + if (*p != ',') + return false; + p++; + } + } + if (!any_nonzero) + return false; + if (r < 2) { + if (*p != ';') + return false; + p++; + } + } + while (*p && isspace((unsigned char)*p)) + p++; + if (*p != '\0') + return false; + memcpy(out[0], rows[0], sizeof(rows[0])); + memcpy(out[1], rows[1], sizeof(rows[1])); + return true; +} + +static bool read_file_text(const char *path, char *buf, size_t cap) +{ + int fd = open(path, O_RDONLY); + if (fd < 0) + return false; + size_t total = 0; + while (total + 1 < cap) { + ssize_t n = read(fd, buf + total, cap - 1 - total); + if (n < 0) { + if (errno == EINTR) + continue; + close(fd); + return false; + } + if (n == 0) + break; + total += (size_t)n; + } + close(fd); + buf[total] = '\0'; + return true; +} + +static void turning_read_mount_matrix(const char *directory, double out[2][3]) +{ + /* Default identity */ + out[0][0] = 1.0; out[0][1] = 0.0; out[0][2] = 0.0; + out[1][0] = 0.0; out[1][1] = 1.0; out[1][2] = 0.0; + + char resolved[PATH_MAX]; + if (realpath(directory, resolved)) { + char *argv[] = { "udevadm", "info", "--query=property", "--path", resolved, NULL }; + char *buf = NULL; + if (run_cmd_capture(argv, 1.0, &buf, NULL) == 0 && buf) { + char *p = buf; + while (*p) { + char *nl = strchr(p, '\n'); + if (nl) + *nl = '\0'; + if (strncmp(p, "ACCEL_MOUNT_MATRIX=", 19) == 0) { + if (parse_mount_matrix_str(p + 19, out)) { + free(buf); + return; + } + } + if (!nl) + break; + p = nl + 1; + } + } + free(buf); + } + + static const char *const names[] = { + "mount_matrix", "in_accel_mount_matrix", "in_mount_matrix" + }; + for (size_t i = 0; i < 3; i++) { + char path[PATH_MAX]; + char buf[512]; + snprintf(path, sizeof(path), "%s/%s", directory, names[i]); + if (read_file_text(path, buf, sizeof(buf)) && + parse_mount_matrix_str(buf, out)) + return; + } +} + +static void turning_init(struct turning_state *t, const char *directory, + double speed, double window) +{ + memset(t, 0, sizeof(*t)); + snprintf(t->directory, sizeof(t->directory), "%s", directory ? directory : ""); + t->speed = speed; + t->window = window; + turning_read_mount_matrix(t->directory, t->matrix); +} + +static void turning_forget(struct turning_state *t) +{ + t->sample_count = 0; + t->facing = ORIENT_NONE; +} + +static void turning_sample_xyz(struct turning_state *t, double now, + double x, double y, double z) +{ + double length = sqrt(x * x + y * y + z * z); + if (length == 0.0 || hypot(x, y) < 0.25 * length) { + turning_forget(t); + return; + } + double across = t->matrix[0][0] * x + t->matrix[0][1] * y + t->matrix[0][2] * z; + double along = t->matrix[1][0] * x + t->matrix[1][1] * y + t->matrix[1][2] * z; + if (fabs(along) >= fabs(across)) + t->facing = (along < 0.0) ? ORIENT_NORMAL : ORIENT_BOTTOM_UP; + else + t->facing = (across < 0.0) ? ORIENT_RIGHT_UP : ORIENT_LEFT_UP; + + double angle = atan2(y, x) * (180.0 / M_PI); + if (t->sample_count == MAX_SAMPLES) { + memmove(&t->samples[0], &t->samples[1], + (MAX_SAMPLES - 1) * sizeof(t->samples[0])); + t->sample_count--; + } + t->samples[t->sample_count].t = now; + t->samples[t->sample_count].angle = angle; + t->sample_count++; + + int drop = 0; + while (drop < t->sample_count && now - t->samples[drop].t > t->window) + drop++; + if (drop > 0) { + t->sample_count -= drop; + memmove(&t->samples[0], &t->samples[drop], + (size_t)t->sample_count * sizeof(t->samples[0])); + } +} + +static bool read_accel_axis(const char *dir, char axis, double *out) +{ + char path[PATH_MAX]; + char buf[64]; + snprintf(path, sizeof(path), "%s/in_accel_%c_raw", dir, axis); + if (!read_file_text(path, buf, sizeof(buf))) + return false; + char *end = NULL; + errno = 0; + long v = strtol(buf, &end, 10); + if (errno != 0 || end == buf) + return false; + *out = (double)v; + return true; +} + +static void turning_sample(struct turning_state *t, double now) +{ + double x, y, z; + if (!read_accel_axis(t->directory, 'x', &x) || + !read_accel_axis(t->directory, 'y', &y) || + !read_accel_axis(t->directory, 'z', &z)) { + t->sample_count = 0; + return; + } + turning_sample_xyz(t, now, x, y, z); +} + +static void turning_judged(struct turning_state *t, enum orient applied) +{ + if (t->facing != ORIENT_NONE) + t->disagreed = (t->facing == applied) ? 0 : t->disagreed + 1; +} + +static enum orient turning_trusted_facing(const struct turning_state *t) +{ + return (t->disagreed < 3) ? t->facing : ORIENT_NONE; +} + +static bool turning_is_turning(const struct turning_state *t) +{ + if (t->sample_count < 2) + return false; + double dt = t->samples[t->sample_count - 1].t - t->samples[0].t; + if (dt < 0.1) + return false; + double diff = t->samples[t->sample_count - 1].angle - t->samples[0].angle + 180.0; + double wrapped = fmod(fmod(diff, 360.0) + 360.0, 360.0) - 180.0; + return fabs(wrapped) / dt > t->speed; +} + +/* -------------------------------------------------------------------------- + * Output selection, wlr-randr & speaker transform + * -------------------------------------------------------------------------- */ + +static const char *internal_output(char *const *outputs, int count) +{ + for (int i = 0; i < count; i++) { + if (strncmp(outputs[i], "eDP-", 4) == 0 || + strncmp(outputs[i], "DSI-", 4) == 0 || + strncmp(outputs[i], "LVDS-", 5) == 0) + return outputs[i]; + } + return count == 1 ? outputs[0] : NULL; +} + +static void publish_speaker_transform(const char *path, const char *transform) +{ + char staging[PATH_MAX]; + snprintf(staging, sizeof(staging), "%s.new", path); + int fd = open(staging, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) { + printf("speaker transform update failed: %s\n", strerror(errno)); + fflush(stdout); + return; + } + char line[32]; + int n = snprintf(line, sizeof(line), "%s\n", transform); + ssize_t written = write(fd, line, (size_t)n); + int close_rc = close(fd); + if (written != n || close_rc != 0 || rename(staging, path) != 0) { + printf("speaker transform update failed: %s\n", strerror(errno)); + fflush(stdout); + unlink(staging); + } +} + +/* Minimal JSON helpers for seed_speaker_transform (wlr-randr --json) */ +struct jcur { + const char *p; + const char *end; +}; + +static void j_ws(struct jcur *c) +{ + while (c->p < c->end && (*c->p == ' ' || *c->p == '\t' || *c->p == '\r' || *c->p == '\n')) + c->p++; +} + +static bool j_str(struct jcur *c, char *out, size_t cap) +{ + j_ws(c); + if (c->p >= c->end || *c->p != '"') + return false; + c->p++; + size_t len = 0; + while (c->p < c->end && *c->p != '"') { + char ch = *c->p++; + if (ch == '\\') { + if (c->p >= c->end) + return false; + ch = *c->p++; + if (ch == 'u') { + if (c->end - c->p < 4) + return false; + c->p += 4; + ch = '?'; + } + } + if (out && len + 1 < cap) + out[len++] = ch; + } + if (c->p >= c->end || *c->p != '"') + return false; + c->p++; + if (out && cap > 0) + out[len] = '\0'; + return true; +} + +static bool j_skip(struct jcur *c, int depth) +{ + if (depth > 32) + return false; + j_ws(c); + if (c->p >= c->end) + return false; + if (*c->p == '"') + return j_str(c, NULL, 0); + if (*c->p == '[') { + c->p++; + j_ws(c); + if (c->p < c->end && *c->p == ']') { c->p++; return true; } + for (;;) { + if (!j_skip(c, depth + 1)) return false; + j_ws(c); + if (c->p >= c->end) return false; + if (*c->p == ']') { c->p++; return true; } + if (*c->p != ',') return false; + c->p++; + } + } + if (*c->p == '{') { + c->p++; + j_ws(c); + if (c->p < c->end && *c->p == '}') { c->p++; return true; } + for (;;) { + if (!j_str(c, NULL, 0)) return false; + j_ws(c); + if (c->p >= c->end || *c->p != ':') return false; + c->p++; + if (!j_skip(c, depth + 1)) return false; + j_ws(c); + if (c->p >= c->end) return false; + if (*c->p == '}') { c->p++; return true; } + if (*c->p != ',') return false; + c->p++; + } + } + while (c->p < c->end && !isspace((unsigned char)*c->p) && + *c->p != ',' && *c->p != ']' && *c->p != '}') + c->p++; + return true; +} + +static void seed_speaker_transform(const char *path) +{ + char *argv[] = { "wlr-randr", "--json", NULL }; + char *buf = NULL; + size_t len = 0; + if (run_cmd_capture(argv, 3.0, &buf, &len) != 0 || !buf) { + printf("speaker transform query failed\n"); + fflush(stdout); + free(buf); + return; + } + + char names[16][64]; + char transforms[16][32]; + char *name_ptrs[16]; + int count = 0; + + struct jcur c = { buf, buf + len }; + j_ws(&c); + if (c.p < c.end && *c.p == '[') { + c.p++; + j_ws(&c); + while (c.p < c.end && *c.p == '{' && count < 16) { + c.p++; + char name[64] = ""; + char tf[32] = ""; + bool enabled = false; + j_ws(&c); + if (c.p < c.end && *c.p == '}') { + c.p++; + } else { + for (;;) { + char key[32]; + if (!j_str(&c, key, sizeof(key))) break; + j_ws(&c); + if (c.p >= c.end || *c.p != ':') break; + c.p++; + j_ws(&c); + if (strcmp(key, "name") == 0) { + j_str(&c, name, sizeof(name)); + } else if (strcmp(key, "transform") == 0) { + j_str(&c, tf, sizeof(tf)); + } else if (strcmp(key, "enabled") == 0) { + if (c.end - c.p >= 4 && memcmp(c.p, "true", 4) == 0) { + enabled = true; + c.p += 4; + } else { + j_skip(&c, 1); + } + } else { + if (!j_skip(&c, 1)) break; + } + j_ws(&c); + if (c.p >= c.end) break; + if (*c.p == '}') { c.p++; break; } + if (*c.p != ',') break; + c.p++; + } + } + if (enabled && name[0]) { + memcpy(names[count], name, sizeof(names[count])); + memcpy(transforms[count], tf, sizeof(transforms[count])); + name_ptrs[count] = names[count]; + count++; + } + j_ws(&c); + if (c.p < c.end && *c.p == ',') { + c.p++; + j_ws(&c); + } else { + break; + } + } + } + + const char *chosen = internal_output(name_ptrs, count); + if (chosen) { + for (int i = 0; i < count; i++) { + if (name_ptrs[i] == chosen && is_valid_transform(transforms[i])) { + publish_speaker_transform(path, transforms[i]); + break; + } + } + } + free(buf); +} + +/* Returns: 1 applied, 0 no eligible output, -1 error */ +static int apply_orientation(enum orient value, const char *speaker_transform) +{ + const char *name = orient_name(value); + const char *tf = orient_transform(value); + if (!name || !tf) + return 0; + + double started = monotonic_now(); + TRACE("output query start orientation=%s", name); + + char *qargv[] = { "wlr-randr", NULL }; + char *buf = NULL; + if (run_cmd_capture(qargv, 3.0, &buf, NULL) != 0 || !buf) { + free(buf); + return -1; + } + + char outputs[16][64]; + char *ptrs[16]; + int count = 0; + char *p = buf; + while (*p && count < 16) { + char *nl = strchr(p, '\n'); + if (nl) + *nl = '\0'; + if (*p && !isspace((unsigned char)*p)) { + size_t len = 0; + while (p[len] && !isspace((unsigned char)p[len]) && len + 1 < sizeof(outputs[0])) + len++; + memcpy(outputs[count], p, len); + outputs[count][len] = '\0'; + ptrs[count] = outputs[count]; + count++; + } + if (!nl) + break; + p = nl + 1; + } + free(buf); + + const char *output = internal_output(ptrs, count); + if (!output) + return 0; + + double queried = monotonic_now(); + TRACE("output query done ms=%.0f; request %s", (queried - started) * 1000.0, tf); + + char *sargv[] = { "wlr-randr", "--output", (char *)output, "--transform", (char *)tf, NULL }; + if (run_cmd_capture(sargv, 4.0, NULL, NULL) != 0) + return -1; + + TRACE("output request done ms=%.0f", (monotonic_now() - queried) * 1000.0); + if (speaker_transform) + publish_speaker_transform(speaker_transform, tf); + printf("rotation applied: %s %s -> %s\n", output, name, tf); + fflush(stdout); + return 1; +} + +/* -------------------------------------------------------------------------- + * monitor-sensor lifecycle + * -------------------------------------------------------------------------- */ + +struct monitor_proc { + pid_t pid; + int fd; +}; + +static bool start_monitor(struct monitor_proc *m) +{ + m->pid = -1; + m->fd = -1; + int pipefd[2]; + if (pipe(pipefd) < 0) + return false; + + pid_t pid = fork(); + if (pid < 0) { + close(pipefd[0]); + close(pipefd[1]); + return false; + } + if (pid == 0) { + close(pipefd[0]); + dup2(pipefd[1], STDOUT_FILENO); + if (pipefd[1] > STDERR_FILENO) + close(pipefd[1]); + execlp("monitor-sensor", "monitor-sensor", "--accel", (char *)NULL); + _exit(127); + } + + close(pipefd[1]); + int flags = fcntl(pipefd[0], F_GETFL, 0); + if (flags >= 0) + fcntl(pipefd[0], F_SETFL, flags | O_NONBLOCK); + m->pid = pid; + m->fd = pipefd[0]; + return true; +} + +static void stop_monitor(struct monitor_proc *m) +{ + if (m->pid > 0) { + kill(m->pid, SIGTERM); + double deadline = monotonic_now() + 2.0; + int status = 0; + for (;;) { + pid_t w = waitpid(m->pid, &status, WNOHANG); + if (w == m->pid || (w < 0 && errno != EINTR)) + break; + if (monotonic_now() >= deadline) { + kill(m->pid, SIGKILL); + while (waitpid(m->pid, &status, 0) < 0 && errno == EINTR) + ; + break; + } + sleep_ms(10); + } + m->pid = -1; + } + if (m->fd >= 0) { + close(m->fd); + m->fd = -1; + } +} + +/* -------------------------------------------------------------------------- + * Unit-test harness (--test) + * -------------------------------------------------------------------------- */ + +static int run_test_mode(void) +{ + struct orientation_state ostate; + orientation_init(&ostate, 0.4, 0.75, 0.6, 1.2); + struct turning_state tstate; + turning_init(&tstate, "/nonexistent", 40.0, 0.25); + + char line[1024]; + while (fgets(line, sizeof(line), stdin)) { + size_t len = strlen(line); + while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) + line[--len] = '\0'; + + if (strncmp(line, "parse ", 6) == 0) { + char tok[64]; + if (extract_orientation_token(line + 6, tok, sizeof(tok))) + printf("VAL %s\n", tok); + else + printf("NONE\n"); + } else if (strncmp(line, "orient_init ", 12) == 0) { + double settle = 0.4, cooldown = 0.75, hold = 0.6, lag = 1.2; + sscanf(line + 12, "%lf %lf %lf %lf", &settle, &cooldown, &hold, &lag); + orientation_init(&ostate, settle, cooldown, hold, lag); + printf("OK\n"); + } else if (strncmp(line, "observe ", 8) == 0) { + char val[32]; + double now = 0.0; + if (sscanf(line + 8, "%31s %lf", val, &now) == 2) + orientation_observe(&ostate, parse_known_orient(val), now); + printf("OK\n"); + } else if (strncmp(line, "committed ", 10) == 0) { + char val[32]; + double now = 0.0; + if (sscanf(line + 10, "%31s %lf", val, &now) == 2) + orientation_committed(&ostate, parse_known_orient(val), now); + printf("OK\n"); + } else if (strncmp(line, "ready ", 6) == 0) { + double now = 0.0; + int locked = 0, turning = 0; + char facing_s[32] = "none"; + sscanf(line + 6, "%lf %d %d %31s", &now, &locked, &turning, facing_s); + enum orient facing = strcmp(facing_s, "none") == 0 + ? ORIENT_NONE : parse_known_orient(facing_s); + enum orient r = orientation_ready(&ostate, now, locked != 0, + turning != 0, facing); + const char *rn = orient_name(r); + if (rn) + printf("VAL %s\n", rn); + else + printf("NONE\n"); + } else if (strcmp(line, "turning_reset") == 0) { + turning_init(&tstate, "/nonexistent", 40.0, 0.25); + printf("OK\n"); + } else if (strncmp(line, "turning_matrix ", 15) == 0) { + double m[2][3]; + if (sscanf(line + 15, "%lf %lf %lf %lf %lf %lf", + &m[0][0], &m[0][1], &m[0][2], + &m[1][0], &m[1][1], &m[1][2]) == 6) + memcpy(tstate.matrix, m, sizeof(m)); + printf("OK\n"); + } else if (strncmp(line, "turning_sample ", 15) == 0) { + double now, x, y, z; + if (sscanf(line + 15, "%lf %lf %lf %lf", &now, &x, &y, &z) == 4) + turning_sample_xyz(&tstate, now, x, y, z); + printf("OK\n"); + } else if (strncmp(line, "turning_judged ", 15) == 0) { + turning_judged(&tstate, parse_known_orient(line + 15)); + printf("OK\n"); + } else if (strcmp(line, "turning_facing") == 0) { + const char *fn = orient_name(turning_trusted_facing(&tstate)); + if (fn) + printf("VAL %s\n", fn); + else + printf("NONE\n"); + } else if (strcmp(line, "turning_is") == 0) { + printf("VAL %d\n", turning_is_turning(&tstate) ? 1 : 0); + } else { + printf("ERR\n"); + } + fflush(stdout); + } + return 0; +} + +/* -------------------------------------------------------------------------- + * Main daemon loop + * -------------------------------------------------------------------------- */ + +static double env_double(const char *name, double def) +{ + const char *v = getenv(name); + if (!v || !*v) + return def; + char *end = NULL; + double parsed = strtod(v, &end); + return (end != v && isfinite(parsed)) ? parsed : def; +} + +int main(int argc, char **argv) +{ + if (argc > 1 && strcmp(argv[1], "--test") == 0) + return run_test_mode(); + + char lock_path[PATH_MAX]; + const char *xdg_config = getenv("XDG_CONFIG_HOME"); + if (xdg_config && *xdg_config) { + snprintf(lock_path, sizeof(lock_path), "%s/omarchy/rotation-lock", xdg_config); + } else { + const char *home = getenv("HOME"); + snprintf(lock_path, sizeof(lock_path), "%s/.config/omarchy/rotation-lock", + home ? home : ""); + } + + struct orientation_state state; + orientation_init(&state, + env_double("ROTATE_SETTLE", 0.4), + env_double("ROTATE_COOLDOWN", 0.75), + 0.6, 1.2); + + const char *parent_env = getenv("LABWC_PID"); + pid_t parent = parent_env ? (pid_t)strtol(parent_env, NULL, 10) : 0; + + char speaker_path[PATH_MAX]; + const char *speaker_transform = NULL; + const char *runtime = getenv("XDG_RUNTIME_DIR"); + struct stat st; + if (runtime && *runtime && stat(J120_SPEAKERS, &st) == 0 && S_ISDIR(st.st_mode)) { + snprintf(speaker_path, sizeof(speaker_path), + "%s/omarchy-j120-speaker-transform", runtime); + speaker_transform = speaker_path; + seed_speaker_transform(speaker_transform); + } + + const char *accel_glob = getenv("ROTATE_ACCEL"); + if (!accel_glob) + accel_glob = "/sys/bus/iio/devices/iio:device*"; + char pattern[PATH_MAX]; + snprintf(pattern, sizeof(pattern), "%s/in_accel_x_raw", accel_glob); + + bool has_sensors = false; + struct turning_state motion_storage; + struct turning_state *motion = NULL; + glob_t g; + if (glob(pattern, 0, NULL, &g) == 0 && g.gl_pathc > 0) { + has_sensors = true; + char dir[PATH_MAX]; + snprintf(dir, sizeof(dir), "%s", g.gl_pathv[0]); + char *slash = strrchr(dir, '/'); + if (slash) + *slash = '\0'; + turning_init(&motion_storage, dir, 40.0, 0.25); + motion = &motion_storage; + } + globfree(&g); + + double discovery_timeout = env_double("ROTATE_DISCOVERY_TIMEOUT", 15.0); + double started = monotonic_now(); + bool saw_proxy = false; + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = handle_signal; + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + + struct monitor_proc monitor; + if (!start_monitor(&monitor)) { + perror("start_monitor"); + return 1; + } + + bool has_restart_at = false; + double restart_at = 0.0; + char pending[8192]; + size_t pending_len = 0; + bool discard_line = false; + bool eof = false; + + while (g_running) { + if (parent > 0) { + if (kill(parent, 0) < 0 && errno == ESRCH) + break; + } + + int wait_ms = (orientation_waiting(&state) || eof) ? 100 : 1000; + if (!eof && monitor.fd >= 0) { + struct pollfd pfd = { .fd = monitor.fd, .events = POLLIN }; + int r = poll(&pfd, 1, wait_ms); + if (r > 0 && (pfd.revents & (POLLIN | POLLHUP | POLLERR))) { + for (;;) { + char chunk[8192]; + ssize_t n = read(monitor.fd, chunk, sizeof(chunk)); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) + break; + if (errno == EINTR) + continue; + eof = true; + break; + } + if (n == 0) { + eof = true; + break; + } + for (ssize_t i = 0; i < n && g_running; i++) { + char c = chunk[i]; + if (c == '\n') { + if (!discard_line) { + pending[pending_len] = '\0'; + if (strstr(pending, "=== No accelerometer") && !has_sensors) { + printf("rotation: no accelerometer; exiting\n"); + fflush(stdout); + g_running = 0; + break; + } + if (strstr(pending, "=== Has accelerometer") || + strstr(pending, "iio-sensor-proxy appeared")) + saw_proxy = true; + char tok[64]; + if (extract_orientation_token(pending, tok, sizeof(tok))) { + saw_proxy = true; + TRACE("sensor orientation=%s", tok); + orientation_observe(&state, parse_known_orient(tok), + monotonic_now()); + } + } + pending_len = 0; + discard_line = false; + } else if (!discard_line) { + if (pending_len + 1 < sizeof(pending)) + pending[pending_len++] = c; + else + discard_line = true; + } + } + } + } + } else { + sleep_ms(wait_ms); + } + + double now = monotonic_now(); + if (!g_running) + break; + + if (!has_sensors && !saw_proxy && discovery_timeout > 0.0 && + now - started >= discovery_timeout) { + printf("rotation: no accelerometer or iio-sensor-proxy after discovery window; exiting\n"); + fflush(stdout); + break; + } + + if (motion) { + if (orientation_waiting(&state)) + turning_sample(motion, now); + else + turning_forget(motion); + } + + bool locked = (access(lock_path, F_OK) == 0); + enum orient ready = orientation_ready( + &state, now, locked, + motion && turning_is_turning(motion), + motion ? turning_trusted_facing(motion) : ORIENT_NONE); + + if (ready != ORIENT_NONE) { + TRACE("stable orientation=%s waited_ms=%.0f", + orient_name(ready), (now - state.since) * 1000.0); + int rc = apply_orientation(ready, speaker_transform); + if (rc == 1) { + orientation_committed(&state, ready, now); + if (motion) + turning_judged(motion, ready); + } else if (rc < 0) { + printf("rotation failed\n"); + fflush(stdout); + state.last_apply = now; + } + } + + if (eof) { + if (!(locked || state.pending == ORIENT_NONE || state.pending == state.applied || + now - state.since > state.settle + state.cooldown + 5.0)) + continue; + if (!parent) + break; + if (!has_restart_at) { + printf("rotation: monitor-sensor ended; restarting\n"); + fflush(stdout); + has_restart_at = true; + restart_at = now + 2.0; + } else if (now >= restart_at) { + stop_monitor(&monitor); + if (!start_monitor(&monitor)) + break; + pending_len = 0; + discard_line = false; + eof = false; + has_restart_at = false; + } + } + } + + stop_monitor(&monitor); + return 0; +} diff --git a/desktop/install-tree b/desktop/install-tree index ed917a7f..43a63cf4 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" "$upstream/themes" "$upstream/bin" \ +for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/arch-ipad-rotate-output" "$upstream/themes" "$upstream/bin" \ "$upstream/themes/jade-horse/colors.toml" "$upstream/icons/papercraft" "$upstream/applications/foot.desktop" "$upstream/default/hypr/toggles/bar-glassy.lua" "$dbus_next/dbus_next/__init__.py"; do [[ -e $input ]] || { echo "Missing input: $input" >&2; exit 1; } done @@ -76,10 +76,11 @@ 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 and the startup cursor helper. +# The keyboard, the startup cursor helper, and the rotation daemon. 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/arch-ipad-rotate-output" "$root/usr/libexec/arch-ipad-rotate-output" 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 @@ -138,7 +139,6 @@ $shell/applications/org.omarchy.settings.svg usr/share/icons/hicolor/scalable/ap $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 diff --git a/release/audit.py b/release/audit.py index cd218a00..b98b1ade 100644 --- a/release/audit.py +++ b/release/audit.py @@ -15,8 +15,9 @@ from .public_root import sha -# The two compiled helpers of the omarchy-a package, of the root's architecture. +# The compiled helpers of the omarchy-a package, of the root's architecture. HELPERS = {'usr/libexec/omarchy-wtype': 'startup cursor helper', + 'usr/libexec/arch-ipad-rotate-output': 'screen rotation daemon', '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 4e715a84..de67ee18 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'): + for name in ('wvkbd-mobintl', 'wtype', 'arch-ipad-rotate-output'): (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_package.py b/tests/test_package.py index 237b676a..98a9c665 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -354,6 +354,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/arch-ipad-rotate-output', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state'}) from release.architecture import check_elf check_elf(elf('aarch64'), 'aarch64') diff --git a/tests/test_rotate_output.py b/tests/test_rotate_output.py index ddb74428..fd34b7f4 100644 --- a/tests/test_rotate_output.py +++ b/tests/test_rotate_output.py @@ -1,7 +1,7 @@ -"""desktop/configuration/rotate-output: iio-sensor-proxy orientations to output transforms.""" +"""desktop/configuration/rotate-output.c: iio-sensor-proxy orientations to output transforms.""" +import atexit +import functools import os -import sys -import runpy from pathlib import Path import shutil import subprocess @@ -9,7 +9,24 @@ import threading import unittest -SCRIPT = Path(__file__).resolve().parents[1] / 'desktop/configuration/rotate-output' +SOURCE = Path(__file__).resolve().parents[1] / 'desktop/configuration/rotate-output.c' + + +@functools.lru_cache(maxsize=1) +def compiled_binary(): + tmp = Path(tempfile.mkdtemp(prefix='omarchy-rotate-output-test-')) + atexit.register(shutil.rmtree, tmp, True) + binary = tmp / 'arch-ipad-rotate-output' + cc = os.environ.get('CC', 'cc') + subprocess.run( + [cc, '-O2', '-Wall', '-Wextra', '-Werror', '-std=c99', str(SOURCE), '-lm', '-o', str(binary)], + check=True, + ) + return binary + + +def setUpModule(): + compiled_binary() RANDR = '''#!/bin/sh if [ "$#" -eq 0 ]; then @@ -55,7 +72,7 @@ def run_script(self, events, locked=False, extra_env=None, timeout=20): 'XDG_CONFIG_HOME': str(config), 'RANDR_LOG': str(log), 'ROTATE_SETTLE': '0.1', 'ROTATE_COOLDOWN': '0', **(extra_env or {})} - subprocess.run([sys.executable, str(SCRIPT)], env=env, check=True, timeout=timeout) + subprocess.run([str(compiled_binary())], env=env, check=True, timeout=timeout) return log.read_text().splitlines() if log.exists() else [] def test_held_orientations_become_transforms_of_the_panel(self): @@ -152,16 +169,100 @@ def test_sensor_reader_ending_inside_a_session_is_restarted(self): self.assertEqual(lines, ['--output Unknown-1 --transform 90']) +class TestHarness: + def __init__(self): + self._proc = subprocess.Popen( + [str(compiled_binary()), '--test'], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + + def ask(self, cmd): + self._proc.stdin.write(cmd + '\n') + self._proc.stdin.flush() + reply = self._proc.stdout.readline() + if not reply: + raise AssertionError('rotate-output --test exited unexpectedly') + reply = reply.rstrip('\n') + if reply == 'NONE': + return None + if reply.startswith('VAL '): + return reply[4:] + if reply == 'OK': + return True + raise AssertionError(f'Unexpected reply: {reply!r}') + + def close(self): + if self._proc.stdin and not self._proc.stdin.closed: + self._proc.stdin.close() + if self._proc.stdout and not self._proc.stdout.closed: + self._proc.stdout.close() + self._proc.wait(timeout=5) + + +class COrientation: + def __init__(self, harness, settle=0.4, cooldown=0.75, hold=0.6, lag=1.2): + self._h = harness + self._h.ask(f'orient_init {settle} {cooldown} {hold} {lag}') + + def observe(self, value, now): + self._h.ask(f'observe {value} {now}') + + def committed(self, value, now): + self._h.ask(f'committed {value} {now}') + + def ready(self, now, locked=False, turning=False, facing=None): + return self._h.ask( + f'ready {now} {1 if locked else 0} {1 if turning else 0} {facing or "none"}' + ) + + +class CTurning: + def __init__(self, harness): + self._h = harness + self._h.ask('turning_reset') + self.read = None + + @property + def matrix(self): + raise NotImplementedError + + @matrix.setter + def matrix(self, rows): + flat = [v for row in rows for v in row] + self._h.ask('turning_matrix ' + ' '.join(str(v) for v in flat)) + + def sample(self, now): + x, y, z = self.read() + self._h.ask(f'turning_sample {now} {x} {y} {z}') + + def judged(self, applied): + self._h.ask(f'turning_judged {applied}') + + def trusted_facing(self): + return self._h.ask('turning_facing') + + def turning(self): + return self._h.ask('turning_is') == '1' + + class RotationPolicy(unittest.TestCase): + def setUp(self): + self.harness = TestHarness() + + def tearDown(self): + self.harness.close() + def test_monitor_sensor_tilt_suffix_is_not_part_of_orientation(self): - parse = runpy.run_path(str(SCRIPT))['orientation'] + parse = lambda line: self.harness.ask('parse ' + line) self.assertEqual(parse('=== Has accelerometer (orientation: normal, tilt: face-up)'), 'normal') self.assertEqual(parse('Accelerometer orientation changed: left-up, tilt: upright'), 'left-up') self.assertEqual(parse('Accelerometer orientation changed: undefined'), 'undefined') self.assertIsNone(parse('Accelerometer tilt changed: face-up')) - def policy(self): - return runpy.run_path(str(SCRIPT))['Orientation']() + def policy(self, **kwargs): + return COrientation(self.harness, **kwargs) def test_repeated_messages_do_not_restart_stability_window(self): p = self.policy() @@ -187,8 +288,7 @@ def test_undefined_cancels_and_unlock_uses_current_reading(self): self.assertEqual(p.ready(6, locked=False), 'right-up') def test_still_turning_holds_a_settled_reading_for_a_bounded_time(self): - module = type("M", (), runpy.run_path(str(SCRIPT))) - state = module.Orientation(settle=0.4, cooldown=0, hold=0.6) + state = self.policy(settle=0.4, cooldown=0, hold=0.6) state.observe('left-up', 0.0) self.assertEqual(state.ready(0.45, turning=False), 'left-up') self.assertIsNone(state.ready(0.45, turning=True)) @@ -201,8 +301,7 @@ def test_still_turning_holds_a_settled_reading_for_a_bounded_time(self): def test_report_lagging_behind_gravity_is_waited_for(self): # J71b, 2026-11-10: half turn over the side, gravity at the final # orientation at 0.3 s, the proxy still said right-up until 0.9 s later. - module = type("M", (), runpy.run_path(str(SCRIPT))) - state = module.Orientation(settle=0.4, cooldown=0, hold=0.6, lag=1.2) + state = self.policy(settle=0.4, cooldown=0, hold=0.6, lag=1.2) state.observe('right-up', 0.0) self.assertIsNone(state.ready(0.5, facing='normal')) self.assertEqual(state.ready(0.5, facing='right-up'), 'right-up') @@ -212,8 +311,7 @@ def test_report_lagging_behind_gravity_is_waited_for(self): self.assertEqual(state.ready(1.65, facing='normal'), 'normal') def test_facing_follows_the_mount_matrix_and_gives_up_when_never_agreeing(self): - module = type("M", (), runpy.run_path(str(SCRIPT))) - motion = module.Turning('/nonexistent') + motion = CTurning(self.harness) motion.matrix = [[-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]] # J71b for raw, name in (((2000, 65000, 3000), 'normal'), ((1000, -66000, 600), 'bottom-up'), ((57000, -2000, 9000), 'right-up'), ((-60000, 900, 9000), 'left-up')): @@ -225,19 +323,18 @@ def test_facing_follows_the_mount_matrix_and_gives_up_when_never_agreeing(self): self.assertIsNone(motion.trusted_facing()) def test_turning_is_read_from_the_gravity_angle(self): - module = type("M", (), runpy.run_path(str(SCRIPT))) - motion = module.Turning('/nonexistent') + motion = CTurning(self.harness) readings = iter([(65000, 0, 3000), (60000, 25000, 3000), (46000, 46000, 3000)]) motion.read = lambda: next(readings) for now in (0.0, 0.1, 0.2): motion.sample(now) self.assertTrue(motion.turning()) - still = module.Turning('/nonexistent') + still = CTurning(self.harness) still.read = lambda: (65000, 200, 3000) for now in (0.0, 0.1, 0.2): still.sample(now) self.assertFalse(still.turning()) - flat = module.Turning('/nonexistent') + flat = CTurning(self.harness) flat.read = lambda: (5000, 1300, 65900) for now in (0.0, 0.1, 0.2): flat.sample(now)