diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a1c33c4..f6855bed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,9 @@ release is checked here and released on by hand. - Screen rotation follows the device with less memory in use: the rotation daemon is a small C program instead of Python (tcballard). +- Automatic brightness uses less memory: its daemon is a small C program + instead of Python (tcballard). + - Upstream's commands show their texts instead of raw keys like `webapp.intro`, in every language upstream has, and Install > Browser gets past its browser policy step (jannyg). diff --git a/Makefile b/Makefile index 3f37f186..9d655955 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,8 @@ # # The compiles are the on-screen keyboard (wvkbd with this repository's # patches) and its controller, the startup cursor helper (wtype), the -# mute-switch and power-control helpers, the rotation daemon and the power daemon +# mute-switch and power-control helpers, the rotation and auto-brightness +# daemons and the power daemon # (omarchy-powerd, against libsystemd's sd-bus: the recipe's makedepends); # desktop/install-tree puts every file in place. @@ -16,7 +17,7 @@ CC ?= cc CFLAGS ?= -O2 PKG_CONFIG ?= pkg-config -all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd $(BUILD)/omarchy-mute-switch $(BUILD)/omarchy-powerctl $(BUILD)/omarchy-keyboard $(BUILD)/arch-ipad-rotate-output +all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd $(BUILD)/omarchy-mute-switch $(BUILD)/omarchy-powerctl $(BUILD)/omarchy-keyboard $(BUILD)/arch-ipad-rotate-output $(BUILD)/arch-ipad-auto-brightness $(BUILD)/omarchy-powerd: desktop/configuration/powerd.c mkdir -p $(BUILD) @@ -39,6 +40,10 @@ $(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)/arch-ipad-auto-brightness: desktop/configuration/auto-brightness.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; } @grep -q preferred_buffer_scale /usr/include/wayland-client-protocol.h || \ diff --git a/desktop/configuration/auto-brightness b/desktop/configuration/auto-brightness deleted file mode 100755 index 6571893c..00000000 --- a/desktop/configuration/auto-brightness +++ /dev/null @@ -1,866 +0,0 @@ -#!/usr/bin/env python3 -"""Ambient-light auto-brightness for omarchy-a. - -Uses the ALS curve, smoothing, hysteresis, ramp and manual pause policy tested -on the iPad 5. Reads generic IIO lux or iio-sensor-proxy; no board calibration -is embedded. Off by default. omarchy-auto-brightness on|off|toggle|enabled|status -controls it; --list and --probe [seconds] diagnose without backlight writes. -Configuration: ~/.config/omarchy/als-brightness.conf (same keys as the port). -The power daemon serializes automatic brightness with screen-off/sleep/wake. -""" - -import argparse -import glob -import json -import math -import os -import pty -import re -import select -import shlex -import shutil -import signal -import socket -import stat -import statistics -import subprocess -import sys -import time - -IIO_ROOT = "/sys/bus/iio/devices" -BACKLIGHT_ROOT = "/sys/class/backlight" -TICK = 0.1 -RAMP_TICK = 1.0 / 30 # loop period while a ramp runs: small, frequent steps look like a fade -RAMP_GAMMA = 2.2 # ramp in perceived brightness (raw ~ perceived ** gamma), not raw PWM -RAMP_MIN_SECS, RAMP_MAX_SECS = 0.3, 3.0 -HOLD_SETTLE = 1.0 # let the power daemon finish restoring brightness after wake -# Panel tuning: the initial brightness curve read too dark on Orchard; lifted ~10-20 points at indoor levels. -DEFAULT_CURVE = "0:15, 5:25, 20:38, 80:58, 250:78, 700:94, 1500:100" -DEFAULTS = { - "enabled": False, - "backlight": "", - "curve": DEFAULT_CURVE, - "min_pct": 5.0, - "max_pct": 100.0, - "lux_scale": 1.0, - "smooth_secs": 3.0, # darkening: slow, so a passing shadow does not dim the panel - "smooth_up_secs": 0.4, # brightening: fast, like iOS (a flashlight should not take seconds) - "hysteresis": 0.20, - "min_pct_step": 2.0, - "min_interval": 2.0, - "min_interval_up": 0.25, - "ramp_pct_per_s": 40.0, - "override_secs": 30.0, - "poll_hz": 4.0, -} - - -def log(*args): - print("omarchy-auto-brightness:", *args, file=sys.stderr, flush=True) - - -# --- configuration and state --------------------------------------------------- -def config_home(): - return os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") - - -def state_path(): - base = os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state") - return os.path.join(base, "omarchy", "display") - - -def runtime_dir(): - return os.path.join(os.environ.get("XDG_RUNTIME_DIR") or "/tmp", "omarchy") - - -def status_path(): - return os.path.join(os.environ.get("XDG_RUNTIME_DIR") or "/tmp", "omarchy-auto-brightness.json") - - -def parse_curve(text): - points = [] - for part in text.replace(";", ",").split(","): - part = part.strip() - if not part: - continue - lux, pct = part.split(":") - points.append((float(lux), float(pct))) - points.sort() - if len(points) < 2 or len({p[0] for p in points}) != len(points): - raise ValueError("needs at least two points with different lux") - return points - - -def load_conf(): - conf = dict(DEFAULTS) - try: - with open(os.path.join(config_home(), "omarchy", "als-brightness.conf")) as f: - lines = f.read().splitlines() - except OSError: - lines = [] - for line in lines: - line = line.split("#", 1)[0].strip() - # several "key = value" pairs may share a line only in the docs; the - # file takes one per line - if "=" not in line: - continue - key, value = (part.strip() for part in line.split("=", 1)) - if key not in DEFAULTS: - log(f"als-brightness.conf: unknown key {key}") - elif key == "enabled": - conf[key] = value.lower() in ("on", "yes", "true", "1") - elif key in ("backlight", "curve"): - conf[key] = value - else: - try: - conf[key] = float(value) - except ValueError: - log(f"als-brightness.conf: {key} = {value}: not a number") - try: - conf["curve_points"] = parse_curve(conf["curve"]) - except ValueError as e: - log(f"als-brightness.conf: curve = {conf['curve']}: {e}; using the default") - conf["curve_points"] = parse_curve(DEFAULT_CURVE) - conf["min_pct"] = max(0.0, min(conf["min_pct"], 100.0)) - conf["max_pct"] = max(conf["min_pct"], min(conf["max_pct"], 100.0)) - return conf - - -def read_state(): - values = {} - try: - with open(state_path()) as f: - for line in f: - m = re.match(r"\s*([\w]+)\s*=\s*(\S+)", line) - if m: - values[m.group(1)] = m.group(2) - except OSError: - pass - return values - - -def set_state(key, value): - """Rewrite the state file with one key changed, the others kept (ipad-rotate - and ipad-tablet keep their own keys in it).""" - path = state_path() - os.makedirs(os.path.dirname(path), exist_ok=True) - try: - with open(path) as f: - lines = [ln for ln in f.read().splitlines() if not re.match(rf"\s*{re.escape(key)}\s*=", ln)] - except OSError: - lines = [] - lines.append(f"{key}={value}") - tmp = f"{path}.{os.getpid()}.tmp" - with open(tmp, "w") as f: - f.write("\n".join(lines) + "\n") - os.replace(tmp, path) - - -FORCE_ENABLED = False # --probe runs whatever the switch says - - -def is_enabled(conf): - if FORCE_ENABLED: - return True - value = read_state().get("auto_brightness") - if value in ("on", "off"): - return value == "on" - return conf["enabled"] - - -# --- the policy (no I/O, so the tests can drive it) ------------------------------- -def curve_pct(points, lux): - """Brightness percent for a lux level: linear in log(1 + lux) between the - points, flat beyond the ends.""" - if lux <= points[0][0]: - return points[0][1] - if lux >= points[-1][0]: - return points[-1][1] - for (x0, y0), (x1, y1) in zip(points, points[1:]): - if x0 <= lux <= x1: - a, b, v = math.log1p(x0), math.log1p(x1), math.log1p(lux) - return y0 + (y1 - y0) * (v - a) / (b - a) - return points[-1][1] - - -class Smoother: - """Median of the last few readings, then a first-order filter in log(1 + lux).""" - - def __init__(self, tau, window=3, tau_up=None): - self.tau, self.window = max(tau, 0.0), window - self.tau_up = self.tau if tau_up is None else max(tau_up, 0.0) - self.readings = [] - self.level = None # log(1 + lux) - self.time = None - - def feed(self, lux, now): - self.readings = (self.readings + [max(lux, 0.0)])[-self.window:] - target = math.log1p(statistics.median(self.readings)) - tau = self.tau_up if self.level is not None and target > self.level else self.tau - if self.level is None or tau == 0: - self.level = target - else: - alpha = 1.0 - math.exp(-max(now - self.time, 0.0) / tau) - self.level += alpha * (target - self.level) - self.time = now - - @property - def lux(self): - return None if self.level is None else math.expm1(self.level) - - -class Policy: - """When to move and to what.""" - - def __init__(self, conf): - self.conf = conf - self.reset() - - def reset(self): - self.ref_level = None # log(1 + lux) at the last move - self.last_move = -1e9 - - def goal(self, lux): - pct = curve_pct(self.conf["curve_points"], lux) - return max(self.conf["min_pct"], min(pct, self.conf["max_pct"])) - - def decide(self, smoothed, now, current_pct): - """The percent to ramp to, or None to stay.""" - goal = self.goal(smoothed.lux) - if self.ref_level is None: - # First move after starting, a pause or a manual change: go now. - if abs(goal - current_pct) < 1.0: - self.ref_level = smoothed.level - return None - else: - if abs(smoothed.level - self.ref_level) < math.log1p(self.conf["hysteresis"]): - return None - if abs(goal - current_pct) < self.conf["min_pct_step"]: - return None - interval = self.conf["min_interval_up"] if goal > current_pct else self.conf["min_interval"] - if now - self.last_move < interval: - return None - self.ref_level = smoothed.level - self.last_move = now - return goal - - -# --- the backlight ------------------------------------------------------------------ -def read_number(path, default=None): - try: - with open(path) as f: - return float(f.read().strip()) - except (OSError, ValueError): - return default - - -def backlight_root(): - return os.environ.get("IPAD_ALS_BACKLIGHT_ROOT") or BACKLIGHT_ROOT - - -def find_backlight(name=""): - root = backlight_root() - if name: - return name if os.path.exists(os.path.join(root, name, "brightness")) else None - for path in sorted(glob.glob(os.path.join(root, "*"))): - if os.path.exists(os.path.join(path, "brightness")) and os.path.exists(os.path.join(path, "max_brightness")): - return os.path.basename(path) - return None - - -class Backlight: - def __init__(self, name): - self.name = name - self.dir = os.path.join(backlight_root(), name) - self.max = int(read_number(os.path.join(self.dir, "max_brightness"), 0)) - self.failed = False - - def read(self): - value = read_number(os.path.join(self.dir, "brightness")) - return None if value is None else int(value) - - def pct(self, raw): - return 100.0 * raw / self.max if self.max else 0.0 - - def raw_for(self, pct): - return max(1, min(self.max, int(round(pct * self.max / 100.0)))) - - def write(self, raw, expected=None): - # Compare-and-set is performed by powerd in its event loop, so an - # automatic ramp cannot race its dark/suspend transition or a manual edit. - current = self.read() - if current is None or current <= 0 or (expected is not None and current != expected): - return False - reply = power_request(f"brightness {self.name} {raw} {current}") - ok = reply == "ok" - if not ok and not self.failed and reply != "held": - log("powerd brightness request failed:", reply or "unavailable") - self.failed = not ok - return ok - - -# --- sensor sources: poll(timeout) -> [lux, ...] ----------------------------------------- -def find_iio_light(root): - """The first IIO device with in_illuminance_input (or raw and scale).""" - for dev in sorted(glob.glob(os.path.join(root, "iio:device*"))): - if os.path.exists(os.path.join(dev, "in_illuminance_input")) or \ - os.path.exists(os.path.join(dev, "in_illuminance_raw")): - return dev - return None - - -def read_iio_lux(dev): - value = read_number(os.path.join(dev, "in_illuminance_input")) - if value is not None: - return value - raw = read_number(os.path.join(dev, "in_illuminance_raw")) - if raw is None: - return None - scale = read_number(os.path.join(dev, "in_illuminance_scale"), 1.0) - offset = read_number(os.path.join(dev, "in_illuminance_offset"), 0.0) - return (raw + offset) * scale - - -class IioSource: - kind = "iio" - - def __init__(self, root, hz): - self.root = root - self.interval = 1.0 / max(hz, 0.5) - self.due = 0.0 - self.warned = False - - def poll(self, timeout): - wait = max(0.0, min(timeout, self.due - time.monotonic())) - time.sleep(wait) - if time.monotonic() < self.due: - return [] - self.due = time.monotonic() + self.interval - dev = find_iio_light(self.root) - lux = read_iio_lux(dev) if dev else None - if lux is None: - if not self.warned: - log("no readable IIO light sensor under", self.root) - self.warned = True - return [] - self.warned = False - return [lux] - - def close(self): - pass - - -class LineSource: - """Lux readings, one number per line, from a FIFO or a file (--mock).""" - - kind = "mock" - - def __init__(self, path): - self.path = path - self.buf = b"" - self.fd = None - self.offset = 0 - self.pending = [] - if not os.path.exists(path): - os.mkfifo(path, 0o600) - self.fifo = stat.S_ISFIFO(os.stat(path).st_mode) - if self.fifo: - self.fd = os.open(path, os.O_RDWR | os.O_NONBLOCK) - else: - with open(path) as f: - self.pending = [v for v in map(self.parse, f.read().splitlines()) if v is not None][-1:] - self.offset = os.path.getsize(path) - - @staticmethod - def parse(line): - line = line.split("#", 1)[0].strip() - try: - return float(line) - except ValueError: - return None - - def poll(self, timeout): - out = list(self.pending) - self.pending = [] - if self.fifo: - ready, _, _ = select.select([self.fd], [], [], timeout) - if ready: - self.buf += os.read(self.fd, 4096) - *lines, self.buf = self.buf.split(b"\n") - out += [self.parse(ln.decode(errors="replace")) for ln in lines] - else: - time.sleep(min(timeout, 0.2)) - try: - size = os.path.getsize(self.path) - except OSError: - size = self.offset - if size < self.offset: - self.offset = 0 - if size > self.offset: - with open(self.path, "rb") as f: - f.seek(self.offset) - data = f.read() - self.offset += len(data) - out += [self.parse(ln.decode(errors="replace")) for ln in data.splitlines()] - return [v for v in out if v is not None] - - def close(self): - if self.fd is not None: - os.close(self.fd) - - -class ProxySource: - """iio-sensor-proxy through monitor-sensor, on a pty so its output isn't - block-buffered. It prints the level when it changes, so the daemon holds - the last value. Restarts monitor-sensor if it exits.""" - - kind = "proxy" - CHANGED = re.compile(r"Light changed:\s*([-+0-9.eE]+)\s*\((\w+)\)") - HAS = re.compile(r"Has ambient light sensor.*?value:\s*([-+0-9.eE]+),\s*unit:\s*(\w+)", re.I) - - def __init__(self): - self.proc = None - self.master = None - self.buf = b"" - self.retry_at = 0.0 - - @staticmethod - def command(): - override = os.environ.get("IPAD_ALS_MONITOR_CMD") - if override: - return shlex.split(override) - cmd = ["monitor-sensor"] - try: - help_text = subprocess.run(cmd + ["--help"], capture_output=True, text=True, timeout=5) - if "--light" in help_text.stdout + help_text.stderr: - cmd.append("--light") - except (OSError, subprocess.TimeoutExpired): - pass - return cmd - - def start(self): - cmd = self.command() - master, slave = pty.openpty() - self.proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=slave, stderr=slave, close_fds=True) - os.close(slave) - self.master = master - self.buf = b"" - log("started", " ".join(cmd)) - - def stop(self): - if self.proc: - self.proc.terminate() - try: - self.proc.wait(timeout=3) - except subprocess.TimeoutExpired: - self.proc.kill() - if self.master is not None: - os.close(self.master) - self.proc = self.master = None - - def poll(self, timeout): - if self.proc is None: - if time.monotonic() < self.retry_at: - time.sleep(timeout) - return [] - try: - self.start() - except OSError as e: - log("cannot start monitor-sensor:", e) - self.retry_at = time.monotonic() + 5 - return [] - ready, _, _ = select.select([self.master], [], [], timeout) - if not ready: - if self.proc.poll() is not None: - self.exited() - return [] - try: - data = os.read(self.master, 4096) - except OSError: # EIO: the child closed the pty - data = b"" - if not data: - self.exited() - return [] - self.buf += data - *lines, self.buf = self.buf.split(b"\n") - out = [] - for raw in lines: - text = raw.decode(errors="replace").strip() - m = self.CHANGED.search(text) or self.HAS.search(text) - if m: - if m.group(2).lower() != "lux": - log(f"iio-sensor-proxy reports {m.group(2)}, not lux: ignoring") - continue - out.append(float(m.group(1))) - elif text: - log("monitor-sensor:", text) - return out - - def exited(self): - log("monitor-sensor exited; retrying in 3 s") - self.stop() - self.retry_at = time.monotonic() + 3 - - def close(self): - self.stop() - - -def proxy_has_light(): - try: - out = subprocess.run( - ["busctl", "--system", "get-property", "net.hadess.SensorProxy", "/net/hadess/SensorProxy", - "net.hadess.SensorProxy", "HasAmbientLight"], - capture_output=True, text=True, timeout=10).stdout.strip() - except (OSError, subprocess.TimeoutExpired): - return False - return out == "b true" - - -def have_monitor_sensor(): - return bool(os.environ.get("IPAD_ALS_MONITOR_CMD")) or shutil.which("monitor-sensor") is not None - - -def make_source(args, conf): - if args.mock: - return LineSource(args.mock) - root = args.mock_iio or IIO_ROOT - if args.mock_iio: - return IioSource(root, conf["poll_hz"]) - if args.source == "proxy": - return ProxySource() - if args.source == "iio": - return IioSource(root, conf["poll_hz"]) - announced = False - deadline = time.monotonic() + float(os.environ.get("IPAD_ALS_DISCOVERY_SECS", "15")) - while True: - if have_monitor_sensor() and proxy_has_light(): - return ProxySource() - if find_iio_light(root): - return IioSource(root, conf["poll_hz"]) - if args.probe is not None: - log("no ambient light sensor: iio-sensor-proxy has none and there is no IIO device") - sys.exit(1) - if time.monotonic() >= deadline: - log("no ambient light sensor after discovery window; exiting") - sys.exit(0) - if not announced: - log("no ambient light sensor yet (iio-sensor-proxy has none, no IIO device); waiting") - announced = True - time.sleep(3) - - -def list_sensors(args, conf): - print("iio-sensor-proxy HasAmbientLight:", proxy_has_light() if shutil.which("busctl") else "no busctl") - print("monitor-sensor:", "found" if have_monitor_sensor() else "missing") - dev = find_iio_light(args.mock_iio or IIO_ROOT) - print("IIO light sensor:", dev or "none") - if dev: - print(" lux:", read_iio_lux(dev)) - name = find_backlight(conf["backlight"]) - print("backlight:", name or "none") - if name: - bl = Backlight(name) - raw = bl.read() - print(f" brightness {raw} of {bl.max}" + ("" if raw is None else f" ({bl.pct(raw):.0f} %)")) - print("powerd:", power_request("als-state") or "unavailable") - print("auto-brightness:", "on" if is_enabled(conf) else "off") - - -# --- holds: other tools that own the backlight for a while ----------------------------- -def power_request(request): - path = os.environ.get("IPAD_ALS_POWER_SOCKET", "/run/omarchy-powerd.sock") - try: - with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer: - peer.settimeout(0.5) - peer.connect(path) - peer.sendall((request + "\n").encode()) - return peer.recv(64).decode().strip() - except (OSError, UnicodeError): - return "" - - -def holds(): - # No answer is a hold too: never infer that an unavailable power daemon - # permits the automatic controller to light the panel. - return [] if power_request("als-state") == "lit" else ["powerd"] - - -# --- the daemon ------------------------------------------------------------------------- -class Daemon: - def __init__(self, conf, source, backlight, dry, debug): - self.conf, self.source, self.backlight, self.dry, self.debug = conf, source, backlight, dry, debug - self.smoother = Smoother(conf["smooth_secs"], tau_up=conf["smooth_up_secs"]) - self.policy = Policy(conf) - self.latest = None # the last lux reading - self.next_sample = 0.0 - self.last_written = None # raw value we last set; a different reading is someone else's - self.goal_raw = None - self.next_step = 0.0 - self.override_until = 0.0 - self.hold = [] - self.settle_until = 0.0 - self.active = False - self.moves = 0 - self.stop = False - self.shown = None - - # -- helpers - def tolerance(self): - return max(2, int(round(self.backlight.max * 0.01))) - - def pause(self, why): - """Forget what we were doing, so that what comes next starts from the - backlight as it is.""" - self.last_written = None - self.goal_raw = None - self.policy.reset() - if self.active: - log("paused:", why) - self.active = False - - def tick(self, now): - conf = self.conf - if not is_enabled(conf): - self.pause("off") - self.write_status(now, enabled=False) - return - hold = [] if self.dry else holds() - if hold != self.hold: - if hold: - log("holding for", ", ".join(hold)) - elif self.hold: - self.settle_until = now + HOLD_SETTLE - self.hold = hold - if hold or now < self.settle_until: - self.pause("hold") - self.write_status(now, enabled=True) - return - raw = self.backlight.read() - if raw is None: - return - # A change we didn't make: a brightness key, the menu. - if self.last_written is not None and abs(raw - self.last_written) > self.tolerance(): - self.override_until = now + conf["override_secs"] - log(f"brightness changed by hand ({self.backlight.pct(self.last_written):.0f} -> " - f"{self.backlight.pct(raw):.0f} %): paused for {conf['override_secs']:.0f} s") - self.pause("manual change") - if now < self.override_until: - self.write_status(now, enabled=True, override=self.override_until - now) - return - if not self.active: - self.active = True - log("auto-brightness on") - # sample - if self.latest is not None and now >= self.next_sample: - self.next_sample = now + 1.0 / max(conf["poll_hz"], 0.5) - self.smoother.feed(self.latest * conf["lux_scale"], now) - goal = self.policy.decide(self.smoother, now, self.backlight.pct(raw)) - if self.debug: - log("lux %.1f smoothed %.1f -> %s" % - (self.latest * conf["lux_scale"], self.smoother.lux, - "%.0f %%" % goal if goal is not None else "stay")) - if goal is not None: - self.goal_raw = self.backlight.raw_for(goal) - self.start_ramp(raw, now) - log("lux %.0f: brightness %.0f %% -> %.0f %% over %.2f s" % - (self.smoother.lux, self.backlight.pct(raw), goal, self.ramp_secs)) - # ramp - if self.goal_raw is not None: - self.step(raw, now) - self.write_status(now, enabled=True) - - # Perceived brightness in [0, 1]: equal steps here look equal on the panel. - def perceived(self, raw): - return (max(raw, 0) / self.backlight.max) ** (1.0 / RAMP_GAMMA) if self.backlight.max else 0.0 - - def raw_from_perceived(self, p): - return max(1, min(self.backlight.max, int(round(self.backlight.max * max(p, 0.0) ** RAMP_GAMMA)))) - - def start_ramp(self, raw, now): - """Fade from the current level to goal_raw: the duration follows the perceived - change (ramp_pct_per_s in perceived percent), eased in and out.""" - self.ramp_from, self.ramp_start = raw, now - delta = abs(self.perceived(self.goal_raw) - self.perceived(raw)) * 100.0 - speed = max(self.conf["ramp_pct_per_s"], 1.0) - self.ramp_secs = max(RAMP_MIN_SECS, min(delta / speed, RAMP_MAX_SECS)) - - def step(self, raw, now): - t = min(1.0, (now - self.ramp_start) / self.ramp_secs) if self.ramp_secs > 0 else 1.0 - if t >= 1.0: - new = self.goal_raw - else: - eased = t * t * (3.0 - 2.0 * t) # smoothstep: no jolt at the start or the end - p0, p1 = self.perceived(self.ramp_from), self.perceived(self.goal_raw) - new = self.raw_from_perceived(p0 + (p1 - p0) * eased) - if new == raw: - if t >= 1.0: - self.goal_raw = None - self.last_written = raw - return - if self.dry: - log(f"would set brightness {new} of {self.backlight.max} (dry run)") - self.goal_raw = None - return - if self.backlight.write(new, expected=raw): - self.last_written = new - self.moves += 1 - if new == self.goal_raw: - self.goal_raw = None - else: - self.goal_raw = None # a manual change or a dark transition: decide again later - - def ramping(self): - return self.goal_raw is not None - - def write_status(self, now, enabled, override=0.0): - if self.shown is not None and now - self.shown < 1.0: - return - self.shown = now - raw = self.backlight.read() - data = { - "pid": os.getpid(), - "source": self.source.kind, - "enabled": enabled, - "backlight": self.backlight.name, - "brightness_pct": None if raw is None else round(self.backlight.pct(raw), 1), - "lux": self.latest, - "smoothed_lux": None if self.smoother.lux is None else round(self.smoother.lux, 1), - "hold": self.hold, - "override_secs_left": round(override, 1), - "moves": self.moves, - "time": time.time(), - } - tmp = status_path() + ".tmp" - try: - with open(tmp, "w") as f: - json.dump(data, f) - os.replace(tmp, status_path()) - except OSError: - pass - - def run(self, seconds=None): - end = time.monotonic() + seconds if seconds else None - log(f"source {self.source.kind}, backlight {self.backlight.name} (max {self.backlight.max})" - + (", dry run" if self.dry else "") + ("" if is_enabled(self.conf) else "; off until switched on")) - compositor = os.environ.get("LABWC_PID") - while not self.stop and (end is None or time.monotonic() < end): - if compositor: - try: - os.kill(int(compositor), 0) - except (OSError, ValueError): - break - if not is_enabled(self.conf): - self.tick(time.monotonic()) - time.sleep(1) # off means no 10Hz backlight/status work - continue - for lux in self.source.poll(RAMP_TICK if self.ramping() else TICK): - self.latest = lux - self.tick(time.monotonic()) - self.source.close() - try: - os.unlink(status_path()) - except OSError: - pass - - -# --- commands ------------------------------------------------------------------------------- -def running_pid(): - try: - with open(status_path()) as f: - pid = json.load(f)["pid"] - os.kill(pid, 0) - return pid - except (OSError, ValueError, KeyError): - return None - - -def cmd_switch(action, conf): - now = is_enabled(conf) - want = (not now) if action == "toggle" else action == "on" - set_state("auto_brightness", "on" if want else "off") - print("auto-brightness", "on" if want else "off") - if want and not running_pid(): - print("note: the daemon isn't running (no ambient light sensor, or not logged in yet)", file=sys.stderr) - return 0 - - -def cmd_status(conf): - pid = running_pid() - print("auto-brightness:", "on" if is_enabled(conf) else "off", "| daemon:", f"running (pid {pid})" if pid else "not running") - if pid: - try: - with open(status_path()) as f: - print(f.read()) - except OSError: - pass - return 0 if pid else 1 - - -def main(): - parser = argparse.ArgumentParser(add_help=False) - parser.add_argument("command", nargs="?", default="daemon", - choices=("daemon", "on", "off", "toggle", "status", "enabled", "available")) - parser.add_argument("--source", choices=("auto", "proxy", "iio"), default=None) - parser.add_argument("--mock") - parser.add_argument("--mock-iio") - parser.add_argument("--dry-run", action="store_true") - parser.add_argument("--probe", nargs="?", const=20, type=float) - parser.add_argument("--list", action="store_true") - parser.add_argument("--debug", action="store_true") - parser.add_argument("-h", "--help", action="store_true") - args = parser.parse_args() - if args.help: - print(__doc__.strip("\n")) - return 0 - conf = load_conf() - if args.source is None: - args.source = os.environ.get("IPAD_ALS_SOURCE", "auto") - if args.list: - list_sensors(args, conf) - return 0 - if args.command in ("on", "off", "toggle"): - return cmd_switch(args.command, conf) - if args.command == "status": - return cmd_status(conf) - if args.command == "enabled": - return 0 if is_enabled(conf) else 1 - if args.command == "available": - return 0 if find_iio_light(args.mock_iio or IIO_ROOT) and find_backlight(conf["backlight"]) else 1 - - if args.probe is not None: - global FORCE_ENABLED - args.dry_run = args.debug = True - FORCE_ENABLED = True - name = find_backlight(conf["backlight"]) - if not name: - log("no backlight under", backlight_root()) - if args.probe is not None: - return 1 - while not name: # the panel may appear after the compositor starts - compositor = os.environ.get("LABWC_PID") - if compositor: - try: - os.kill(int(compositor), 0) - except (OSError, ValueError): - return 0 - time.sleep(1) - name = find_backlight(conf["backlight"]) - source = make_source(args, conf) - daemon = Daemon(conf, source, Backlight(name), args.dry_run, args.debug) - def stop(*_): - daemon.stop = True - - def reload(*_): - daemon.conf.update(load_conf()) - daemon.smoother.tau = daemon.conf["smooth_secs"] - daemon.smoother.tau_up = daemon.conf["smooth_up_secs"] - - signal.signal(signal.SIGTERM, stop) - signal.signal(signal.SIGINT, stop) - signal.signal(signal.SIGHUP, reload) - daemon.run(args.probe) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/desktop/configuration/auto-brightness.c b/desktop/configuration/auto-brightness.c new file mode 100644 index 00000000..21a9e2c1 --- /dev/null +++ b/desktop/configuration/auto-brightness.c @@ -0,0 +1,2170 @@ +/* Ambient-light auto-brightness for omarchy-a. + * + * Uses the ALS curve, smoothing, hysteresis, ramp and manual pause policy tested + * on the iPad 5. Reads generic IIO lux or iio-sensor-proxy; no board calibration + * is embedded. Off by default. omarchy-auto-brightness on|off|toggle|enabled|status + * controls it; --list and --probe [seconds] diagnose without backlight writes. + * Configuration: ~/.config/omarchy/als-brightness.conf (same keys as the port). + * The power daemon serializes automatic brightness with screen-off/sleep/wake. + */ + +#define _XOPEN_SOURCE 700 +#define _DEFAULT_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define IIO_ROOT "/sys/bus/iio/devices" +#define BACKLIGHT_ROOT "/sys/class/backlight" +#define TICK_SECS 0.1 +#define RAMP_TICK_SECS (1.0 / 30.0) +#define RAMP_GAMMA 2.2 +#define RAMP_MIN_SECS 0.3 +#define RAMP_MAX_SECS 3.0 +#define HOLD_SETTLE 1.0 +#define DEFAULT_CURVE "0:15, 5:25, 20:38, 80:58, 250:78, 700:94, 1500:100" +#define MAX_CURVE_PTS 64 +#define MAX_WINDOW 16 + +static const char *USAGE_DOC = + "Ambient-light auto-brightness for omarchy-a.\n" + "\n" + "Uses the ALS curve, smoothing, hysteresis, ramp and manual pause policy tested\n" + "on the iPad 5. Reads generic IIO lux or iio-sensor-proxy; no board calibration\n" + "is embedded. Off by default. omarchy-auto-brightness on|off|toggle|enabled|status\n" + "controls it; --list and --probe [seconds] diagnose without backlight writes.\n" + "Configuration: ~/.config/omarchy/als-brightness.conf (same keys as the port).\n" + "The power daemon serializes automatic brightness with screen-off/sleep/wake."; + +static volatile sig_atomic_t g_stop = 0; +static volatile sig_atomic_t g_reload = 0; +static bool g_force_enabled = false; + +static void handle_stop(int sig) +{ + (void)sig; + g_stop = 1; +} + +static void handle_reload(int sig) +{ + (void)sig; + g_reload = 1; +} + +static void log_msg(const char *fmt, ...) +{ + va_list ap; + fprintf(stderr, "omarchy-auto-brightness: "); + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + fputc('\n', stderr); + fflush(stderr); +} + +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 double realtime_now(void) +{ + struct timespec ts; + if (clock_gettime(CLOCK_REALTIME, &ts) != 0) + return 0.0; + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static void sleep_secs(double secs) +{ + if (secs <= 0.0) + return; + struct timespec ts; + ts.tv_sec = (time_t)secs; + ts.tv_nsec = (long)((secs - (double)ts.tv_sec) * 1e9); + if (ts.tv_nsec < 0) + ts.tv_nsec = 0; + if (ts.tv_nsec >= 1000000000L) { + ts.tv_sec++; + ts.tv_nsec -= 1000000000L; + } + nanosleep(&ts, NULL); +} + +static char *trim_ws(char *s) +{ + while (*s && isspace((unsigned char)*s)) + s++; + size_t n = strlen(s); + while (n > 0 && isspace((unsigned char)s[n - 1])) + s[--n] = '\0'; + return s; +} + +static void mkdir_p(const char *dir) +{ + char tmp[PATH_MAX]; + size_t len = strlen(dir); + if (len == 0 || len >= sizeof(tmp)) + return; + memcpy(tmp, dir, len + 1); + for (char *p = tmp + 1; *p; p++) { + if (*p == '/') { + *p = '\0'; + mkdir(tmp, 0755); + *p = '/'; + } + } + mkdir(tmp, 0755); +} + +/* -------------------------------------------------------------------------- + * Configuration and state + * -------------------------------------------------------------------------- */ + +struct curve_point { + double lux; + double pct; +}; + +struct conf { + bool enabled; + char backlight[128]; + char curve[512]; + struct curve_point curve_points[MAX_CURVE_PTS]; + int curve_count; + double min_pct; + double max_pct; + double lux_scale; + double smooth_secs; + double smooth_up_secs; + double hysteresis; + double min_pct_step; + double min_interval; + double min_interval_up; + double ramp_pct_per_s; + double override_secs; + double poll_hz; +}; + +static void get_config_home(char *out, size_t cap) +{ + const char *xdg = getenv("XDG_CONFIG_HOME"); + if (xdg && *xdg) { + snprintf(out, cap, "%s", xdg); + } else { + const char *home = getenv("HOME"); + snprintf(out, cap, "%s/.config", home ? home : ""); + } +} + +static void get_state_path(char *out, size_t cap) +{ + const char *xdg = getenv("XDG_STATE_HOME"); + if (xdg && *xdg) { + snprintf(out, cap, "%s/omarchy/display", xdg); + } else { + const char *home = getenv("HOME"); + snprintf(out, cap, "%s/.local/state/omarchy/display", home ? home : ""); + } +} + +static void get_status_path(char *out, size_t cap) +{ + const char *rt = getenv("XDG_RUNTIME_DIR"); + snprintf(out, cap, "%s/omarchy-auto-brightness.json", (rt && *rt) ? rt : "/tmp"); +} + +static int cmp_curve_point(const void *a, const void *b) +{ + const struct curve_point *pa = a; + const struct curve_point *pb = b; + if (pa->lux < pb->lux) + return -1; + if (pa->lux > pb->lux) + return 1; + if (pa->pct < pb->pct) + return -1; + if (pa->pct > pb->pct) + return 1; + return 0; +} + +static bool parse_curve(const char *text, struct curve_point *pts, int *out_count) +{ + char copy[512]; + size_t n = strlen(text); + if (n >= sizeof(copy)) + return false; + memcpy(copy, text, n + 1); + for (size_t i = 0; i < n; i++) { + if (copy[i] == ';') + copy[i] = ','; + } + + int count = 0; + char *p = copy; + while (p) { + char *comma = strchr(p, ','); + if (comma) + *comma = '\0'; + char *part = trim_ws(p); + if (*part) { + char *colon = strchr(part, ':'); + if (!colon || strchr(colon + 1, ':')) + return false; + *colon = '\0'; + char *s_lux = trim_ws(part); + char *s_pct = trim_ws(colon + 1); + char *e1 = NULL, *e2 = NULL; + double lux = strtod(s_lux, &e1); + double pct = strtod(s_pct, &e2); + if (e1 == s_lux || *e1 != '\0' || !isfinite(lux) || + e2 == s_pct || *e2 != '\0' || !isfinite(pct)) + return false; + if (count >= MAX_CURVE_PTS) + return false; + pts[count].lux = lux; + pts[count].pct = pct; + count++; + } + p = comma ? comma + 1 : NULL; + } + + if (count < 2) + return false; + qsort(pts, (size_t)count, sizeof(pts[0]), cmp_curve_point); + for (int i = 1; i < count; i++) { + if (pts[i].lux == pts[i - 1].lux) + return false; + } + *out_count = count; + return true; +} + +static void conf_defaults(struct conf *c) +{ + memset(c, 0, sizeof(*c)); + c->enabled = false; + c->backlight[0] = '\0'; + snprintf(c->curve, sizeof(c->curve), "%s", DEFAULT_CURVE); + c->min_pct = 5.0; + c->max_pct = 100.0; + c->lux_scale = 1.0; + c->smooth_secs = 3.0; + c->smooth_up_secs = 0.4; + c->hysteresis = 0.20; + c->min_pct_step = 2.0; + c->min_interval = 2.0; + c->min_interval_up = 0.25; + c->ramp_pct_per_s = 40.0; + c->override_secs = 30.0; + c->poll_hz = 4.0; + parse_curve(DEFAULT_CURVE, c->curve_points, &c->curve_count); +} + +static void load_conf(struct conf *c) +{ + conf_defaults(c); + + char cfg_home[PATH_MAX]; + char path[PATH_MAX + 64]; + get_config_home(cfg_home, sizeof(cfg_home)); + snprintf(path, sizeof(path), "%s/omarchy/als-brightness.conf", cfg_home); + + FILE *f = fopen(path, "r"); + if (f) { + char line[1024]; + while (fgets(line, sizeof(line), f)) { + char *hash = strchr(line, '#'); + if (hash) + *hash = '\0'; + char *s = trim_ws(line); + char *eq = strchr(s, '='); + if (!eq) + continue; + *eq = '\0'; + char *key = trim_ws(s); + char *val = trim_ws(eq + 1); + + if (strcmp(key, "enabled") == 0) { + c->enabled = (strcasecmp(val, "on") == 0 || + strcasecmp(val, "yes") == 0 || + strcasecmp(val, "true") == 0 || + strcmp(val, "1") == 0); + } else if (strcmp(key, "backlight") == 0) { + snprintf(c->backlight, sizeof(c->backlight), "%s", val); + } else if (strcmp(key, "curve") == 0) { + snprintf(c->curve, sizeof(c->curve), "%s", val); + } else { + double *target = NULL; + if (strcmp(key, "min_pct") == 0) target = &c->min_pct; + else if (strcmp(key, "max_pct") == 0) target = &c->max_pct; + else if (strcmp(key, "lux_scale") == 0) target = &c->lux_scale; + else if (strcmp(key, "smooth_secs") == 0) target = &c->smooth_secs; + else if (strcmp(key, "smooth_up_secs") == 0) target = &c->smooth_up_secs; + else if (strcmp(key, "hysteresis") == 0) target = &c->hysteresis; + else if (strcmp(key, "min_pct_step") == 0) target = &c->min_pct_step; + else if (strcmp(key, "min_interval") == 0) target = &c->min_interval; + else if (strcmp(key, "min_interval_up") == 0) target = &c->min_interval_up; + else if (strcmp(key, "ramp_pct_per_s") == 0) target = &c->ramp_pct_per_s; + else if (strcmp(key, "override_secs") == 0) target = &c->override_secs; + else if (strcmp(key, "poll_hz") == 0) target = &c->poll_hz; + + if (!target) { + log_msg("als-brightness.conf: unknown key %s", key); + } else { + char *end = NULL; + double v = strtod(val, &end); + if (end == val || *end != '\0' || !isfinite(v)) + log_msg("als-brightness.conf: %s = %s: not a number", key, val); + else + *target = v; + } + } + } + fclose(f); + } + + if (!parse_curve(c->curve, c->curve_points, &c->curve_count)) { + log_msg("als-brightness.conf: curve = %s: invalid; using the default", c->curve); + parse_curve(DEFAULT_CURVE, c->curve_points, &c->curve_count); + } + if (c->min_pct < 0.0) c->min_pct = 0.0; + if (c->min_pct > 100.0) c->min_pct = 100.0; + if (c->max_pct < c->min_pct) c->max_pct = c->min_pct; + if (c->max_pct > 100.0) c->max_pct = 100.0; +} + +static bool is_ident_char(char c) +{ + return isalnum((unsigned char)c) || c == '_'; +} + +static bool read_state_value(const char *wanted_key, char *out, size_t cap) +{ + char path[PATH_MAX]; + get_state_path(path, sizeof(path)); + FILE *f = fopen(path, "r"); + if (!f) + return false; + + bool found = false; + char line[512]; + while (fgets(line, sizeof(line), f)) { + char *p = line; + while (*p && isspace((unsigned char)*p)) + p++; + char *kstart = p; + while (*p && is_ident_char(*p)) + p++; + size_t klen = (size_t)(p - kstart); + if (klen == 0) + continue; + while (*p && isspace((unsigned char)*p)) + p++; + if (*p != '=') + continue; + p++; + while (*p && isspace((unsigned char)*p)) + p++; + char *vstart = p; + while (*p && !isspace((unsigned char)*p)) + p++; + size_t vlen = (size_t)(p - vstart); + if (vlen == 0) + continue; + if (strlen(wanted_key) == klen && memcmp(kstart, wanted_key, klen) == 0) { + if (vlen >= cap) + vlen = cap - 1; + memcpy(out, vstart, vlen); + out[vlen] = '\0'; + found = true; + } + } + fclose(f); + return found; +} + +static bool set_state_value(const char *key, const char *value) +{ + char path[PATH_MAX]; + get_state_path(path, sizeof(path)); + + char dir[PATH_MAX]; + snprintf(dir, sizeof(dir), "%s", path); + char *slash = strrchr(dir, '/'); + if (slash) { + *slash = '\0'; + mkdir_p(dir); + } + + char tmp[PATH_MAX + 32]; + snprintf(tmp, sizeof(tmp), "%s.%ld.tmp", path, (long)getpid()); + FILE *out = fopen(tmp, "w"); + if (!out) + return false; + + size_t key_len = strlen(key); + FILE *in = fopen(path, "r"); + if (in) { + char line[512]; + while (fgets(line, sizeof(line), in)) { + char *p = line; + while (*p && isspace((unsigned char)*p)) + p++; + if (strncmp(p, key, key_len) == 0) { + char *q = p + key_len; + while (*q && isspace((unsigned char)*q)) + q++; + if (*q == '=') + continue; + } + fputs(line, out); + if (line[0] && line[strlen(line) - 1] != '\n') + fputc('\n', out); + } + fclose(in); + } + + fprintf(out, "%s=%s\n", key, value); + if (fclose(out) != 0) { + unlink(tmp); + return false; + } + if (rename(tmp, path) != 0) { + unlink(tmp); + return false; + } + return true; +} + +static bool is_enabled(const struct conf *c) +{ + if (g_force_enabled) + return true; + char val[64]; + if (read_state_value("auto_brightness", val, sizeof(val))) { + if (strcmp(val, "on") == 0) + return true; + if (strcmp(val, "off") == 0) + return false; + } + return c->enabled; +} + +/* -------------------------------------------------------------------------- + * Pure policy math + * -------------------------------------------------------------------------- */ + +static double curve_pct(const struct curve_point *pts, int count, double lux) +{ + if (lux <= pts[0].lux) + return pts[0].pct; + if (lux >= pts[count - 1].lux) + return pts[count - 1].pct; + for (int i = 0; i < count - 1; i++) { + double x0 = pts[i].lux, y0 = pts[i].pct; + double x1 = pts[i + 1].lux, y1 = pts[i + 1].pct; + if (x0 <= lux && lux <= x1) { + double a = log1p(x0), b = log1p(x1), v = log1p(lux); + return y0 + (y1 - y0) * (v - a) / (b - a); + } + } + return pts[count - 1].pct; +} + +struct smoother { + double tau; + double tau_up; + int window; + double readings[MAX_WINDOW]; + int count; + bool has_level; + double level; + double last_time; +}; + +static void smoother_init(struct smoother *s, double tau, int window, bool has_tau_up, double tau_up) +{ + memset(s, 0, sizeof(*s)); + s->tau = tau > 0.0 ? tau : 0.0; + s->tau_up = has_tau_up ? (tau_up > 0.0 ? tau_up : 0.0) : s->tau; + s->window = (window < 1) ? 1 : (window > MAX_WINDOW ? MAX_WINDOW : window); +} + +static int cmp_double(const void *a, const void *b) +{ + double da = *(const double *)a; + double db = *(const double *)b; + return (da < db) ? -1 : (da > db ? 1 : 0); +} + +static void smoother_feed(struct smoother *s, double lux, double now) +{ + if (lux < 0.0) + lux = 0.0; + if (s->count == s->window) { + memmove(&s->readings[0], &s->readings[1], + (size_t)(s->window - 1) * sizeof(s->readings[0])); + s->readings[s->window - 1] = lux; + } else { + s->readings[s->count++] = lux; + } + + double sorted[MAX_WINDOW]; + memcpy(sorted, s->readings, (size_t)s->count * sizeof(sorted[0])); + qsort(sorted, (size_t)s->count, sizeof(sorted[0]), cmp_double); + double med = (s->count % 2 == 1) + ? sorted[s->count / 2] + : 0.5 * (sorted[s->count / 2 - 1] + sorted[s->count / 2]); + + double target = log1p(med); + double tau = (s->has_level && target > s->level) ? s->tau_up : s->tau; + if (!s->has_level || tau == 0.0) { + s->level = target; + s->has_level = true; + } else { + double dt = now - s->last_time; + if (dt < 0.0) + dt = 0.0; + double alpha = 1.0 - exp(-dt / tau); + s->level += alpha * (target - s->level); + } + s->last_time = now; +} + +static double smoother_lux(const struct smoother *s) +{ + return expm1(s->level); +} + +struct policy { + const struct conf *conf; + bool has_ref_level; + double ref_level; + double last_move; +}; + +static void policy_reset(struct policy *p) +{ + p->has_ref_level = false; + p->ref_level = 0.0; + p->last_move = -1e9; +} + +static void policy_init(struct policy *p, const struct conf *c) +{ + p->conf = c; + policy_reset(p); +} + +static double policy_goal(const struct policy *p, double lux) +{ + double pct = curve_pct(p->conf->curve_points, p->conf->curve_count, lux); + if (pct < p->conf->min_pct) pct = p->conf->min_pct; + if (pct > p->conf->max_pct) pct = p->conf->max_pct; + return pct; +} + +static bool policy_decide(struct policy *p, double level, double lux, + double now, double current_pct, double *out_goal) +{ + double goal = policy_goal(p, lux); + if (!p->has_ref_level) { + if (fabs(goal - current_pct) < 1.0) { + p->has_ref_level = true; + p->ref_level = level; + return false; + } + } else { + if (fabs(level - p->ref_level) < log1p(p->conf->hysteresis)) + return false; + if (fabs(goal - current_pct) < p->conf->min_pct_step) + return false; + double interval = (goal > current_pct) + ? p->conf->min_interval_up : p->conf->min_interval; + if (now - p->last_move < interval) + return false; + } + p->has_ref_level = true; + p->ref_level = level; + p->last_move = now; + *out_goal = goal; + return true; +} + +/* -------------------------------------------------------------------------- + * Power daemon IPC & Backlight + * -------------------------------------------------------------------------- */ + +static bool power_request(const char *request, char *reply, size_t cap) +{ + if (cap > 0) + reply[0] = '\0'; + const char *path = getenv("IPAD_ALS_POWER_SOCKET"); + if (!path || !*path) + path = "/run/omarchy-powerd.sock"; + + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + if (strlen(path) >= sizeof(addr.sun_path)) + return false; + memcpy(addr.sun_path, path, strlen(path) + 1); + + int fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) + return false; + + struct timeval tv = { .tv_sec = 0, .tv_usec = 500000 }; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + + if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + close(fd); + return false; + } + + char req_buf[256]; + int req_len = snprintf(req_buf, sizeof(req_buf), "%s\n", request); + if (req_len <= 0 || (size_t)req_len >= sizeof(req_buf)) { + close(fd); + return false; + } + size_t off = 0; + while (off < (size_t)req_len) { + ssize_t n = send(fd, req_buf + off, (size_t)req_len - off, MSG_NOSIGNAL); + if (n <= 0) { + if (n < 0 && errno == EINTR) + continue; + close(fd); + return false; + } + off += (size_t)n; + } + + ssize_t n = recv(fd, reply, cap - 1, 0); + close(fd); + if (n <= 0) + return false; + reply[n] = '\0'; + char *trimmed = trim_ws(reply); + if (trimmed != reply) + memmove(reply, trimmed, strlen(trimmed) + 1); + return true; +} + +static bool has_powerd_hold(void) +{ + char reply[64]; + if (!power_request("als-state", reply, sizeof(reply))) + return true; + return strcmp(reply, "lit") != 0; +} + +static bool read_number(const char *path, double *out) +{ + FILE *f = fopen(path, "r"); + if (!f) + return false; + char buf[128]; + size_t n = fread(buf, 1, sizeof(buf) - 1, f); + fclose(f); + buf[n] = '\0'; + char *s = trim_ws(buf); + if (!*s) + return false; + char *end = NULL; + double v = strtod(s, &end); + if (end == s || *end != '\0' || !isfinite(v)) + return false; + *out = v; + return true; +} + +static const char *backlight_root(void) +{ + const char *env = getenv("IPAD_ALS_BACKLIGHT_ROOT"); + return (env && *env) ? env : BACKLIGHT_ROOT; +} + +static bool find_backlight(const char *wanted, char *out_name, size_t cap) +{ + const char *root = backlight_root(); + char path[PATH_MAX]; + if (wanted && *wanted) { + snprintf(path, sizeof(path), "%s/%s/brightness", root, wanted); + if (access(path, F_OK) == 0) { + snprintf(out_name, cap, "%s", wanted); + return true; + } + return false; + } + + char pattern[PATH_MAX]; + snprintf(pattern, sizeof(pattern), "%s/*", root); + glob_t g; + bool found = false; + if (glob(pattern, 0, NULL, &g) == 0) { + for (size_t i = 0; i < g.gl_pathc; i++) { + char bpath[PATH_MAX], mpath[PATH_MAX]; + snprintf(bpath, sizeof(bpath), "%s/brightness", g.gl_pathv[i]); + snprintf(mpath, sizeof(mpath), "%s/max_brightness", g.gl_pathv[i]); + if (access(bpath, F_OK) == 0 && access(mpath, F_OK) == 0) { + const char *base = strrchr(g.gl_pathv[i], '/'); + snprintf(out_name, cap, "%s", base ? base + 1 : g.gl_pathv[i]); + found = true; + break; + } + } + } + globfree(&g); + return found; +} + +struct backlight { + char name[128]; + char dir[PATH_MAX]; + int max; + bool failed; +}; + +static void backlight_init(struct backlight *bl, const char *name) +{ + memset(bl, 0, sizeof(*bl)); + snprintf(bl->name, sizeof(bl->name), "%s", name); + snprintf(bl->dir, sizeof(bl->dir), "%s/%s", backlight_root(), name); + char mpath[PATH_MAX + 32]; + snprintf(mpath, sizeof(mpath), "%s/max_brightness", bl->dir); + double m = 0.0; + if (read_number(mpath, &m)) + bl->max = (int)m; +} + +static bool backlight_read(const struct backlight *bl, int *out) +{ + char bpath[PATH_MAX + 32]; + snprintf(bpath, sizeof(bpath), "%s/brightness", bl->dir); + double v = 0.0; + if (!read_number(bpath, &v)) + return false; + *out = (int)v; + return true; +} + +static double backlight_pct(const struct backlight *bl, int raw) +{ + return bl->max ? (100.0 * (double)raw / (double)bl->max) : 0.0; +} + +static int backlight_raw_for(const struct backlight *bl, double pct) +{ + int v = (int)llround(pct * (double)bl->max / 100.0); + if (v < 1) v = 1; + if (v > bl->max) v = bl->max; + return v; +} + +static bool backlight_write(struct backlight *bl, int raw, bool has_expected, int expected) +{ + int current = 0; + if (!backlight_read(bl, ¤t) || current <= 0 || + (has_expected && current != expected)) + return false; + + char req[256]; + char reply[64]; + snprintf(req, sizeof(req), "brightness %s %d %d", bl->name, raw, current); + bool got = power_request(req, reply, sizeof(reply)); + bool ok = got && strcmp(reply, "ok") == 0; + if (!ok && !bl->failed && strcmp(reply, "held") != 0) + log_msg("powerd brightness request failed: %s", + (got && reply[0]) ? reply : "unavailable"); + bl->failed = !ok; + return ok; +} + +/* -------------------------------------------------------------------------- + * Subprocess capture & PATH lookup + * -------------------------------------------------------------------------- */ + +static bool which_cmd(const char *cmd) +{ + if (!cmd || !*cmd) + return false; + if (strchr(cmd, '/')) + return access(cmd, X_OK) == 0; + const char *path_env = getenv("PATH"); + if (!path_env) + return false; + char copy[4096]; + snprintf(copy, sizeof(copy), "%s", path_env); + char *p = copy; + while (p) { + char *colon = strchr(p, ':'); + if (colon) + *colon = '\0'; + char full[PATH_MAX + 64]; + if (snprintf(full, sizeof(full), "%s/%s", *p ? p : ".", cmd) < (int)sizeof(full) && + access(full, X_OK) == 0) + return true; + p = colon ? colon + 1 : NULL; + } + return false; +} + +static bool run_capture(char *const argv[], double timeout_s, bool merge_stderr, + char *out, size_t cap) +{ + if (cap > 0) + out[0] = '\0'; + 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]); + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + if (!merge_stderr) + dup2(devnull, STDERR_FILENO); + if (devnull > STDERR_FILENO) + close(devnull); + } + dup2(pipefd[1], STDOUT_FILENO); + if (merge_stderr) + dup2(pipefd[1], STDERR_FILENO); + if (pipefd[1] > STDERR_FILENO) + close(pipefd[1]); + execvp(argv[0], argv); + _exit(127); + } + + close(pipefd[1]); + int flags = fcntl(pipefd[0], F_GETFL, 0); + if (flags >= 0) + fcntl(pipefd[0], F_SETFL, flags | O_NONBLOCK); + + double deadline = monotonic_now() + timeout_s; + size_t len = 0; + bool timed_out = false; + 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 (;;) { + char tmp[1024]; + ssize_t n = read(pipefd[0], tmp, sizeof(tmp)); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) + break; + if (errno == EINTR) + continue; + eof = true; + break; + } + if (n == 0) { + eof = true; + break; + } + if (len + 1 < cap) { + size_t take = (size_t)n; + if (len + take >= cap) + take = cap - 1 - len; + memcpy(out + len, tmp, take); + len += take; + } + } + if (eof) + break; + } + close(pipefd[0]); + if (cap > 0) + out[len] = '\0'; + + if (timed_out) + kill(pid, SIGKILL); + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) + ; + return !timed_out; +} + +/* -------------------------------------------------------------------------- + * Sensor sources: IIO, mock file/FIFO, iio-sensor-proxy (monitor-sensor pty) + * -------------------------------------------------------------------------- */ + +static bool find_iio_light(const char *root, char *out, size_t cap) +{ + char pattern[PATH_MAX]; + snprintf(pattern, sizeof(pattern), "%s/iio:device*", root); + glob_t g; + bool found = false; + if (glob(pattern, 0, NULL, &g) == 0) { + for (size_t i = 0; i < g.gl_pathc; i++) { + char p1[PATH_MAX], p2[PATH_MAX]; + snprintf(p1, sizeof(p1), "%s/in_illuminance_input", g.gl_pathv[i]); + snprintf(p2, sizeof(p2), "%s/in_illuminance_raw", g.gl_pathv[i]); + if (access(p1, F_OK) == 0 || access(p2, F_OK) == 0) { + if (out && cap > 0) + snprintf(out, cap, "%s", g.gl_pathv[i]); + found = true; + break; + } + } + } + globfree(&g); + return found; +} + +static bool read_iio_lux(const char *dev, double *out) +{ + char path[PATH_MAX]; + snprintf(path, sizeof(path), "%s/in_illuminance_input", dev); + if (read_number(path, out)) + return true; + + double raw = 0.0; + snprintf(path, sizeof(path), "%s/in_illuminance_raw", dev); + if (!read_number(path, &raw)) + return false; + + double scale = 1.0, offset = 0.0; + snprintf(path, sizeof(path), "%s/in_illuminance_scale", dev); + read_number(path, &scale); + snprintf(path, sizeof(path), "%s/in_illuminance_offset", dev); + read_number(path, &offset); + *out = (raw + offset) * scale; + return true; +} + +static bool proxy_has_light(void) +{ + char *argv[] = { + "busctl", "--system", "get-property", + "net.hadess.SensorProxy", "/net/hadess/SensorProxy", + "net.hadess.SensorProxy", "HasAmbientLight", NULL + }; + char buf[128]; + if (!run_capture(argv, 10.0, false, buf, sizeof(buf))) + return false; + return strcmp(trim_ws(buf), "b true") == 0; +} + +static bool have_monitor_sensor(void) +{ + const char *ov = getenv("IPAD_ALS_MONITOR_CMD"); + return (ov && *ov) || which_cmd("monitor-sensor"); +} + +enum source_kind { + SRC_IIO, + SRC_MOCK, + SRC_PROXY, +}; + +struct source { + enum source_kind kind; + const char *kind_name; + + /* IIO */ + char iio_root[PATH_MAX]; + double interval; + double due; + bool warned; + + /* Mock (LineSource) */ + char mock_path[PATH_MAX]; + bool is_fifo; + int fifo_fd; + off_t offset; + bool has_pending_lux; + double pending_lux; + + /* Proxy (monitor-sensor on PTY) */ + pid_t proc_pid; + int master_fd; + double retry_at; + + /* Shared line buffer for FIFO / PTY */ + char buf[8192]; + size_t buf_len; +}; + +static bool parse_lux_line(const char *line, double *out) +{ + char copy[256]; + snprintf(copy, sizeof(copy), "%s", line); + char *hash = strchr(copy, '#'); + if (hash) + *hash = '\0'; + char *s = trim_ws(copy); + if (!*s) + return false; + char *end = NULL; + double v = strtod(s, &end); + if (end == s || *end != '\0' || !isfinite(v)) + return false; + *out = v; + return true; +} + +static void source_init_iio(struct source *src, const char *root, double hz) +{ + memset(src, 0, sizeof(*src)); + src->kind = SRC_IIO; + src->kind_name = "iio"; + snprintf(src->iio_root, sizeof(src->iio_root), "%s", root); + src->interval = 1.0 / (hz > 0.5 ? hz : 0.5); + src->fifo_fd = -1; + src->master_fd = -1; + src->proc_pid = -1; +} + +static bool source_init_mock(struct source *src, const char *path) +{ + memset(src, 0, sizeof(*src)); + src->kind = SRC_MOCK; + src->kind_name = "mock"; + snprintf(src->mock_path, sizeof(src->mock_path), "%s", path); + src->fifo_fd = -1; + src->master_fd = -1; + src->proc_pid = -1; + + struct stat st; + if (stat(path, &st) != 0) { + if (mkfifo(path, 0600) != 0) + return false; + if (stat(path, &st) != 0) + return false; + } + src->is_fifo = S_ISFIFO(st.st_mode); + if (src->is_fifo) { + src->fifo_fd = open(path, O_RDWR | O_NONBLOCK); + if (src->fifo_fd < 0) + return false; + } else { + FILE *f = fopen(path, "r"); + if (!f) + return false; + char line[256]; + while (fgets(line, sizeof(line), f)) { + double v = 0.0; + if (parse_lux_line(line, &v)) { + src->pending_lux = v; + src->has_pending_lux = true; + } + } + fclose(f); + src->offset = st.st_size; + } + return true; +} + +static void source_init_proxy(struct source *src) +{ + memset(src, 0, sizeof(*src)); + src->kind = SRC_PROXY; + src->kind_name = "proxy"; + src->fifo_fd = -1; + src->master_fd = -1; + src->proc_pid = -1; +} + +static void proxy_stop(struct source *src) +{ + if (src->proc_pid > 0) { + kill(src->proc_pid, SIGTERM); + double deadline = monotonic_now() + 3.0; + int status = 0; + for (;;) { + pid_t w = waitpid(src->proc_pid, &status, WNOHANG); + if (w == src->proc_pid || (w < 0 && errno != EINTR)) + break; + if (monotonic_now() >= deadline) { + kill(src->proc_pid, SIGKILL); + while (waitpid(src->proc_pid, &status, 0) < 0 && errno == EINTR) + ; + break; + } + sleep_secs(0.02); + } + src->proc_pid = -1; + } + if (src->master_fd >= 0) { + close(src->master_fd); + src->master_fd = -1; + } +} + +static bool proxy_start(struct source *src) +{ + char *argv[32]; + char cmd_copy[512]; + int argc = 0; + + const char *ov = getenv("IPAD_ALS_MONITOR_CMD"); + if (ov && *ov) { + snprintf(cmd_copy, sizeof(cmd_copy), "%s", ov); + char *p = cmd_copy; + while (*p && argc < 30) { + while (*p && isspace((unsigned char)*p)) + p++; + if (!*p) + break; + argv[argc++] = p; + while (*p && !isspace((unsigned char)*p)) + p++; + if (*p) + *p++ = '\0'; + } + argv[argc] = NULL; + } else { + argv[argc++] = "monitor-sensor"; + char *hargv[] = { "monitor-sensor", "--help", NULL }; + char hbuf[2048]; + if (run_capture(hargv, 5.0, true, hbuf, sizeof(hbuf)) && + strstr(hbuf, "--light")) + argv[argc++] = "--light"; + argv[argc] = NULL; + } + + int master = posix_openpt(O_RDWR | O_NOCTTY); + if (master < 0) + return false; + if (grantpt(master) != 0 || unlockpt(master) != 0) { + close(master); + return false; + } + char *slave_name = ptsname(master); + if (!slave_name) { + close(master); + return false; + } + int slave = open(slave_name, O_RDWR | O_NOCTTY); + if (slave < 0) { + close(master); + return false; + } + + pid_t pid = fork(); + if (pid < 0) { + close(master); + close(slave); + return false; + } + if (pid == 0) { + close(master); + setsid(); + ioctl(slave, TIOCSCTTY, 0); + int devnull = open("/dev/null", O_RDONLY); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + if (devnull > STDERR_FILENO) + close(devnull); + } + dup2(slave, STDOUT_FILENO); + dup2(slave, STDERR_FILENO); + if (slave > STDERR_FILENO) + close(slave); + execvp(argv[0], argv); + _exit(127); + } + + close(slave); + src->proc_pid = pid; + src->master_fd = master; + src->buf_len = 0; + + char joined[512] = ""; + size_t pos = 0; + for (int i = 0; i < argc; i++) { + int w = snprintf(joined + pos, sizeof(joined) - pos, + "%s%s", i ? " " : "", argv[i]); + if (w > 0 && pos + (size_t)w < sizeof(joined)) + pos += (size_t)w; + } + log_msg("started %s", joined); + return true; +} + +static bool parse_proxy_light_line(const char *text, double *out_lux, + char *out_unit, size_t unit_cap) +{ + /* Pattern 1: Light changed:\s*([-+0-9.eE]+)\s*\((\w+)\) */ + const char *p = strstr(text, "Light changed:"); + if (p) { + p += 14; + while (*p && isspace((unsigned char)*p)) + p++; + char *end = NULL; + double v = strtod(p, &end); + if (end != p && isfinite(v)) { + p = end; + while (*p && isspace((unsigned char)*p)) + p++; + if (*p == '(') { + p++; + const char *u = p; + while (*p && is_ident_char(*p)) + p++; + if (p > u && *p == ')') { + size_t ulen = (size_t)(p - u); + if (ulen >= unit_cap) ulen = unit_cap - 1; + memcpy(out_unit, u, ulen); + out_unit[ulen] = '\0'; + *out_lux = v; + return true; + } + } + } + } + + /* Pattern 2 (case-insensitive): Has ambient light sensor... value:\s*,\s*unit:\s*(\w+) */ + const char *q = NULL; + for (const char *s = text; *s; s++) { + if (strncasecmp(s, "Has ambient light sensor", 24) == 0) { + q = s + 24; + break; + } + } + if (q) { + const char *vp = NULL; + for (const char *s = q; *s; s++) { + if (strncasecmp(s, "value:", 6) == 0) { + vp = s + 6; + break; + } + } + if (vp) { + while (*vp && isspace((unsigned char)*vp)) + vp++; + char *end = NULL; + double v = strtod(vp, &end); + if (end != vp && isfinite(v)) { + const char *up = end; + while (*up && isspace((unsigned char)*up)) + up++; + if (*up == ',') { + up++; + while (*up && isspace((unsigned char)*up)) + up++; + if (strncasecmp(up, "unit:", 5) == 0) { + up += 5; + while (*up && isspace((unsigned char)*up)) + up++; + const char *u = up; + while (*up && is_ident_char(*up)) + up++; + if (up > u) { + size_t ulen = (size_t)(up - u); + if (ulen >= unit_cap) ulen = unit_cap - 1; + memcpy(out_unit, u, ulen); + out_unit[ulen] = '\0'; + *out_lux = v; + return true; + } + } + } + } + } + } + return false; +} + +static bool source_poll(struct source *src, double timeout, double *out_latest) +{ + bool got = false; + if (src->kind == SRC_IIO) { + double wait = src->due - monotonic_now(); + if (wait < 0.0) wait = 0.0; + if (wait > timeout) wait = timeout; + sleep_secs(wait); + if (monotonic_now() < src->due) + return false; + src->due = monotonic_now() + src->interval; + char dev[PATH_MAX]; + double lux = 0.0; + if (!find_iio_light(src->iio_root, dev, sizeof(dev)) || + !read_iio_lux(dev, &lux)) { + if (!src->warned) { + log_msg("no readable IIO light sensor under %s", src->iio_root); + src->warned = true; + } + return false; + } + src->warned = false; + *out_latest = lux; + return true; + } + + if (src->kind == SRC_MOCK) { + if (src->has_pending_lux) { + *out_latest = src->pending_lux; + src->has_pending_lux = false; + got = true; + } + if (src->is_fifo) { + struct pollfd pfd = { .fd = src->fifo_fd, .events = POLLIN }; + if (poll(&pfd, 1, (int)(timeout * 1000.0)) > 0 && (pfd.revents & POLLIN)) { + char chunk[4096]; + ssize_t n = read(src->fifo_fd, chunk, sizeof(chunk)); + if (n > 0) { + for (ssize_t i = 0; i < n; i++) { + if (chunk[i] == '\n') { + src->buf[src->buf_len] = '\0'; + double v = 0.0; + if (parse_lux_line(src->buf, &v)) { + *out_latest = v; + got = true; + } + src->buf_len = 0; + } else if (src->buf_len + 1 < sizeof(src->buf)) { + src->buf[src->buf_len++] = chunk[i]; + } + } + } + } + } else { + sleep_secs(timeout < 0.2 ? timeout : 0.2); + struct stat st; + if (stat(src->mock_path, &st) == 0) { + if (st.st_size < src->offset) + src->offset = 0; + if (st.st_size > src->offset) { + int fd = open(src->mock_path, O_RDONLY); + if (fd >= 0) { + lseek(fd, src->offset, SEEK_SET); + char chunk[4096]; + ssize_t n; + while ((n = read(fd, chunk, sizeof(chunk))) > 0) { + src->offset += n; + for (ssize_t i = 0; i < n; i++) { + if (chunk[i] == '\n') { + src->buf[src->buf_len] = '\0'; + double v = 0.0; + if (parse_lux_line(src->buf, &v)) { + *out_latest = v; + got = true; + } + src->buf_len = 0; + } else if (src->buf_len + 1 < sizeof(src->buf)) { + src->buf[src->buf_len++] = chunk[i]; + } + } + } + if (src->buf_len > 0) { + src->buf[src->buf_len] = '\0'; + double v = 0.0; + if (parse_lux_line(src->buf, &v)) { + *out_latest = v; + got = true; + } + src->buf_len = 0; + } + close(fd); + } + } + } + } + return got; + } + + /* SRC_PROXY */ + if (src->proc_pid <= 0) { + if (monotonic_now() < src->retry_at) { + sleep_secs(timeout); + return false; + } + if (!proxy_start(src)) { + log_msg("cannot start monitor-sensor"); + src->retry_at = monotonic_now() + 5.0; + return false; + } + } + + struct pollfd pfd = { .fd = src->master_fd, .events = POLLIN }; + int r = poll(&pfd, 1, (int)(timeout * 1000.0)); + if (r <= 0) { + int status = 0; + if (waitpid(src->proc_pid, &status, WNOHANG) == src->proc_pid) { + src->proc_pid = -1; + log_msg("monitor-sensor exited; retrying in 3 s"); + proxy_stop(src); + src->retry_at = monotonic_now() + 3.0; + } + return false; + } + + char chunk[4096]; + ssize_t n = read(src->master_fd, chunk, sizeof(chunk)); + if (n <= 0) { + log_msg("monitor-sensor exited; retrying in 3 s"); + proxy_stop(src); + src->retry_at = monotonic_now() + 3.0; + return false; + } + + for (ssize_t i = 0; i < n; i++) { + if (chunk[i] == '\n') { + src->buf[src->buf_len] = '\0'; + char *text = trim_ws(src->buf); + double v = 0.0; + char unit[32]; + if (parse_proxy_light_line(text, &v, unit, sizeof(unit))) { + if (strcasecmp(unit, "lux") != 0) { + log_msg("iio-sensor-proxy reports %s, not lux: ignoring", unit); + } else { + *out_latest = v; + got = true; + } + } else if (*text) { + log_msg("monitor-sensor: %s", text); + } + src->buf_len = 0; + } else if (src->buf_len + 1 < sizeof(src->buf)) { + src->buf[src->buf_len++] = chunk[i]; + } + } + return got; +} + +static void source_close(struct source *src) +{ + if (src->fifo_fd >= 0) { + close(src->fifo_fd); + src->fifo_fd = -1; + } + if (src->kind == SRC_PROXY) + proxy_stop(src); +} + +/* -------------------------------------------------------------------------- + * Daemon + * -------------------------------------------------------------------------- */ + +struct daemon_state { + struct conf conf; + struct source *source; + struct backlight backlight; + bool dry; + bool debug; + + struct smoother smoother; + struct policy policy; + + bool has_latest; + double latest; + double next_sample; + bool has_last_written; + int last_written; + bool has_goal_raw; + int goal_raw; + int ramp_from; + double ramp_start; + double ramp_secs; + double override_until; + bool held; + double settle_until; + bool active; + int moves; + bool has_shown; + double shown; +}; + +static void daemon_init(struct daemon_state *d, const struct conf *c, + struct source *src, const struct backlight *bl, + bool dry, bool debug) +{ + memset(d, 0, sizeof(*d)); + d->conf = *c; + d->source = src; + d->backlight = *bl; + d->dry = dry; + d->debug = debug; + smoother_init(&d->smoother, d->conf.smooth_secs, 3, true, d->conf.smooth_up_secs); + policy_init(&d->policy, &d->conf); +} + +static int daemon_tolerance(const struct daemon_state *d) +{ + int t = (int)llround((double)d->backlight.max * 0.01); + return t > 2 ? t : 2; +} + +static void daemon_pause(struct daemon_state *d, const char *why) +{ + d->has_last_written = false; + d->has_goal_raw = false; + policy_reset(&d->policy); + if (d->active) + log_msg("paused: %s", why); + d->active = false; +} + +static double daemon_perceived(const struct daemon_state *d, int raw) +{ + if (d->backlight.max <= 0) + return 0.0; + double r = raw > 0 ? (double)raw : 0.0; + return pow(r / (double)d->backlight.max, 1.0 / RAMP_GAMMA); +} + +static int daemon_raw_from_perceived(const struct daemon_state *d, double p) +{ + if (p < 0.0) p = 0.0; + int v = (int)llround((double)d->backlight.max * pow(p, RAMP_GAMMA)); + if (v < 1) v = 1; + if (v > d->backlight.max) v = d->backlight.max; + return v; +} + +static void daemon_start_ramp(struct daemon_state *d, int raw, double now) +{ + d->ramp_from = raw; + d->ramp_start = now; + double delta = fabs(daemon_perceived(d, d->goal_raw) - daemon_perceived(d, raw)) * 100.0; + double speed = d->conf.ramp_pct_per_s > 1.0 ? d->conf.ramp_pct_per_s : 1.0; + double secs = delta / speed; + if (secs < RAMP_MIN_SECS) secs = RAMP_MIN_SECS; + if (secs > RAMP_MAX_SECS) secs = RAMP_MAX_SECS; + d->ramp_secs = secs; +} + +static void daemon_step(struct daemon_state *d, int raw, double now) +{ + double t = (d->ramp_secs > 0.0) ? ((now - d->ramp_start) / d->ramp_secs) : 1.0; + if (t > 1.0) t = 1.0; + int next_raw; + if (t >= 1.0) { + next_raw = d->goal_raw; + } else { + double eased = t * t * (3.0 - 2.0 * t); + double p0 = daemon_perceived(d, d->ramp_from); + double p1 = daemon_perceived(d, d->goal_raw); + next_raw = daemon_raw_from_perceived(d, p0 + (p1 - p0) * eased); + } + if (next_raw == raw) { + if (t >= 1.0) { + d->has_goal_raw = false; + d->has_last_written = true; + d->last_written = raw; + } + return; + } + if (d->dry) { + log_msg("would set brightness %d of %d (dry run)", next_raw, d->backlight.max); + d->has_goal_raw = false; + return; + } + if (backlight_write(&d->backlight, next_raw, true, raw)) { + d->has_last_written = true; + d->last_written = next_raw; + d->moves++; + if (next_raw == d->goal_raw) + d->has_goal_raw = false; + } else { + d->has_goal_raw = false; + } +} + +static void daemon_write_status(struct daemon_state *d, double now, + bool enabled, double override_left) +{ + if (d->has_shown && now - d->shown < 1.0) + return; + d->has_shown = true; + d->shown = now; + + char path[PATH_MAX]; + char tmp[PATH_MAX + 16]; + get_status_path(path, sizeof(path)); + snprintf(tmp, sizeof(tmp), "%s.tmp", path); + + FILE *f = fopen(tmp, "w"); + if (!f) + return; + + int raw = 0; + bool has_raw = backlight_read(&d->backlight, &raw); + fprintf(f, "{\"pid\": %ld, \"source\": \"%s\", \"enabled\": %s, \"backlight\": \"%s\", ", + (long)getpid(), + d->source ? d->source->kind_name : "test", + enabled ? "true" : "false", + d->backlight.name); + if (has_raw) + fprintf(f, "\"brightness_pct\": %.1f, ", backlight_pct(&d->backlight, raw)); + else + fprintf(f, "\"brightness_pct\": null, "); + if (d->has_latest) + fprintf(f, "\"lux\": %.6g, ", d->latest); + else + fprintf(f, "\"lux\": null, "); + if (d->smoother.has_level) + fprintf(f, "\"smoothed_lux\": %.1f, ", smoother_lux(&d->smoother)); + else + fprintf(f, "\"smoothed_lux\": null, "); + fprintf(f, "\"hold\": [%s], \"override_secs_left\": %.1f, \"moves\": %d, \"time\": %.6f}", + d->held ? "\"powerd\"" : "", + override_left, + d->moves, + realtime_now()); + + if (fclose(f) == 0) + rename(tmp, path); + else + unlink(tmp); +} + +static void daemon_tick(struct daemon_state *d, double now, bool check_holds) +{ + if (!is_enabled(&d->conf)) { + daemon_pause(d, "off"); + daemon_write_status(d, now, false, 0.0); + return; + } + bool hold = (d->dry || !check_holds) ? false : has_powerd_hold(); + if (hold != d->held) { + if (hold) + log_msg("holding for powerd"); + else if (d->held) + d->settle_until = now + HOLD_SETTLE; + d->held = hold; + } + if (hold || now < d->settle_until) { + daemon_pause(d, "hold"); + daemon_write_status(d, now, true, 0.0); + return; + } + int raw = 0; + if (!backlight_read(&d->backlight, &raw)) + return; + if (d->has_last_written && abs(raw - d->last_written) > daemon_tolerance(d)) { + d->override_until = now + d->conf.override_secs; + log_msg("brightness changed by hand (%.0f -> %.0f %%): paused for %.0f s", + backlight_pct(&d->backlight, d->last_written), + backlight_pct(&d->backlight, raw), + d->conf.override_secs); + daemon_pause(d, "manual change"); + } + if (now < d->override_until) { + daemon_write_status(d, now, true, d->override_until - now); + return; + } + if (!d->active) { + d->active = true; + log_msg("auto-brightness on"); + } + if (d->has_latest && now >= d->next_sample) { + double hz = d->conf.poll_hz > 0.5 ? d->conf.poll_hz : 0.5; + d->next_sample = now + 1.0 / hz; + smoother_feed(&d->smoother, d->latest * d->conf.lux_scale, now); + double goal = 0.0; + bool move = policy_decide(&d->policy, d->smoother.level, + smoother_lux(&d->smoother), + now, backlight_pct(&d->backlight, raw), &goal); + if (d->debug) { + if (move) + log_msg("lux %.1f smoothed %.1f -> %.0f %%", + d->latest * d->conf.lux_scale, + smoother_lux(&d->smoother), goal); + else + log_msg("lux %.1f smoothed %.1f -> stay", + d->latest * d->conf.lux_scale, + smoother_lux(&d->smoother)); + } + if (move) { + d->goal_raw = backlight_raw_for(&d->backlight, goal); + d->has_goal_raw = true; + daemon_start_ramp(d, raw, now); + log_msg("lux %.0f: brightness %.0f %% -> %.0f %% over %.2f s", + smoother_lux(&d->smoother), + backlight_pct(&d->backlight, raw), goal, d->ramp_secs); + } + } + if (d->has_goal_raw) + daemon_step(d, raw, now); + daemon_write_status(d, now, true, 0.0); +} + +static void daemon_run(struct daemon_state *d, bool has_seconds, double seconds) +{ + double end = has_seconds ? (monotonic_now() + seconds) : 0.0; + log_msg("source %s, backlight %s (max %d)%s%s", + d->source->kind_name, d->backlight.name, d->backlight.max, + d->dry ? ", dry run" : "", + is_enabled(&d->conf) ? "" : "; off until switched on"); + + const char *comp_env = getenv("LABWC_PID"); + pid_t compositor = comp_env ? (pid_t)strtol(comp_env, NULL, 10) : 0; + + while (!g_stop && (!has_seconds || monotonic_now() < end)) { + if (g_reload) { + g_reload = 0; + load_conf(&d->conf); + d->smoother.tau = d->conf.smooth_secs > 0.0 ? d->conf.smooth_secs : 0.0; + d->smoother.tau_up = d->conf.smooth_up_secs > 0.0 ? d->conf.smooth_up_secs : 0.0; + } + if (compositor > 0 && kill(compositor, 0) < 0 && errno == ESRCH) + break; + if (!is_enabled(&d->conf)) { + daemon_tick(d, monotonic_now(), true); + sleep_secs(1.0); + continue; + } + double lux = 0.0; + if (source_poll(d->source, d->has_goal_raw ? RAMP_TICK_SECS : TICK_SECS, &lux)) { + d->latest = lux; + d->has_latest = true; + } + daemon_tick(d, monotonic_now(), true); + } + + source_close(d->source); + char path[PATH_MAX]; + get_status_path(path, sizeof(path)); + unlink(path); +} + +/* -------------------------------------------------------------------------- + * CLI subcommands + * -------------------------------------------------------------------------- */ + +static pid_t running_pid(void) +{ + char path[PATH_MAX]; + get_status_path(path, sizeof(path)); + FILE *f = fopen(path, "r"); + if (!f) + return 0; + char buf[1024]; + size_t n = fread(buf, 1, sizeof(buf) - 1, f); + fclose(f); + buf[n] = '\0'; + + char *p = strstr(buf, "\"pid\""); + if (!p) + return 0; + p = strchr(p, ':'); + if (!p) + return 0; + long pid = strtol(p + 1, NULL, 10); + if (pid <= 0) + return 0; + if (kill((pid_t)pid, 0) < 0 && errno == ESRCH) + return 0; + return (pid_t)pid; +} + +static int cmd_switch(const char *action, const struct conf *c) +{ + bool now = is_enabled(c); + bool want = (strcmp(action, "toggle") == 0) ? !now : (strcmp(action, "on") == 0); + set_state_value("auto_brightness", want ? "on" : "off"); + printf("auto-brightness %s\n", want ? "on" : "off"); + if (want && !running_pid()) + fprintf(stderr, "note: the daemon isn't running (no ambient light sensor, or not logged in yet)\n"); + return 0; +} + +static int cmd_status(const struct conf *c) +{ + pid_t pid = running_pid(); + if (pid) + printf("auto-brightness: %s | daemon: running (pid %ld)\n", + is_enabled(c) ? "on" : "off", (long)pid); + else + printf("auto-brightness: %s | daemon: not running\n", + is_enabled(c) ? "on" : "off"); + if (pid) { + char path[PATH_MAX]; + get_status_path(path, sizeof(path)); + FILE *f = fopen(path, "r"); + if (f) { + char buf[2048]; + size_t n = fread(buf, 1, sizeof(buf) - 1, f); + fclose(f); + buf[n] = '\0'; + printf("%s\n", buf); + } + } + return pid ? 0 : 1; +} + +static void cmd_list(const char *mock_iio, const struct conf *c) +{ + if (which_cmd("busctl")) + printf("iio-sensor-proxy HasAmbientLight: %s\n", proxy_has_light() ? "True" : "False"); + else + printf("iio-sensor-proxy HasAmbientLight: no busctl\n"); + printf("monitor-sensor: %s\n", have_monitor_sensor() ? "found" : "missing"); + + char dev[PATH_MAX]; + if (find_iio_light(mock_iio ? mock_iio : IIO_ROOT, dev, sizeof(dev))) { + printf("IIO light sensor: %s\n", dev); + double lux = 0.0; + if (read_iio_lux(dev, &lux)) + printf(" lux: %g\n", lux); + else + printf(" lux: None\n"); + } else { + printf("IIO light sensor: none\n"); + } + + char bname[128]; + if (find_backlight(c->backlight, bname, sizeof(bname))) { + printf("backlight: %s\n", bname); + struct backlight bl; + backlight_init(&bl, bname); + int raw = 0; + if (backlight_read(&bl, &raw)) + printf(" brightness %d of %d (%.0f %%)\n", raw, bl.max, backlight_pct(&bl, raw)); + else + printf(" brightness None of %d\n", bl.max); + } else { + printf("backlight: none\n"); + } + + char reply[64]; + bool got = power_request("als-state", reply, sizeof(reply)); + printf("powerd: %s\n", (got && reply[0]) ? reply : "unavailable"); + printf("auto-brightness: %s\n", is_enabled(c) ? "on" : "off"); +} + +/* -------------------------------------------------------------------------- + * Unit-test harness (--test) + * -------------------------------------------------------------------------- */ + +static int run_test_mode(void) +{ + struct conf c; + load_conf(&c); + struct smoother sm; + smoother_init(&sm, 0.0, 3, false, 0.0); + struct policy pol; + policy_init(&pol, &c); + struct backlight bl; + memset(&bl, 0, sizeof(bl)); + struct daemon_state d; + memset(&d, 0, sizeof(d)); + + 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, "curve_pct ", 10) == 0) { + double lux = strtod(line + 10, NULL); + printf("VAL %.9f\n", curve_pct(c.curve_points, c.curve_count, lux)); + } else if (strncmp(line, "smoother_init ", 14) == 0) { + double tau = 0.0, tau_up = 0.0; + int has_up = 0; + sscanf(line + 14, "%lf %d %lf", &tau, &has_up, &tau_up); + smoother_init(&sm, tau, 3, has_up != 0, tau_up); + printf("OK\n"); + } else if (strncmp(line, "smoother_feed ", 14) == 0) { + double lux = 0.0, now = 0.0; + sscanf(line + 14, "%lf %lf", &lux, &now); + smoother_feed(&sm, lux, now); + printf("VAL %.9f\n", smoother_lux(&sm)); + } else if (strcmp(line, "policy_reset") == 0) { + policy_init(&pol, &c); + printf("OK\n"); + } else if (strncmp(line, "policy_state ", 13) == 0) { + double ref = 0.0, last = 0.0; + sscanf(line + 13, "%lf %lf", &ref, &last); + pol.has_ref_level = true; + pol.ref_level = ref; + pol.last_move = last; + printf("OK\n"); + } else if (strncmp(line, "policy_decide ", 14) == 0) { + double lux = 0.0, now = 0.0, cur = 0.0; + sscanf(line + 14, "%lf %lf %lf", &lux, &now, &cur); + double goal = 0.0; + if (policy_decide(&pol, log1p(lux), lux, now, cur, &goal)) + printf("VAL %.9f\n", goal); + else + printf("NONE\n"); + } else if (strcmp(line, "holds") == 0) { + printf("VAL %s\n", has_powerd_hold() ? "powerd" : ""); + } else if (strncmp(line, "bl_write ", 9) == 0) { + char name[128]; + int raw = 0, exp = 0; + if (sscanf(line + 9, "%127s %d %d", name, &raw, &exp) == 3) { + backlight_init(&bl, name); + printf("VAL %d\n", backlight_write(&bl, raw, true, exp) ? 1 : 0); + } else { + printf("ERR\n"); + } + } else if (strncmp(line, "override_test ", 14) == 0) { + char name[128]; + int last_w = 0; + double latest = 0.0, now = 0.0; + sscanf(line + 14, "%127s %d %lf %lf", name, &last_w, &latest, &now); + load_conf(&c); + c.enabled = true; + backlight_init(&bl, name); + daemon_init(&d, &c, NULL, &bl, false, false); + d.has_last_written = true; + d.last_written = last_w; + d.has_latest = true; + d.latest = latest; + daemon_tick(&d, now, false); + printf("VAL %.9f %d\n", d.override_until, d.moves); + } else if (strncmp(line, "ramp_test ", 10) == 0) { + char name[128]; + int start_raw = 0, goal_raw = 0; + sscanf(line + 10, "%127s %d %d", name, &start_raw, &goal_raw); + load_conf(&c); + c.enabled = true; + backlight_init(&bl, name); + daemon_init(&d, &c, NULL, &bl, false, false); + d.has_goal_raw = true; + d.goal_raw = goal_raw; + daemon_start_ramp(&d, start_raw, 0.0); + printf("RAMP %.9f\n", d.ramp_secs); + double t = 0.0; + int cur = start_raw; + while (d.has_goal_raw && t < 10.0) { + double tt = (d.ramp_secs > 0.0) ? (t / d.ramp_secs) : 1.0; + if (tt > 1.0) tt = 1.0; + int next_raw; + if (tt >= 1.0) { + next_raw = d.goal_raw; + } else { + double eased = tt * tt * (3.0 - 2.0 * tt); + double p0 = daemon_perceived(&d, d.ramp_from); + double p1 = daemon_perceived(&d, d.goal_raw); + next_raw = daemon_raw_from_perceived(&d, p0 + (p1 - p0) * eased); + } + if (next_raw != cur) { + cur = next_raw; + printf("STEP %d %.9f\n", cur, daemon_perceived(&d, cur)); + if (cur == d.goal_raw) + d.has_goal_raw = false; + } else if (tt >= 1.0) { + d.has_goal_raw = false; + } + t += RAMP_TICK_SECS; + } + printf("DONE\n"); + } else { + printf("ERR\n"); + } + fflush(stdout); + } + return 0; +} + +/* -------------------------------------------------------------------------- + * Main entry point + * -------------------------------------------------------------------------- */ + +int main(int argc, char **argv) +{ + if (argc > 1 && strcmp(argv[1], "--test") == 0) + return run_test_mode(); + + const char *command = "daemon"; + const char *source_arg = NULL; + const char *mock_path = NULL; + const char *mock_iio = NULL; + bool dry_run = false; + bool has_probe = false; + double probe_secs = 20.0; + bool do_list = false; + bool debug = false; + + for (int i = 1; i < argc; i++) { + const char *a = argv[i]; + if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) { + printf("%s\n", USAGE_DOC); + return 0; + } else if (strcmp(a, "--dry-run") == 0) { + dry_run = true; + } else if (strcmp(a, "--list") == 0) { + do_list = true; + } else if (strcmp(a, "--debug") == 0) { + debug = true; + } else if (strcmp(a, "--source") == 0 && i + 1 < argc) { + source_arg = argv[++i]; + } else if (strcmp(a, "--mock") == 0 && i + 1 < argc) { + mock_path = argv[++i]; + } else if (strcmp(a, "--mock-iio") == 0 && i + 1 < argc) { + mock_iio = argv[++i]; + } else if (strcmp(a, "--probe") == 0) { + has_probe = true; + if (i + 1 < argc && argv[i + 1][0] != '-') { + char *end = NULL; + double v = strtod(argv[i + 1], &end); + if (end != argv[i + 1] && *end == '\0' && isfinite(v)) { + probe_secs = v; + i++; + } + } + } else if (a[0] != '-') { + command = a; + } else { + fprintf(stderr, "Unknown option: %s\n", a); + return 2; + } + } + + if (strcmp(command, "daemon") != 0 && strcmp(command, "on") != 0 && + strcmp(command, "off") != 0 && strcmp(command, "toggle") != 0 && + strcmp(command, "status") != 0 && strcmp(command, "enabled") != 0 && + strcmp(command, "available") != 0) { + fprintf(stderr, "Unknown command: %s\n", command); + return 2; + } + + struct conf c; + load_conf(&c); + if (!source_arg) { + const char *env_src = getenv("IPAD_ALS_SOURCE"); + source_arg = (env_src && *env_src) ? env_src : "auto"; + } + + if (do_list) { + cmd_list(mock_iio, &c); + return 0; + } + if (strcmp(command, "on") == 0 || strcmp(command, "off") == 0 || + strcmp(command, "toggle") == 0) + return cmd_switch(command, &c); + if (strcmp(command, "status") == 0) + return cmd_status(&c); + if (strcmp(command, "enabled") == 0) + return is_enabled(&c) ? 0 : 1; + if (strcmp(command, "available") == 0) { + char bname[128]; + return (find_iio_light(mock_iio ? mock_iio : IIO_ROOT, NULL, 0) && + find_backlight(c.backlight, bname, sizeof(bname))) ? 0 : 1; + } + + if (has_probe) { + dry_run = true; + debug = true; + g_force_enabled = true; + } + + char bname[128]; + if (!find_backlight(c.backlight, bname, sizeof(bname))) { + log_msg("no backlight under %s", backlight_root()); + if (has_probe) + return 1; + const char *comp_env = getenv("LABWC_PID"); + pid_t compositor = comp_env ? (pid_t)strtol(comp_env, NULL, 10) : 0; + while (!find_backlight(c.backlight, bname, sizeof(bname))) { + if (compositor > 0 && kill(compositor, 0) < 0 && errno == ESRCH) + return 0; + sleep_secs(1.0); + } + } + + struct source src; + const char *root = mock_iio ? mock_iio : IIO_ROOT; + if (mock_path) { + if (!source_init_mock(&src, mock_path)) { + perror(mock_path); + return 1; + } + } else if (mock_iio || strcmp(source_arg, "iio") == 0) { + source_init_iio(&src, root, c.poll_hz); + } else if (strcmp(source_arg, "proxy") == 0) { + source_init_proxy(&src); + } else { + bool announced = false; + const char *disc_env = getenv("IPAD_ALS_DISCOVERY_SECS"); + double disc_secs = (disc_env && *disc_env) ? strtod(disc_env, NULL) : 15.0; + double deadline = monotonic_now() + disc_secs; + for (;;) { + if (have_monitor_sensor() && proxy_has_light()) { + source_init_proxy(&src); + break; + } + if (find_iio_light(root, NULL, 0)) { + source_init_iio(&src, root, c.poll_hz); + break; + } + if (has_probe) { + log_msg("no ambient light sensor: iio-sensor-proxy has none and there is no IIO device"); + return 1; + } + if (monotonic_now() >= deadline) { + log_msg("no ambient light sensor after discovery window; exiting"); + return 0; + } + if (!announced) { + log_msg("no ambient light sensor yet (iio-sensor-proxy has none, no IIO device); waiting"); + announced = true; + } + sleep_secs(3.0); + } + } + + struct backlight bl; + backlight_init(&bl, bname); + struct daemon_state d; + daemon_init(&d, &c, &src, &bl, dry_run, debug); + + struct sigaction sa_stop, sa_reload; + memset(&sa_stop, 0, sizeof(sa_stop)); + sa_stop.sa_handler = handle_stop; + sigaction(SIGTERM, &sa_stop, NULL); + sigaction(SIGINT, &sa_stop, NULL); + memset(&sa_reload, 0, sizeof(sa_reload)); + sa_reload.sa_handler = handle_reload; + sigaction(SIGHUP, &sa_reload, NULL); + + daemon_run(&d, has_probe, probe_secs); + return 0; +} diff --git a/desktop/install-tree b/desktop/install-tree index 7252f9c5..339db879 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/arch-ipad-rotate-output" "$build/omarchy-keyboard" "$build/omarchy-powerctl" "$build/omarchy-mute-switch" "$build/omarchy-powerd" "$upstream/themes" "$upstream/bin" \ +for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/arch-ipad-auto-brightness" "$build/arch-ipad-rotate-output" "$build/omarchy-keyboard" "$build/omarchy-powerctl" "$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" \ @@ -108,7 +108,8 @@ for set in "$omarchy"/icons/*/; do done # The keyboard, its controller, the startup cursor helper, the power daemon, -# the rotation daemon, and the power-control and hardware mute-switch helpers. +# the rotation and auto-brightness daemons, and the power-control and +# hardware mute-switch helpers. put "$build/wvkbd-mobintl" "$omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state" 755 put "$build/omarchy-keyboard" "$omarchy/bin/omarchy-keyboard" 755 put "$build/wtype" "$root/usr/libexec/omarchy-wtype" 755 @@ -117,6 +118,7 @@ put "$build/omarchy-powerd" "$root/usr/libexec/omarchy-powerd" 755 put "$build/omarchy-mute-switch" "$root/usr/libexec/omarchy-mute-switch" 755 put "$build/omarchy-powerctl" "$root/usr/libexec/omarchy-powerctl" 755 put "$build/arch-ipad-rotate-output" "$root/usr/libexec/arch-ipad-rotate-output" 755 +put "$build/arch-ipad-auto-brightness" "$root/usr/libexec/arch-ipad-auto-brightness" 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 @@ -174,7 +176,6 @@ $shell/applications/org.omarchy.settings.desktop usr/share/applications/org.omar $shell/applications/org.omarchy.settings.svg usr/share/icons/hicolor/scalable/apps/org.omarchy.settings.svg 644 $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/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 aac0fc8e..c564d02c 100644 --- a/release/audit.py +++ b/release/audit.py @@ -22,6 +22,7 @@ 'usr/libexec/omarchy-powerctl': 'power control client', 'usr/share/omarchy/bin/omarchy-keyboard': 'on-screen keyboard controller', 'usr/libexec/arch-ipad-rotate-output': 'screen rotation daemon', + 'usr/libexec/arch-ipad-auto-brightness': 'ambient-light auto-brightness 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 3eab6ed9..4fae242e 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', 'omarchy-mute-switch', 'omarchy-powerctl', 'omarchy-keyboard', 'arch-ipad-rotate-output'): + for name in ('wvkbd-mobintl', 'wtype', 'omarchy-powerd', 'omarchy-mute-switch', 'omarchy-powerctl', 'omarchy-keyboard', 'arch-ipad-rotate-output', 'arch-ipad-auto-brightness'): (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_auto_brightness.py b/tests/test_auto_brightness.py index 247bae35..4d95e2c0 100644 --- a/tests/test_auto_brightness.py +++ b/tests/test_auto_brightness.py @@ -1,106 +1,224 @@ -"""Ported ALS policy and power-daemon cooperation, with no hardware access.""" -import importlib.machinery -import importlib.util +"""Ported ALS policy and power-daemon cooperation, tested against the C99 binary.""" +import atexit +import functools import math import os from pathlib import Path +import shutil +import socket +import subprocess import tempfile +import threading import unittest -from unittest.mock import patch PROJECT = Path(__file__).resolve().parents[1] -loader = importlib.machinery.SourceFileLoader('auto_brightness', str(PROJECT/'desktop/configuration/auto-brightness')) -spec = importlib.util.spec_from_loader(loader.name, loader) -a = importlib.util.module_from_spec(spec); loader.exec_module(a) +SOURCE = PROJECT / 'desktop/configuration/auto-brightness.c' + + +@functools.lru_cache(maxsize=1) +def compiled_binary(): + tmp = Path(tempfile.mkdtemp(prefix='omarchy-auto-brightness-test-')) + atexit.register(shutil.rmtree, tmp, True) + binary = tmp / 'arch-ipad-auto-brightness' + 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() + + +class MockPowerd: + """Minimal Unix-socket powerd stand-in recording requests and replying.""" + + def __init__(self, path, reply='lit'): + self.path = str(path) + self.reply = reply + self.requests = [] + self._stop = False + self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._sock.bind(self.path) + self._sock.listen(5) + self._sock.settimeout(0.05) + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def _serve(self): + while not self._stop: + try: + conn, _ = self._sock.accept() + except socket.timeout: + continue + except OSError: + break + with conn: + data = conn.recv(256).decode().strip() + self.requests.append(data) + if self.reply: + conn.sendall((self.reply + '\n').encode()) + + def close(self): + self._stop = True + self._sock.close() + self._thread.join(timeout=2) + class AutoBrightness(unittest.TestCase): def setUp(self): - temp = tempfile.TemporaryDirectory(); self.addCleanup(temp.cleanup) - self.root = Path(temp.name); self.panel = self.root/'backlight/panel'; self.panel.mkdir(parents=True) - (self.panel/'max_brightness').write_text('1000\n'); self.set_raw(500) - self.env = patch.dict(os.environ, {'XDG_CONFIG_HOME':str(self.root/'config'), - 'XDG_STATE_HOME':str(self.root/'state'), 'XDG_RUNTIME_DIR':str(self.root), - 'IPAD_ALS_BACKLIGHT_ROOT':str(self.root/'backlight')}) - self.env.start(); self.addCleanup(self.env.stop) - self.conf = a.load_conf() + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.panel = self.root / 'backlight/panel' + self.panel.mkdir(parents=True) + (self.panel / 'max_brightness').write_text('1000\n') + self.set_raw(500) + self.sock_path = self.root / 'powerd.sock' + self.env = { + **os.environ, + 'XDG_CONFIG_HOME': str(self.root / 'config'), + 'XDG_STATE_HOME': str(self.root / 'state'), + 'XDG_RUNTIME_DIR': str(self.root), + 'IPAD_ALS_BACKLIGHT_ROOT': str(self.root / 'backlight'), + 'IPAD_ALS_POWER_SOCKET': str(self.sock_path), + } + + def set_raw(self, value): + (self.panel / 'brightness').write_text(str(value) + '\n') - def set_raw(self, value): (self.panel/'brightness').write_text(str(value)+'\n') + def run_cli(self, *args): + return subprocess.run( + [str(compiled_binary()), *args], + env=self.env, + capture_output=True, + text=True, + timeout=5, + ) + + def run_harness(self, *commands): + res = subprocess.run( + [str(compiled_binary()), '--test'], + input='\n'.join(commands) + '\n', + env=self.env, + capture_output=True, + text=True, + check=True, + timeout=5, + ) + return res.stdout.splitlines() def test_default_off_and_persisted_switch(self): - self.assertFalse(a.is_enabled(self.conf)) - a.set_state('auto_brightness','on'); self.assertTrue(a.is_enabled(self.conf)) - a.set_state('auto_brightness','off'); self.assertFalse(a.is_enabled(self.conf)) + self.assertEqual(self.run_cli('enabled').returncode, 1) + self.assertEqual(self.run_cli('on').returncode, 0) + self.assertEqual(self.run_cli('enabled').returncode, 0) + self.assertEqual(self.run_cli('off').returncode, 0) + self.assertEqual(self.run_cli('enabled').returncode, 1) def test_curve_and_median_ignore_one_spike(self): - points = a.parse_curve(a.DEFAULT_CURVE) - self.assertEqual(a.curve_pct(points, 80), 58) - self.assertEqual(a.curve_pct(points, 100000), 100) - smooth = a.Smoother(0) - for i, lux in enumerate((20,20,20,20000,20)): smooth.feed(lux,float(i)) - self.assertAlmostEqual(smooth.lux,20) + out = self.run_harness( + 'curve_pct 80', + 'curve_pct 100000', + 'smoother_init 0 0 0', + 'smoother_feed 20 0', + 'smoother_feed 20 1', + 'smoother_feed 20 2', + 'smoother_feed 20000 3', + 'smoother_feed 20 4', + ) + self.assertAlmostEqual(float(out[0].split()[1]), 58.0) + self.assertAlmostEqual(float(out[1].split()[1]), 100.0) + self.assertAlmostEqual(float(out[-1].split()[1]), 20.0) def test_brightening_is_fast_and_darkening_slow(self): # Hands-on test 2026-11-08: a flashlight took seconds to register, then moved in steps. - up=a.Smoother(3.0,tau_up=0.4); down=a.Smoother(3.0,tau_up=0.4) - for t in (0.0,0.25,0.5): up.feed(20,t); down.feed(2000,t) - for t in (0.75,1.0,1.25,1.5): up.feed(2000,t); down.feed(20,t) - self.assertGreater(up.lux,800) # most of the way within ~1 s of a flashlight - self.assertGreater(down.lux,300) # a shadow does not dim at once - policy=a.Policy(self.conf); policy.ref_level=0.0; policy.last_move=10.0 - class S: level=math.log1p(1000); lux=1000 - self.assertIsNotNone(policy.decide(S,10.3,30.0)) # brighter: 0.25 s spacing - policy.last_move=10.0 - class D: level=math.log1p(0.5); lux=0.5 - policy.ref_level=math.log1p(1000) - self.assertIsNone(policy.decide(D,10.3,90.0)) # darker: keeps the 2 s spacing + up_out = self.run_harness( + 'smoother_init 3.0 1 0.4', + *[f'smoother_feed 20 {t}' for t in (0.0, 0.25, 0.5)], + *[f'smoother_feed 2000 {t}' for t in (0.75, 1.0, 1.25, 1.5)], + ) + down_out = self.run_harness( + 'smoother_init 3.0 1 0.4', + *[f'smoother_feed 2000 {t}' for t in (0.0, 0.25, 0.5)], + *[f'smoother_feed 20 {t}' for t in (0.75, 1.0, 1.25, 1.5)], + ) + self.assertGreater(float(up_out[-1].split()[1]), 800) # most of the way within ~1 s of a flashlight + self.assertGreater(float(down_out[-1].split()[1]), 300) # a shadow does not dim at once + + pol_out = self.run_harness( + 'policy_reset', + 'policy_state 0.0 10.0', + 'policy_decide 1000 10.3 30.0', + f'policy_state {math.log1p(1000):.9f} 10.0', + 'policy_decide 0.5 10.3 90.0', + ) + self.assertTrue(pol_out[2].startswith('VAL ')) # brighter: 0.25 s spacing + self.assertEqual(pol_out[4], 'NONE') # darker: keeps the 2 s spacing def test_powerd_missing_or_dark_is_a_hold(self): - for reply in ('','dark'): - with patch.object(a,'power_request',return_value=reply): self.assertEqual(a.holds(),['powerd']) - with patch.object(a,'power_request',return_value='lit'): self.assertEqual(a.holds(),[]) + # Missing socket -> hold + self.assertEqual(self.run_harness('holds'), ['VAL powerd']) + # Dark reply -> hold + dark = MockPowerd(self.sock_path, reply='dark') + try: + self.assertEqual(self.run_harness('holds'), ['VAL powerd']) + finally: + dark.close() + self.sock_path.unlink(missing_ok=True) + # Lit reply -> no hold + lit = MockPowerd(self.sock_path, reply='lit') + try: + self.assertEqual(self.run_harness('holds'), ['VAL ']) + finally: + lit.close() def test_automatic_write_is_compare_and_set_through_powerd(self): - panel=a.Backlight('panel') - with patch.object(a,'power_request',return_value='ok') as request: - self.assertTrue(panel.write(600,expected=500)) - request.assert_called_once_with('brightness panel 600 500') - for raw in (0,501): - self.set_raw(raw) - with patch.object(a,'power_request') as request: - self.assertFalse(panel.write(600,expected=500)); request.assert_not_called() + srv = MockPowerd(self.sock_path, reply='ok') + try: + self.assertEqual(self.run_harness('bl_write panel 600 500'), ['VAL 1']) + self.assertEqual(srv.requests, ['brightness panel 600 500']) + for raw in (0, 501): + self.set_raw(raw) + self.assertEqual(self.run_harness('bl_write panel 600 500'), ['VAL 0']) + self.assertEqual(len(srv.requests), 1) + finally: + srv.close() def test_hysteresis_and_manual_override(self): - panel=a.Backlight('panel'); self.conf['enabled']=True - daemon=a.Daemon(self.conf,type('Source',(),{'kind':'test'})(),panel,False,False) - daemon.last_written=500; self.set_raw(300); daemon.latest=1500 - with patch.object(a,'holds',return_value=[]), patch.object(panel,'write') as write: - daemon.tick(10.0) - self.assertGreater(daemon.override_until,10.0); write.assert_not_called() + self.set_raw(300) + out = self.run_harness('override_test panel 500 1500 10.0') + _, override_until, moves = out[0].split() + self.assertGreater(float(override_until), 10.0) + self.assertEqual(int(moves), 0) def test_ramp_is_a_smooth_perceptual_fade(self): - panel=a.Backlight('panel'); self.conf['enabled']=True - daemon=a.Daemon(self.conf,type('Source',(),{'kind':'test'})(),panel,False,False) - self.set_raw(100); daemon.goal_raw=800; daemon.start_ramp(100,0.0) - self.assertGreaterEqual(daemon.ramp_secs,a.RAMP_MIN_SECS); self.assertLessEqual(daemon.ramp_secs,a.RAMP_MAX_SECS) - written=[] - def fake_write(new,expected=None): - self.assertEqual(expected,int((self.panel/'brightness').read_text())); self.set_raw(new); written.append(new); return True - with patch.object(panel,'write',side_effect=fake_write): - t=0.0 - while daemon.ramping() and t<10: - daemon.step(int((self.panel/'brightness').read_text()),t); t+=a.RAMP_TICK - self.assertEqual(written[-1],800); self.assertFalse(daemon.ramping()) - self.assertEqual(written,sorted(written)) # monotonic, no overshoot - self.assertGreater(len(written),10) # a fade of many small steps, not a few jumps - p=[daemon.perceived(w) for w in [100]+written] - steps=[b-c for c,b in zip(p,p[1:])] - self.assertLess(max(steps),0.08) # no single step brighter than ~8% perceived - self.assertLess(steps[0],max(steps)) # eased in: starts gentler than the middle + self.set_raw(100) + out = self.run_harness('ramp_test panel 100 800') + ramp_secs = float(out[0].split()[1]) + self.assertGreaterEqual(ramp_secs, 0.3) + self.assertLessEqual(ramp_secs, 3.0) + written = [] + perceived = [pow(100 / 1000.0, 1.0 / 2.2)] + for line in out[1:]: + if line.startswith('STEP '): + _, raw_s, p_s = line.split() + written.append(int(raw_s)) + perceived.append(float(p_s)) + self.assertEqual(written[-1], 800) + self.assertEqual(written, sorted(written)) # monotonic, no overshoot + self.assertGreater(len(written), 10) # a fade of many small steps, not a few jumps + steps = [b - c for c, b in zip(perceived, perceived[1:])] + self.assertLess(max(steps), 0.08) # no single step brighter than ~8% perceived + self.assertLess(steps[0], max(steps)) # eased in: starts gentler than the middle def test_the_package_stages_the_helper_and_the_session_starts_it(self): - install=(PROJECT/'desktop/install-tree').read_text() - self.assertIn('$config/auto-brightness usr/libexec/arch-ipad-auto-brightness 755',install) - self.assertIn('exec /usr/libexec/arch-ipad-auto-brightness',(PROJECT/'desktop/shell/bin/omarchy-auto-brightness').read_text()) - self.assertIn('/usr/libexec/arch-ipad-auto-brightness',(PROJECT/'desktop/shell/default/labwc/autostart').read_text()) + install = (PROJECT / 'desktop/install-tree').read_text() + self.assertIn('put "$build/arch-ipad-auto-brightness" "$root/usr/libexec/arch-ipad-auto-brightness" 755', install) + self.assertIn('exec /usr/libexec/arch-ipad-auto-brightness', (PROJECT / 'desktop/shell/bin/omarchy-auto-brightness').read_text()) + self.assertIn('/usr/libexec/arch-ipad-auto-brightness', (PROJECT / 'desktop/shell/default/labwc/autostart').read_text()) + -if __name__=='__main__': unittest.main() +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_package.py b/tests/test_package.py index f06571f7..a15d262f 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -381,6 +381,7 @@ def test_the_compiled_helpers_are_of_the_roots_architecture(self): 'usr/libexec/omarchy-powerctl', 'usr/share/omarchy/bin/omarchy-keyboard', 'usr/libexec/arch-ipad-rotate-output', + 'usr/libexec/arch-ipad-auto-brightness', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state'}) from release.architecture import check_elf check_elf(elf('aarch64'), 'aarch64')