diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index afb0864e..3972bcd1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -152,7 +152,12 @@ jobs: run: bash ci/dependencies --tools-only env: ORCHARD_REF: main + # powerd talks to logind through sd-bus; its tests build it with + # libsystemd as the package does and run it against a private bus. + - run: pkg-config --exists libsystemd || { sudo apt-get update && sudo apt-get install -y libsystemd-dev; } - run: .venv/bin/python -m unittest discover -s tests -v + env: + OMARCHY_TEST_REQUIRE_SD_BUS: '1' supported-devices: # The README's chips and devices (between its supported markers) follow # orchard main's compatibility table. Checked for every nightly and diff --git a/CHANGELOG.md b/CHANGELOG.md index ad59d79b..1f50902e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,10 @@ release is checked here and released on by hand. ### Desktop +- The power, lock and sleep daemon is a small C program instead of Python: + about 18 MiB more free memory on every board, with the same behaviour + (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 02f07514..7c9a4604 100644 --- a/Makefile +++ b/Makefile @@ -5,16 +5,22 @@ # make WVKBD= WTYPE= # make install DESTDIR= OMARCHY= DBUS_NEXT= # -# The only compiles are the on-screen keyboard (wvkbd with this repository's -# patches) and the startup cursor helper (wtype); desktop/install-tree puts -# every file in place. +# The compiles are the on-screen keyboard (wvkbd with this repository's +# patches), the startup cursor helper (wtype) and the power daemon +# (omarchy-powerd, against libsystemd's sd-bus: the recipe's makedepends); +# desktop/install-tree puts every file in place. BUILD ?= build CC ?= cc CFLAGS ?= -O2 PKG_CONFIG ?= pkg-config -all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype +all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd + +$(BUILD)/omarchy-powerd: desktop/configuration/powerd.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 -DHAVE_SD_BUS $< \ + $$($(PKG_CONFIG) --cflags --libs libsystemd) -lpthread -lm $(LDFLAGS) -o $@ $(BUILD)/wvkbd-mobintl: @test -d "$(WVKBD)" || { echo 'Set WVKBD to the wvkbd v0.20 source' >&2; exit 1; } diff --git a/desktop/configuration/powerd.c b/desktop/configuration/powerd.c new file mode 100644 index 00000000..ef7eba15 --- /dev/null +++ b/desktop/configuration/powerd.c @@ -0,0 +1,3380 @@ +/* The one owner of screen, lock request and sleep. See docs/power-and-lock.md. + * + * Machine is the state machine: no I/O, no clocks, every input defined in every + * state. Daemon around it reads the keys, drives the backlight and talks to + * logind (via sd-bus) and the session. The state is never inferred from + * brightness or files. + */ + +#define _POSIX_C_SOURCE 200809L +#define _DEFAULT_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef HAVE_SD_BUS +#include +#endif +#include +#include + +#ifndef CLOCK_BOOTTIME +#define CLOCK_BOOTTIME CLOCK_MONOTONIC +#endif + +#ifndef SW_MACHINE_COVER +#define SW_MACHINE_COVER 0x10 +#endif + +#define LOGIND_BUS "org.freedesktop.login1" +#define LOGIND_PATH "/org/freedesktop/login1" +#define LOGIND_IFACE "org.freedesktop.login1.Manager" +#define SYSTEMD_BUS "org.freedesktop.systemd1" +#define SYSTEMD_SUSPEND_OBJ "/org/freedesktop/systemd1/unit/systemd_2dsuspend_2eservice" +#define SYSTEMD_UNIT_IFACE "org.freedesktop.systemd1.Unit" + +#define DEFAULT_IDLE_GRACE_SECONDS 8.0 +#define DEFAULT_FADE_SECONDS 0.24 +#define DEFAULT_SETTLE_SECONDS 10.0 +#define RETRY_SECONDS 60.0 +#define ABORTS_BEFORE_DARK 3 +#define BACKOFF_SECONDS 600.0 +#define TICK_SECONDS 0.05 +#define SUSPEND_AWAKE_SECONDS 30.0 +#define SLEEP_END_AWAKE_SECONDS 120.0 +#define AWAKE_STEP_MAX 1.0 +#define FRAME_SECONDS (1.0 / 60.0) +#define LOGIND_END_WAIT_SECONDS 5.0 +#define LONG_HOLD_SECONDS 1.5 +#define EMPTY_PERCENT 2 + +#define DEFAULT_SOCKET "/run/omarchy-powerd.sock" +#define SHELL_ROOT "/usr/share/omarchy" +#define DEFAULT_STATS "/sys/power/suspend_stats" +#define DEFAULT_WAKEUP_COUNT "/sys/power/wakeup_count" +#define DEFAULT_BACKLIGHTS "/sys/class/backlight" +#define DEFAULT_BRIGHTNESS "/var/lib/omarchy-powerd/brightness" +#define DEFAULT_USB_DEVICES "/sys/bus/usb/devices" +#define DEFAULT_POWER_SUPPLIES "/sys/class/power_supply" + +static volatile sig_atomic_t g_sigterm = 0; +static volatile sig_atomic_t g_sigint = 0; +static int g_sig_wake_fd = -1; + +static void handle_sigterm(int sig) +{ + (void)sig; + g_sigterm = 1; + if (g_sig_wake_fd >= 0) { + char b = 'T'; + ssize_t r = write(g_sig_wake_fd, &b, 1); + (void)r; + } +} + +static void handle_sigint(int sig) +{ + (void)sig; + g_sigint = 1; + if (g_sig_wake_fd >= 0) { + char b = 'I'; + ssize_t r = write(g_sig_wake_fd, &b, 1); + (void)r; + } +} + +static bool g_quiet_log = false; + +static void log_msg(const char *fmt, ...) +{ + if (g_quiet_log) + return; + va_list ap; + va_start(ap, fmt); + vprintf(fmt, ap); + va_end(ap); + putchar('\n'); + fflush(stdout); +} + +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 boottime_now(void) +{ + struct timespec ts; + if (clock_gettime(CLOCK_BOOTTIME, &ts) != 0) + return monotonic_now(); + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static void sleep_ms(int ms) +{ + struct timespec ts; + ts.tv_sec = ms / 1000; + ts.tv_nsec = (long)(ms % 1000) * 1000000L; + while (nanosleep(&ts, &ts) == -1 && errno == EINTR) + ; +} + +static 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 bool read_text_file(const char *path, char *buf, size_t cap) +{ + int fd = open(path, O_RDONLY); + if (fd < 0) + return false; + size_t total = 0; + while (total + 1 < cap) { + ssize_t n = read(fd, buf + total, cap - 1 - total); + if (n < 0) { + if (errno == EINTR) + continue; + close(fd); + return false; + } + if (n == 0) + break; + total += (size_t)n; + } + close(fd); + buf[total] = '\0'; + return true; +} + +static bool write_text_file(const char *path, const char *text) +{ + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) + return false; + size_t len = strlen(text); + size_t off = 0; + while (off < len) { + ssize_t n = write(fd, text + off, len - off); + if (n < 0) { + if (errno == EINTR) + continue; + close(fd); + return false; + } + off += (size_t)n; + } + return close(fd) == 0; +} + +static bool read_int_file(const char *path, int *out) +{ + char buf[64]; + if (!read_text_file(path, buf, sizeof(buf))) + return false; + char *s = trim_ws(buf); + if (!*s) + return false; + char *end = NULL; + errno = 0; + long v = strtol(s, &end, 10); + if (errno != 0 || end == s || *end != '\0') + return false; + *out = (int)v; + return true; +} + +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); +} + +/* -------------------------------------------------------------------------- + * State Machine (exact parity with docs/power-and-lock.md) + * -------------------------------------------------------------------------- */ + +enum pstate { + ST_ON = 0, + ST_GRACE, + ST_SETTLING, + ST_DARK, + ST_SUSPENDING, +}; + +static const char *state_name(enum pstate st) +{ + switch (st) { + case ST_ON: return "ON"; + case ST_GRACE: return "GRACE"; + case ST_SETTLING: return "SETTLING"; + case ST_DARK: return "DARK"; + case ST_SUSPENDING: return "SUSPENDING"; + } + return "ON"; +} + +static bool parse_state_name(const char *s, enum pstate *out) +{ + if (strcmp(s, "ON") == 0) { *out = ST_ON; return true; } + if (strcmp(s, "GRACE") == 0) { *out = ST_GRACE; return true; } + if (strcmp(s, "SETTLING") == 0) { *out = ST_SETTLING; return true; } + if (strcmp(s, "DARK") == 0) { *out = ST_DARK; return true; } + if (strcmp(s, "SUSPENDING") == 0) { *out = ST_SUSPENDING; return true; } + return false; +} + +enum pevent { + EV_INVALID = -1, + EV_POWER = 0, + EV_HOME, + EV_WAKE, + EV_IDLE, + EV_SETTLE, + EV_LOCK_OK, + EV_LOCK_FAILED, + EV_PLAYING, + EV_NOT_PLAYING, + EV_SUSPEND_REFUSED, + EV_SUSPEND_UNAVAILABLE, + EV_SUSPEND_BLOCKED, + EV_SUSPEND_BUSY, + EV_SLEEP_SIGNAL, + EV_SLEEP_ENDED, + EV_SLEEP_ABORTED, + EV_TIMEOUT, + EV_GRACE_ENDED, + EV_LOCK, +}; + +static const char *const EVENT_NAMES[] = { + "power", "home", "wake", "idle", "settle", "lock-ok", "lock-failed", + "playing", "not-playing", "suspend-refused", "suspend-unavailable", + "suspend-blocked", "suspend-busy", "sleep-signal", "sleep-ended", + "sleep-aborted", "timeout", "grace-ended", "lock", +}; + +static enum pevent parse_event(const char *s) +{ + for (size_t i = 0; i < sizeof(EVENT_NAMES) / sizeof(EVENT_NAMES[0]); i++) { + if (strcmp(s, EVENT_NAMES[i]) == 0) + return (enum pevent)i; + } + return EV_INVALID; +} + +enum paction { + ACT_DARK = 0, + ACT_LIGHT, + ACT_LOCK, + ACT_WOKE, + ACT_NOTIFY, + ACT_ARM_GRACE, + ACT_CANCEL_GRACE, + ACT_ARM_SETTLE, + ACT_ARM_BACKOFF, + ACT_CANCEL_SETTLE, + ACT_ARM_RETRY, + ACT_TAKE_INHIBITOR, + ACT_RELEASE_INHIBITOR, + ACT_CANCEL_SUSPEND, + ACT_SUSPEND, +}; + +static const char *action_name(enum paction a) +{ + switch (a) { + case ACT_DARK: return "dark"; + case ACT_LIGHT: return "light"; + case ACT_LOCK: return "lock"; + case ACT_WOKE: return "woke"; + case ACT_NOTIFY: return "notify"; + case ACT_ARM_GRACE: return "arm-grace"; + case ACT_CANCEL_GRACE: return "cancel-grace"; + case ACT_ARM_SETTLE: return "arm-settle"; + case ACT_ARM_BACKOFF: return "arm-backoff"; + case ACT_CANCEL_SETTLE: return "cancel-settle"; + case ACT_ARM_RETRY: return "arm-retry"; + case ACT_TAKE_INHIBITOR: return "take-inhibitor"; + case ACT_RELEASE_INHIBITOR: return "release-inhibitor"; + case ACT_CANCEL_SUSPEND: return "cancel-suspend"; + case ACT_SUSPEND: return "suspend"; + } + return ""; +} + +struct action_list { + enum paction items[8]; + int count; +}; + +static void al_push(struct action_list *al, enum paction a) +{ + if (al->count < 8) + al->items[al->count++] = a; +} + +struct machine { + enum pstate state; + bool lock_ok; + bool settle_due; + bool inflight; + bool playing; + bool no_suspend; + bool hold_release; + int aborts; + bool empty; +}; + +static void machine_init(struct machine *m) +{ + memset(m, 0, sizeof(*m)); + m->state = ST_ON; +} + +static void m_darken(struct machine *m, struct action_list *al) +{ + m->lock_ok = false; + m->settle_due = false; + m->no_suspend = false; + m->playing = false; + m->state = ST_SETTLING; + al_push(al, ACT_DARK); + al_push(al, ACT_LOCK); + al_push(al, ACT_ARM_SETTLE); +} + +static void m_light(struct machine *m, struct action_list *al) +{ + m->state = ST_ON; + m->aborts = 0; + m->playing = false; + m->settle_due = false; + al_push(al, ACT_LIGHT); + al_push(al, ACT_WOKE); +} + +static void m_settle_again(struct machine *m, struct action_list *al) +{ + m->state = ST_SETTLING; + m->settle_due = false; + al_push(al, m->aborts >= ABORTS_BEFORE_DARK ? ACT_ARM_BACKOFF : ACT_ARM_SETTLE); +} + +static void m_begin_suspend(struct machine *m, struct action_list *al) +{ + m->state = ST_SUSPENDING; + m->inflight = true; + al_push(al, ACT_SUSPEND); +} + +static void m_external_sleep(struct machine *m, struct action_list *al) +{ + if (m->state == ST_ON || m->state == ST_GRACE) { + m->lock_ok = false; + if (m->state == ST_GRACE) + al_push(al, ACT_CANCEL_GRACE); + al_push(al, ACT_DARK); + al_push(al, ACT_LOCK); + } + m->state = ST_SUSPENDING; + m->inflight = true; + if (m->lock_ok) + al_push(al, ACT_RELEASE_INHIBITOR); + else + m->hold_release = true; +} + +static void m_lock_answer(struct machine *m, bool ok, struct action_list *al) +{ + m->lock_ok = ok; + if (m->hold_release) { + m->hold_release = false; + al_push(al, ACT_RELEASE_INHIBITOR); + } +} + +static struct action_list machine_handle(struct machine *m, enum pevent ev) +{ + struct action_list al = { .count = 0 }; + if (ev == EV_SLEEP_ENDED) + m->aborts = 0; + + bool is_end_ev = (ev == EV_SLEEP_ENDED || ev == EV_SLEEP_ABORTED || + ev == EV_SUSPEND_REFUSED || ev == EV_SUSPEND_UNAVAILABLE || + ev == EV_SUSPEND_BLOCKED || ev == EV_SUSPEND_BUSY || + ev == EV_TIMEOUT); + if (is_end_ev && m->state != ST_SUSPENDING) { + if (m->inflight) { + m->inflight = false; + al_push(&al, ACT_TAKE_INHIBITOR); + if (m->state == ST_SETTLING && m->settle_due && m->lock_ok) + m_begin_suspend(m, &al); + } + return al; + } + + switch (m->state) { + case ST_ON: + if (ev == EV_POWER || ev == EV_LOCK) { + m_darken(m, &al); + } else if (ev == EV_IDLE) { + m->state = ST_GRACE; + m->lock_ok = false; + al_push(&al, ACT_DARK); + al_push(&al, ACT_ARM_GRACE); + } else if (ev == EV_SLEEP_SIGNAL) { + if (!m->inflight) + m_external_sleep(m, &al); + } else if (ev == EV_LOCK_OK) { + m_lock_answer(m, true, &al); + } else if (ev == EV_LOCK_FAILED) { + m_lock_answer(m, false, &al); + } + break; + + case ST_GRACE: + if (ev == EV_POWER || ev == EV_HOME || ev == EV_WAKE) { + al_push(&al, ACT_CANCEL_GRACE); + m_light(m, &al); + } else if (ev == EV_GRACE_ENDED) { + m_darken(m, &al); + } else if (ev == EV_LOCK) { + al_push(&al, ACT_CANCEL_GRACE); + m_darken(m, &al); + } else if (ev == EV_SLEEP_SIGNAL) { + m_external_sleep(m, &al); + } + break; + + case ST_SETTLING: + if ((ev == EV_POWER || ev == EV_HOME) && m->empty) + break; + if (ev == EV_POWER || ev == EV_HOME || ev == EV_WAKE) { + al_push(&al, ACT_CANCEL_SETTLE); + m_light(m, &al); + } else if (ev == EV_SETTLE) { + m->settle_due = true; + if (m->lock_ok && !m->inflight) + m_begin_suspend(m, &al); + } else if (ev == EV_LOCK_OK) { + m_lock_answer(m, true, &al); + if (m->settle_due && !m->inflight) + m_begin_suspend(m, &al); + } else if (ev == EV_LOCK_FAILED) { + m_lock_answer(m, false, &al); + al_push(&al, ACT_CANCEL_SETTLE); + al_push(&al, ACT_NOTIFY); + m_light(m, &al); + } else if (ev == EV_PLAYING) { + m->state = ST_DARK; + m->playing = true; + al_push(&al, ACT_CANCEL_SETTLE); + } else if (ev == EV_SLEEP_SIGNAL) { + al_push(&al, ACT_CANCEL_SETTLE); + m_external_sleep(m, &al); + } + break; + + case ST_DARK: + if ((ev == EV_POWER || ev == EV_HOME) && m->empty) + break; + if (ev == EV_POWER || ev == EV_HOME || ev == EV_WAKE) { + m_light(m, &al); + } else if (ev == EV_LOCK_OK) { + m_lock_answer(m, true, &al); + } else if (ev == EV_LOCK_FAILED) { + m_lock_answer(m, false, &al); + al_push(&al, ACT_NOTIFY); + m_light(m, &al); + } else if (ev == EV_PLAYING) { + m->playing = true; + } else if (ev == EV_NOT_PLAYING) { + m->playing = false; + if (!m->no_suspend) + m_settle_again(m, &al); + } else if (ev == EV_SLEEP_SIGNAL) { + m_external_sleep(m, &al); + } + break; + + case ST_SUSPENDING: + if ((ev == EV_POWER || ev == EV_HOME) && m->empty) + break; + if (ev == EV_POWER || ev == EV_HOME || ev == EV_WAKE) { + al_push(&al, ACT_CANCEL_SUSPEND); + m_light(m, &al); + } else if (ev == EV_LOCK_OK) { + m_lock_answer(m, true, &al); + } else if (ev == EV_LOCK_FAILED) { + m_lock_answer(m, false, &al); + } else if (ev == EV_SLEEP_ENDED || ev == EV_SLEEP_ABORTED) { + if (ev == EV_SLEEP_ABORTED && m->aborts < ABORTS_BEFORE_DARK) + m->aborts++; + m->inflight = false; + al_push(&al, ACT_TAKE_INHIBITOR); + m_settle_again(m, &al); + } else if (ev == EV_SUSPEND_BUSY || ev == EV_TIMEOUT) { + m->inflight = false; + al_push(&al, ACT_TAKE_INHIBITOR); + m_settle_again(m, &al); + } else if (ev == EV_SUSPEND_REFUSED) { + m->inflight = false; + m->state = ST_SETTLING; + m->settle_due = false; + al_push(&al, ACT_TAKE_INHIBITOR); + al_push(&al, ACT_ARM_RETRY); + } else if (ev == EV_SUSPEND_UNAVAILABLE) { + m->inflight = false; + m->no_suspend = true; + m->state = ST_DARK; + al_push(&al, ACT_TAKE_INHIBITOR); + } else if (ev == EV_SUSPEND_BLOCKED) { + m->inflight = false; + m->playing = true; + m->state = ST_DARK; + al_push(&al, ACT_TAKE_INHIBITOR); + } + break; + } + return al; +} + +/* -------------------------------------------------------------------------- + * Pure helpers: battery, supplies, USB, evdev bitmaps, Cover, Buttons, JSON + * -------------------------------------------------------------------------- */ + +static bool battery_empty(const char *supplies_dir) +{ + DIR *d = opendir(supplies_dir); + if (!d) + return false; + struct dirent *de; + bool empty = false; + while ((de = readdir(d)) != NULL) { + if (de->d_name[0] == '.') + continue; + char p[PATH_MAX]; + char buf[64]; + if (snprintf(p, sizeof(p), "%s/%s/type", supplies_dir, de->d_name) >= (int)sizeof(p)) + continue; + if (!read_text_file(p, buf, sizeof(buf)) || strcmp(trim_ws(buf), "Battery") != 0) + continue; + if (snprintf(p, sizeof(p), "%s/%s/status", supplies_dir, de->d_name) >= (int)sizeof(p)) + continue; + if (!read_text_file(p, buf, sizeof(buf)) || strcmp(trim_ws(buf), "Discharging") != 0) + continue; + int cap = 0; + if (snprintf(p, sizeof(p), "%s/%s/capacity", supplies_dir, de->d_name) >= (int)sizeof(p)) + continue; + if (read_int_file(p, &cap) && cap <= EMPTY_PERCENT) { + empty = true; + break; + } + } + closedir(d); + return empty; +} + +static bool parse_supply_uevent(const char *msg, size_t len, + char *out_name, size_t name_cap, bool *out_online) +{ + bool is_ps = false; + bool has_online = false; + bool online = false; + out_name[0] = '\0'; + + size_t pos = 0; + while (pos < len) { + const char *item = msg + pos; + size_t ilen = strnlen(item, len - pos); + if (ilen == 0) { + pos++; + continue; + } + if (strncmp(item, "SUBSYSTEM=", 10) == 0 && ilen == 22 && + memcmp(item + 10, "power_supply", 12) == 0) { + is_ps = true; + } else if (strncmp(item, "POWER_SUPPLY_ONLINE=", 20) == 0) { + has_online = true; + online = (ilen == 21 && item[20] == '1'); + } else if (strncmp(item, "POWER_SUPPLY_NAME=", 18) == 0) { + size_t vlen = ilen - 18; + if (vlen >= name_cap) + vlen = name_cap - 1; + memcpy(out_name, item + 18, vlen); + out_name[vlen] = '\0'; + } + pos += ilen + 1; + } + if (!is_ps || !has_online) + return false; + *out_online = online; + return true; +} + +struct supply_entry { + char name[64]; + bool online; +}; + +struct supply_map { + struct supply_entry items[16]; + int count; +}; + +static bool supply_plugged_in(struct supply_map *map, const char *name, bool online) +{ + for (int i = 0; i < map->count; i++) { + if (strcmp(map->items[i].name, name) == 0) { + bool was = map->items[i].online; + map->items[i].online = online; + return online && !was; + } + } + if (map->count < 16) { + snprintf(map->items[map->count].name, sizeof(map->items[0].name), "%s", name); + map->items[map->count].online = online; + map->count++; + } + return online; +} + +static void usb_new_devices(const char *usb_root, bool allowed) +{ + char pattern[PATH_MAX]; + snprintf(pattern, sizeof(pattern), "%s/usb*/authorized_default", usb_root); + glob_t g; + if (glob(pattern, 0, NULL, &g) == 0) { + for (size_t i = 0; i < g.gl_pathc; i++) { + if (!write_text_file(g.gl_pathv[i], allowed ? "1" : "0")) + log_msg("%s: %s", g.gl_pathv[i], strerror(errno)); + } + } + globfree(&g); +} + +static bool reports_cover(const char *cap_sw) +{ + const char *last_start = NULL; + const char *p = cap_sw; + while (*p) { + while (*p && isspace((unsigned char)*p)) + p++; + if (!*p) + break; + last_start = p; + while (*p && !isspace((unsigned char)*p)) + p++; + } + if (!last_start) + return false; + unsigned long long bits = strtoull(last_start, NULL, 16); + return ((bits >> SW_MACHINE_COVER) & 1ULL) != 0; +} + +static bool reports_keys(const char *cap_key) +{ + unsigned long words[32]; + int count = 0; + const char *p = cap_key; + while (*p && count < 32) { + while (*p && isspace((unsigned char)*p)) + p++; + if (!*p) + break; + char *end = NULL; + unsigned long w = strtoul(p, &end, 16); + if (end == p) + return false; + words[count++] = w; + p = end; + } + if (count == 0) + return false; + + const int word_bits = (int)(sizeof(unsigned long) * 8); + const int codes[] = { KEY_POWER, KEY_HOMEPAGE, KEY_VOLUMEDOWN }; + for (size_t i = 0; i < 3; i++) { + int idx_from_right = codes[i] / word_bits; + int bit = codes[i] % word_bits; + if (idx_from_right < count) { + unsigned long w = words[count - 1 - idx_from_right]; + if ((w >> bit) & 1UL) + return true; + } + } + return false; +} + +struct cover_entry { + int key; + bool closed; +}; + +struct cover_state { + struct cover_entry items[16]; + int count; +}; + +static bool cover_any_closed(const struct cover_state *c) +{ + for (int i = 0; i < c->count; i++) { + if (c->items[i].closed) + return true; + } + return false; +} + +static void cover_set_initial(struct cover_state *c, int key, bool closed) +{ + for (int i = 0; i < c->count; i++) { + if (c->items[i].key == key) { + c->items[i].closed = closed; + return; + } + } + if (c->count < 16) { + c->items[c->count].key = key; + c->items[c->count].closed = closed; + c->count++; + } +} + +static enum pevent cover_change(struct cover_state *c, int key, bool closed) +{ + bool before = cover_any_closed(c); + cover_set_initial(c, key, closed); + bool after = cover_any_closed(c); + if (after == before) + return EV_INVALID; + return after ? EV_LOCK : EV_WAKE; +} + +static void cover_forget(struct cover_state *c, int key) +{ + for (int i = 0; i < c->count; i++) { + if (c->items[i].key == key) { + c->items[i] = c->items[--c->count]; + return; + } + } +} + +enum button_result { + BTN_NONE = 0, + BTN_POWER, + BTN_HOME, + BTN_HOME_UP, + BTN_SCREENSHOT, +}; + +struct buttons { + bool has_held; + double held; + bool spoiled; + bool has_home_down; + double home_down; + bool has_vol_down; + double vol_down; + bool has_combo; + double combo; + bool combo_spent; + bool home_in_combo; + bool home_woke; +}; + +static void buttons_start_combo(struct buttons *b, double when) +{ + b->spoiled = true; + b->has_combo = true; + b->combo = when; + b->combo_spent = false; + if (b->has_home_down) + b->home_in_combo = true; +} + +static enum button_result buttons_end_combo(struct buttons *b, double when) +{ + if (!b->has_combo || b->combo_spent) + return BTN_NONE; + b->combo_spent = true; + return (when - b->combo < LONG_HOLD_SECONDS) ? BTN_SCREENSHOT : BTN_NONE; +} + +static void buttons_both_up(struct buttons *b) +{ + if (!b->has_held && !b->has_home_down && !b->has_vol_down) + b->has_combo = false; +} + +static enum button_result buttons_edge(struct buttons *b, int key_code, bool down, + double when, bool lit) +{ + if (key_code == KEY_VOLUMEDOWN) { + if (down) { + b->has_vol_down = true; + b->vol_down = when; + if (b->has_held) + buttons_start_combo(b, when); + return BTN_NONE; + } + b->has_vol_down = false; + enum button_result ev = buttons_end_combo(b, when); + buttons_both_up(b); + return ev; + } + if (key_code == KEY_HOMEPAGE) { + if (down) { + b->has_home_down = true; + b->home_down = when; + b->home_in_combo = false; + b->home_woke = !lit; + if (b->has_held) + buttons_start_combo(b, when); + return BTN_HOME; + } + bool pressed = b->has_home_down; + b->has_home_down = false; + enum button_result ev = buttons_end_combo(b, when); + buttons_both_up(b); + if (ev == BTN_NONE && pressed && !b->home_in_combo && !b->home_woke) + return BTN_HOME_UP; + return ev; + } + /* KEY_POWER */ + if (down) { + if (!lit) { + b->has_held = false; + return BTN_POWER; + } + b->has_held = true; + b->held = when; + b->spoiled = false; + if (b->has_home_down || b->has_vol_down) + buttons_start_combo(b, when); + return BTN_NONE; + } + if (!b->has_held) + return BTN_NONE; + enum button_result ev = buttons_end_combo(b, when); + bool is_short = (when - b->held < LONG_HOLD_SECONDS) && !b->spoiled; + b->has_held = false; + buttons_both_up(b); + if (ev != BTN_NONE || b->has_combo || b->spoiled) + return ev; + return is_short ? BTN_POWER : BTN_NONE; +} + +/* Minimal JSON helpers for pw-dump (`streams_running`), lock status, and test monitor */ +struct jcur { + const char *p; + const char *end; +}; + +static void j_ws(struct jcur *c) +{ + while (c->p < c->end && (*c->p == ' ' || *c->p == '\t' || *c->p == '\r' || *c->p == '\n')) + c->p++; +} + +static bool j_str(struct jcur *c, char *out, size_t cap) +{ + j_ws(c); + if (c->p >= c->end || *c->p != '"') + return false; + c->p++; + size_t len = 0; + while (c->p < c->end && *c->p != '"') { + char ch = *c->p++; + if (ch == '\\') { + if (c->p >= c->end) + return false; + ch = *c->p++; + if (ch == 'u') { + if (c->end - c->p < 4) + return false; + c->p += 4; + ch = '?'; + } + } + if (out && len + 1 < cap) + out[len++] = ch; + } + if (c->p >= c->end || *c->p != '"') + return false; + c->p++; + if (out && cap > 0) + out[len] = '\0'; + return true; +} + +static bool j_skip(struct jcur *c, int depth) +{ + if (depth > 32) + return false; + j_ws(c); + if (c->p >= c->end) + return false; + if (*c->p == '"') + return j_str(c, NULL, 0); + if (*c->p == '[') { + c->p++; + j_ws(c); + if (c->p < c->end && *c->p == ']') { c->p++; return true; } + for (;;) { + if (!j_skip(c, depth + 1)) return false; + j_ws(c); + if (c->p >= c->end) return false; + if (*c->p == ']') { c->p++; return true; } + if (*c->p != ',') return false; + c->p++; + } + } + if (*c->p == '{') { + c->p++; + j_ws(c); + if (c->p < c->end && *c->p == '}') { c->p++; return true; } + for (;;) { + if (!j_str(c, NULL, 0)) return false; + j_ws(c); + if (c->p >= c->end || *c->p != ':') return false; + c->p++; + if (!j_skip(c, depth + 1)) return false; + j_ws(c); + if (c->p >= c->end) return false; + if (*c->p == '}') { c->p++; return true; } + if (*c->p != ',') return false; + c->p++; + } + } + while (c->p < c->end && !isspace((unsigned char)*c->p) && + *c->p != ',' && *c->p != ']' && *c->p != '}') + c->p++; + return true; +} + +static bool j_parse_props_media(struct jcur *c, bool *is_stream_output) +{ + j_ws(c); + if (c->p >= c->end || *c->p != '{') + return j_skip(c, 3); + c->p++; + j_ws(c); + if (c->p < c->end && *c->p == '}') { c->p++; return true; } + for (;;) { + char key[64]; + if (!j_str(c, key, sizeof(key))) return false; + j_ws(c); + if (c->p >= c->end || *c->p != ':') return false; + c->p++; + j_ws(c); + if (strcmp(key, "media.class") == 0 && c->p < c->end && *c->p == '"') { + char val[64]; + if (!j_str(c, val, sizeof(val))) return false; + if (strncmp(val, "Stream/Output/", 14) == 0) + *is_stream_output = true; + } else { + if (!j_skip(c, 4)) return false; + } + j_ws(c); + if (c->p >= c->end) return false; + if (*c->p == '}') { c->p++; return true; } + if (*c->p != ',') return false; + c->p++; + } +} + +static bool streams_running(const char *dump, size_t len) +{ + struct jcur c = { dump, dump + len }; + j_ws(&c); + if (c.p >= c.end || *c.p != '[') + return false; + c.p++; + j_ws(&c); + if (c.p < c.end && *c.p == ']') + return false; + for (;;) { + j_ws(&c); + if (c.p >= c.end || *c.p != '{') + return false; + c.p++; + bool running = false; + bool stream_out = false; + j_ws(&c); + if (c.p < c.end && *c.p == '}') { + c.p++; + } else { + for (;;) { + char key[32]; + if (!j_str(&c, key, sizeof(key))) return false; + j_ws(&c); + if (c.p >= c.end || *c.p != ':') return false; + c.p++; + j_ws(&c); + if (strcmp(key, "info") == 0 && c.p < c.end && *c.p == '{') { + c.p++; + j_ws(&c); + if (c.p < c.end && *c.p == '}') { + c.p++; + } else { + for (;;) { + char ikey[32]; + if (!j_str(&c, ikey, sizeof(ikey))) return false; + j_ws(&c); + if (c.p >= c.end || *c.p != ':') return false; + c.p++; + j_ws(&c); + if (strcmp(ikey, "state") == 0 && c.p < c.end && *c.p == '"') { + char sval[32]; + if (!j_str(&c, sval, sizeof(sval))) return false; + if (strcmp(sval, "running") == 0) + running = true; + } else if (strcmp(ikey, "props") == 0) { + if (!j_parse_props_media(&c, &stream_out)) + return false; + } else { + if (!j_skip(&c, 3)) return false; + } + j_ws(&c); + if (c.p >= c.end) return false; + if (*c.p == '}') { c.p++; break; } + if (*c.p != ',') return false; + c.p++; + } + } + } else { + if (!j_skip(&c, 2)) return false; + } + j_ws(&c); + if (c.p >= c.end) return false; + if (*c.p == '}') { c.p++; break; } + if (*c.p != ',') return false; + c.p++; + } + } + if (running && stream_out) + return true; + j_ws(&c); + if (c.p >= c.end) return false; + if (*c.p == ']') return false; + if (*c.p != ',') return false; + c.p++; + } +} + +static bool json_has_secure_true(const char *s, size_t len) +{ + struct jcur c = { s, s + len }; + j_ws(&c); + if (c.p >= c.end || *c.p != '{') + return false; + c.p++; + j_ws(&c); + if (c.p < c.end && *c.p == '}') + return false; + for (;;) { + char key[32]; + if (!j_str(&c, key, sizeof(key))) return false; + j_ws(&c); + if (c.p >= c.end || *c.p != ':') return false; + c.p++; + j_ws(&c); + if (strcmp(key, "secure") == 0) { + return (c.end - c.p >= 4 && memcmp(c.p, "true", 4) == 0); + } + if (!j_skip(&c, 1)) return false; + j_ws(&c); + if (c.p >= c.end) return false; + if (*c.p == '}') return false; + if (*c.p != ',') return false; + c.p++; + } +} + +/* -------------------------------------------------------------------------- + * Subprocess execution helpers + * -------------------------------------------------------------------------- */ + +static int run_cmd(char *const argv[], char *const envp[], const char *cwd, + double timeout_s, char **out_buf, size_t *out_len) +{ + int pipefd[2] = { -1, -1 }; + if (out_buf && pipe(pipefd) < 0) + return -1; + + pid_t pid = fork(); + if (pid < 0) { + if (out_buf) { close(pipefd[0]); close(pipefd[1]); } + return -1; + } + if (pid == 0) { + if (cwd && chdir(cwd) != 0) + _exit(127); + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + dup2(devnull, STDERR_FILENO); + if (!out_buf) + dup2(devnull, STDOUT_FILENO); + if (devnull > STDERR_FILENO) + close(devnull); + } + if (out_buf) { + close(pipefd[0]); + dup2(pipefd[1], STDOUT_FILENO); + if (pipefd[1] > STDERR_FILENO) + close(pipefd[1]); + } + if (envp) { + extern char **environ; + environ = (char **)envp; + } + execvp(argv[0], argv); + _exit(127); + } + + if (out_buf) + close(pipefd[1]); + + double deadline = monotonic_now() + timeout_s; + bool timed_out = false; + char *buf = NULL; + size_t cap = 0, len = 0; + + if (out_buf) { + int flags = fcntl(pipefd[0], F_GETFL, 0); + if (flags >= 0) + fcntl(pipefd[0], F_SETFL, flags | O_NONBLOCK); + cap = 4096; + buf = malloc(cap); + if (!buf) { + close(pipefd[0]); + kill(pid, SIGKILL); + waitpid(pid, NULL, 0); + return -1; + } + for (;;) { + double rem = deadline - monotonic_now(); + if (rem <= 0.0) { timed_out = true; break; } + struct pollfd pfd = { .fd = pipefd[0], .events = POLLIN }; + int r = poll(&pfd, 1, (int)(rem * 1000.0) + 1); + if (r < 0) { + if (errno == EINTR) continue; + break; + } + if (r == 0) { timed_out = true; break; } + bool eof = false; + for (;;) { + if (len + 4096 > cap) { + if (cap >= 4 * 1024 * 1024) { eof = true; break; } + cap *= 2; + char *nb = realloc(buf, cap); + if (!nb) { eof = true; break; } + buf = nb; + } + ssize_t n = read(pipefd[0], buf + len, cap - 1 - len); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) break; + if (errno == EINTR) continue; + eof = true; + break; + } + if (n == 0) { eof = true; break; } + len += (size_t)n; + } + if (eof) break; + } + close(pipefd[0]); + buf[len] = '\0'; + } + + int status = 0; + if (timed_out) { + kill(pid, SIGKILL); + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) + ; + free(buf); + return -1; + } + for (;;) { + pid_t w = waitpid(pid, &status, WNOHANG); + if (w == pid) break; + if (w < 0) { + if (errno == EINTR) continue; + free(buf); + return -1; + } + if (monotonic_now() >= deadline) { + kill(pid, SIGKILL); + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) + ; + free(buf); + return -1; + } + sleep_ms(10); + } + if (out_buf) { + *out_buf = buf; + if (out_len) *out_len = len; + } + return WIFEXITED(status) ? WEXITSTATUS(status) : -1; +} + +struct user_info { + char name[128]; + char home[PATH_MAX]; + uid_t uid; + gid_t gid; +}; + +static bool get_session_user(struct user_info *u) +{ + if (getenv("OMARCHY_POWERD_NO_SESSION")) + return false; + const char *test_user = getenv("OMARCHY_POWERD_TEST_USER"); + if (test_user && *test_user) { + snprintf(u->name, sizeof(u->name), "%s", test_user); + snprintf(u->home, sizeof(u->home), "/home/%s", test_user); + u->uid = 1000; + u->gid = 1000; + return true; + } + + char *a1[] = { "loginctl", "show-seat", "seat0", "-p", "ActiveSession", "--value", NULL }; + char *out = NULL; + if (run_cmd(a1, NULL, NULL, 5.0, &out, NULL) != 0 || !out) { + free(out); + return false; + } + char *sess = trim_ws(out); + if (!*sess) { + free(out); + return false; + } + char sess_id[128]; + snprintf(sess_id, sizeof(sess_id), "%s", sess); + free(out); + + char *a2[] = { "loginctl", "show-session", sess_id, "-p", "Name", "-p", "Class", NULL }; + out = NULL; + if (run_cmd(a2, NULL, NULL, 5.0, &out, NULL) != 0 || !out) { + free(out); + return false; + } + bool is_user = false; + char uname[128] = ""; + char *p = out; + while (*p) { + char *nl = strchr(p, '\n'); + if (nl) *nl = '\0'; + if (strcmp(p, "Class=user") == 0) + is_user = true; + else if (strncmp(p, "Name=", 5) == 0) + snprintf(uname, sizeof(uname), "%s", p + 5); + if (!nl) break; + p = nl + 1; + } + free(out); + if (!is_user || !uname[0]) + return false; + + struct passwd *pw = getpwnam(uname); + if (!pw) + return false; + snprintf(u->name, sizeof(u->name), "%s", pw->pw_name); + snprintf(u->home, sizeof(u->home), "%s", pw->pw_dir); + u->uid = pw->pw_uid; + u->gid = pw->pw_gid; + return true; +} + +static int run_as_user(const struct user_info *u, char *const user_argv[], + double timeout_s, char **out_buf, size_t *out_len) +{ + char reuid[32], regid[32]; + snprintf(reuid, sizeof(reuid), "--reuid=%lu", (unsigned long)u->uid); + snprintf(regid, sizeof(regid), "--regid=%lu", (unsigned long)u->gid); + + char *argv[24]; + int argc = 0; + argv[argc++] = "setpriv"; + argv[argc++] = reuid; + argv[argc++] = regid; + argv[argc++] = "--init-groups"; + argv[argc++] = "--"; + for (int i = 0; user_argv[i] && argc < 23; i++) + argv[argc++] = user_argv[i]; + argv[argc] = NULL; + + char e_home[PATH_MAX + 8], e_user[160], e_rt[64]; + snprintf(e_home, sizeof(e_home), "HOME=%s", u->home); + snprintf(e_user, sizeof(e_user), "USER=%s", u->name); + snprintf(e_rt, sizeof(e_rt), "XDG_RUNTIME_DIR=/run/user/%lu", (unsigned long)u->uid); + char *envp[] = { + e_home, e_user, e_rt, + "OMARCHY_PATH=" SHELL_ROOT, + "PATH=/usr/local/bin:/usr/bin", + NULL + }; + return run_cmd(argv, envp, "/", timeout_s, out_buf, out_len); +} + +static void spawn_as_user(const struct user_info *u, const char *cmd, const char *labwc_pid) +{ + const char *test_log = getenv("OMARCHY_POWERD_SPAWN_LOG"); + if (test_log && *test_log) { + FILE *f = fopen(test_log, "a"); + if (f) { + fprintf(f, "%s\n", cmd); + fclose(f); + } + return; + } + + pid_t first = fork(); + if (first < 0) + return; + if (first == 0) { + pid_t second = fork(); + if (second != 0) + _exit(0); + setsid(); + if (chdir("/") != 0) + _exit(127); + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + dup2(devnull, STDOUT_FILENO); + dup2(devnull, STDERR_FILENO); + if (devnull > STDERR_FILENO) + close(devnull); + } + char reuid[32], regid[32]; + snprintf(reuid, sizeof(reuid), "--reuid=%lu", (unsigned long)u->uid); + snprintf(regid, sizeof(regid), "--regid=%lu", (unsigned long)u->gid); + + char e_home[PATH_MAX + 8], e_user[160], e_rt[64], e_labwc[48]; + snprintf(e_home, sizeof(e_home), "HOME=%s", u->home); + snprintf(e_user, sizeof(e_user), "USER=%s", u->name); + snprintf(e_rt, sizeof(e_rt), "XDG_RUNTIME_DIR=/run/user/%lu", (unsigned long)u->uid); + char *envp[7]; + int ei = 0; + envp[ei++] = e_home; + envp[ei++] = e_user; + envp[ei++] = e_rt; + envp[ei++] = "OMARCHY_PATH=" SHELL_ROOT; + envp[ei++] = "PATH=/usr/local/bin:/usr/bin"; + if (labwc_pid && *labwc_pid) { + snprintf(e_labwc, sizeof(e_labwc), "LABWC_PID=%s", labwc_pid); + envp[ei++] = e_labwc; + } + envp[ei] = NULL; + + extern char **environ; + environ = envp; + execlp("setpriv", "setpriv", reuid, regid, "--init-groups", "--", cmd, (char *)NULL); + _exit(127); + } + int st = 0; + while (waitpid(first, &st, 0) < 0 && errno == EINTR) + ; +} + +/* -------------------------------------------------------------------------- + * Daemon state & queues + * -------------------------------------------------------------------------- */ + +#define MAX_EVENTS_Q 64 +#define MAX_JOBS_Q 32 +#define MAX_INPUT_FDS 32 + +struct event_item { + bool is_sleep_over; + int sleep_record; + enum pevent ev; +}; + +enum session_job { + JOB_LOCK = 0, + JOB_WOKE, + JOB_SCREENSHOT, + JOB_NOTIFY, +}; + +struct input_dev { + int fd; + char path[128]; + bool dropped; +}; + +struct fade_state { + bool active; + char panel[PATH_MAX]; + int start; + int target; + double began; + double written; +}; + +struct daemon { + /* Configurable paths & timings (overridable in tests) */ + const char *socket_path; + const char *stats_dir; + const char *wakeup_count_path; + const char *backlights_dir; + const char *brightness_path; + const char *usb_devices_dir; + const char *power_supplies_dir; + double settle_seconds; + double fade_seconds; + double idle_grace_seconds; + bool no_dbus; + bool no_chown; + + struct machine machine; + struct cover_state cover; + struct buttons buttons; + struct supply_map supplies; + + struct input_dev keys[MAX_INPUT_FDS]; + int key_count; + struct input_dev covers[MAX_INPUT_FDS]; + int cover_count; + + int wake_read; + int wake_write; + int uevents_fd; + int test_monitor_fd; + char monitor_buf[8192]; + size_t monitor_buf_len; + +#ifdef HAVE_SD_BUS + sd_bus *bus; + sd_bus_slot *slot_sleep; + sd_bus_slot *slot_owner; +#endif + int inhibitor_fd; + bool want_inhibitor; + double next_inhibitor; + + double next_scan; + bool has_settle_at; + double settle_at; + bool has_grace_at; + double grace_at; + + struct fade_state fade; + bool has_saved; + int saved; + bool has_dim; + int dim_saved; + int dim_level; + + int counters_ok; + int counters_fail; + int seen_ok; + int seen_fail; + double sleep_started; + bool sleep_begun; + double awake; + double last_turn; + bool logind_asleep; + double logind_busy_until; + double key_time; + bool has_lit_at; + double lit_at; + bool watching_unit; + + /* Shared with worker threads (protected by lock) */ + pthread_mutex_t lock; + pthread_cond_t dark_cv; + pthread_cond_t job_cv; + + bool stopping; + bool dark_flag; + bool cancel_flag; + bool inflight_shared; + bool playing_shared; + bool kernel_attempted_shared; + int sleep_record_shared; + + struct event_item ev_q[MAX_EVENTS_Q]; + int ev_head, ev_tail, ev_count; + + enum session_job job_q[MAX_JOBS_Q]; + int job_head, job_tail, job_count; +}; + +static double env_double(const char *name, double def) +{ + const char *v = getenv(name); + if (!v || !*v) + return def; + char *end = NULL; + double d = strtod(v, &end); + return (end != v && isfinite(d)) ? d : def; +} + +static const char *env_str(const char *name, const char *def) +{ + const char *v = getenv(name); + return (v && *v) ? v : def; +} + +static void daemon_init(struct daemon *d) +{ + memset(d, 0, sizeof(*d)); + d->socket_path = env_str("OMARCHY_POWERD_SOCKET", DEFAULT_SOCKET); + d->stats_dir = env_str("OMARCHY_POWERD_STATS", DEFAULT_STATS); + d->wakeup_count_path = env_str("OMARCHY_POWERD_WAKEUP_COUNT", DEFAULT_WAKEUP_COUNT); + d->backlights_dir = env_str("OMARCHY_POWERD_BACKLIGHTS", DEFAULT_BACKLIGHTS); + d->brightness_path = env_str("OMARCHY_POWERD_BRIGHTNESS", DEFAULT_BRIGHTNESS); + d->usb_devices_dir = env_str("OMARCHY_POWERD_USB_DEVICES", DEFAULT_USB_DEVICES); + d->power_supplies_dir = env_str("OMARCHY_POWERD_POWER_SUPPLIES", DEFAULT_POWER_SUPPLIES); + d->settle_seconds = env_double("OMARCHY_POWERD_SETTLE_SECONDS", DEFAULT_SETTLE_SECONDS); + d->fade_seconds = env_double("OMARCHY_POWERD_FADE_SECONDS", DEFAULT_FADE_SECONDS); + d->idle_grace_seconds = env_double("OMARCHY_POWERD_IDLE_GRACE_SECONDS", DEFAULT_IDLE_GRACE_SECONDS); + d->no_dbus = getenv("OMARCHY_POWERD_NO_DBUS") != NULL; + d->no_chown = getenv("OMARCHY_POWERD_NO_CHOWN") != NULL; + + machine_init(&d->machine); + d->wake_read = -1; + d->wake_write = -1; + d->uevents_fd = -1; + d->test_monitor_fd = -1; + d->inhibitor_fd = -1; + d->last_turn = monotonic_now(); + d->logind_busy_until = INFINITY; + + pthread_mutex_init(&d->lock, NULL); + pthread_cond_init(&d->dark_cv, NULL); + pthread_cond_init(&d->job_cv, NULL); + + int pfd[2]; + if (pipe(pfd) == 0) { + fcntl(pfd[0], F_SETFL, O_NONBLOCK); + fcntl(pfd[1], F_SETFL, O_NONBLOCK); + d->wake_read = pfd[0]; + d->wake_write = pfd[1]; + } +} + +static void daemon_post_event(struct daemon *d, enum pevent ev) +{ + pthread_mutex_lock(&d->lock); + if (d->ev_count < MAX_EVENTS_Q) { + d->ev_q[d->ev_tail].is_sleep_over = false; + d->ev_q[d->ev_tail].ev = ev; + d->ev_tail = (d->ev_tail + 1) % MAX_EVENTS_Q; + d->ev_count++; + } + pthread_mutex_unlock(&d->lock); + if (d->wake_write >= 0) { + char b = '.'; + ssize_t r = write(d->wake_write, &b, 1); + (void)r; + } +} + +static void daemon_post_sleep_over(struct daemon *d, int record) +{ + pthread_mutex_lock(&d->lock); + if (d->ev_count < MAX_EVENTS_Q) { + d->ev_q[d->ev_tail].is_sleep_over = true; + d->ev_q[d->ev_tail].sleep_record = record; + d->ev_tail = (d->ev_tail + 1) % MAX_EVENTS_Q; + d->ev_count++; + } + pthread_mutex_unlock(&d->lock); + if (d->wake_write >= 0) { + char b = '.'; + ssize_t r = write(d->wake_write, &b, 1); + (void)r; + } +} + +static void daemon_push_job(struct daemon *d, enum session_job job) +{ + pthread_mutex_lock(&d->lock); + if (d->job_count < MAX_JOBS_Q) { + d->job_q[d->job_tail] = job; + d->job_tail = (d->job_tail + 1) % MAX_JOBS_Q; + d->job_count++; + pthread_cond_signal(&d->job_cv); + } + pthread_mutex_unlock(&d->lock); +} + +/* -------------------------------------------------------------------------- + * Backlight & brightness persistence + * -------------------------------------------------------------------------- */ + +static bool find_backlight(const struct daemon *d, char *out, size_t cap) +{ + DIR *dir = opendir(d->backlights_dir); + if (!dir) + return false; + struct dirent *de; + char found[256] = ""; + int count = 0; + while ((de = readdir(dir)) != NULL) { + if (de->d_name[0] == '.') + continue; + count++; + if (count == 1) + snprintf(found, sizeof(found), "%s", de->d_name); + } + closedir(dir); + if (count != 1) + return false; + snprintf(out, cap, "%s/%s", d->backlights_dir, found); + return true; +} + +static bool bl_read_int(const char *panel, const char *attr, int *out) +{ + char path[PATH_MAX + 32]; + snprintf(path, sizeof(path), "%s/%s", panel, attr); + return read_int_file(path, out); +} + +static void bl_write_int(const char *panel, int val) +{ + char path[PATH_MAX + 32]; + char buf[32]; + snprintf(path, sizeof(path), "%s/brightness", panel); + snprintf(buf, sizeof(buf), "%d\n", val); + write_text_file(path, buf); +} + +static void remember_brightness(const struct daemon *d, int level) +{ + char dir[PATH_MAX]; + snprintf(dir, sizeof(dir), "%s", d->brightness_path); + char *slash = strrchr(dir, '/'); + if (slash) { + *slash = '\0'; + mkdir_p(dir); + } + char tmp[PATH_MAX + 16]; + snprintf(tmp, sizeof(tmp), "%s.new", d->brightness_path); + char buf[32]; + snprintf(buf, sizeof(buf), "%d\n", level); + if (!write_text_file(tmp, buf) || rename(tmp, d->brightness_path) != 0) + log_msg("brightness not remembered: %s", strerror(errno)); +} + +static int remembered_level(const struct daemon *d, const char *panel) +{ + int maximum = 100; + bl_read_int(panel, "max_brightness", &maximum); + int floor_val = maximum / 20; + if (floor_val < 1) floor_val = 1; + int level = maximum; + if (read_int_file(d->brightness_path, &level)) { + if (level < floor_val) + level = floor_val; + } else { + level = maximum; + } + if (level > maximum) + level = maximum; + return level; +} + +static void restore_brightness(struct daemon *d) +{ + char panel[PATH_MAX]; + if (!find_backlight(d, panel, sizeof(panel))) + return; + d->saved = remembered_level(d, panel); + d->has_saved = true; + bl_write_int(panel, d->saved); +} + +static void start_fade(struct daemon *d, const char *panel, int target, double now) +{ + int current = 0; + bl_read_int(panel, "brightness", ¤t); + if (d->fade_seconds <= 0.0 || current == target) { + d->fade.active = false; + bl_write_int(panel, target); + return; + } + d->fade.active = true; + snprintf(d->fade.panel, sizeof(d->fade.panel), "%s", panel); + d->fade.start = current; + d->fade.target = target; + d->fade.began = now; + d->fade.written = -INFINITY; +} + +static double next_frame(const struct daemon *d, double now) +{ + if (!d->fade.active) + return 1.0; + double rem = d->fade.written + FRAME_SECONDS - now; + return rem > 0.0 ? rem : 0.0; +} + +static void tick_fade(struct daemon *d, double now) +{ + if (!d->fade.active) + return; + double t = (now - d->fade.began) / d->fade_seconds; + if (t < 0.0) t = 0.0; + if (t > 1.0) t = 1.0; + if (t < 1.0 && now - d->fade.written < FRAME_SECONDS) + return; + double eased = t * t * (3.0 - 2.0 * t); + int level = (int)llround((double)d->fade.start + (double)(d->fade.target - d->fade.start) * eased); + bl_write_int(d->fade.panel, level); + if (t >= 1.0) + d->fade.active = false; + else + d->fade.written = now; +} + +static void finish_dark_fade(struct daemon *d) +{ + if (d->fade.active && d->fade.target == 0) { + bl_write_int(d->fade.panel, 0); + d->fade.active = false; + } +} + +static void stop_brightness(struct daemon *d) +{ + char panel[PATH_MAX]; + if (find_backlight(d, panel, sizeof(panel))) { + if (d->has_dim && d->machine.state == ST_ON && !d->fade.active) + bl_write_int(panel, d->dim_saved); + else if (d->fade.active) + bl_write_int(panel, d->fade.target); + int current = 0; + bl_read_int(panel, "brightness", ¤t); + if (d->fade.active && d->has_saved && d->saved > 0) + remember_brightness(d, d->saved); + else if (current > 0) + remember_brightness(d, current); + } +} + +/* -------------------------------------------------------------------------- + * Sleep counters, wakeup_count, logind / sd-bus + * -------------------------------------------------------------------------- */ + +static void read_sleep_counters(const struct daemon *d, int *ok_out, int *fail_out) +{ + char p[PATH_MAX + 32]; + int ok = 0, fail = 0; + snprintf(p, sizeof(p), "%s/success", d->stats_dir); + read_int_file(p, &ok); + snprintf(p, sizeof(p), "%s/fail", d->stats_dir); + read_int_file(p, &fail); + *ok_out = ok; + *fail_out = fail; +} + +static bool arm_wakeup(const struct daemon *d) +{ + char buf[64]; + if (!read_text_file(d->wakeup_count_path, buf, sizeof(buf))) { + log_msg("wakeup_count: %s", strerror(errno)); + return false; + } + char out[64]; + snprintf(out, sizeof(out), "%s\n", trim_ws(buf)); + if (!write_text_file(d->wakeup_count_path, out)) { + log_msg("wakeup_count: %s", strerror(errno)); + return false; + } + return true; +} + +static bool logind_busy(const struct daemon *d, double now) +{ + return d->logind_asleep && now < d->logind_busy_until; +} + +static void take_inhibitor(struct daemon *d) +{ + d->want_inhibitor = true; + if (logind_busy(d, monotonic_now())) + return; +#ifdef HAVE_SD_BUS + if (d->inhibitor_fd >= 0 || d->no_dbus || !d->bus) + return; + + sd_bus_error err = SD_BUS_ERROR_NULL; + sd_bus_message *reply = NULL; + int r = sd_bus_call_method(d->bus, LOGIND_BUS, LOGIND_PATH, LOGIND_IFACE, "Inhibit", + &err, &reply, "ssss", + "sleep", "omarchy-powerd", "Lock and darken first", "delay"); + if (r >= 0) { + int fd = -1; + if (sd_bus_message_read(reply, "h", &fd) >= 0 && fd >= 0) + d->inhibitor_fd = dup(fd); + } + sd_bus_error_free(&err); + sd_bus_message_unref(reply); +#endif +} + +static void keep_inhibitor(struct daemon *d, double now) +{ + if (d->want_inhibitor && !d->machine.inflight && !logind_busy(d, now) && + d->inhibitor_fd < 0 && now >= d->next_inhibitor) { + d->next_inhibitor = now + 2.0; + take_inhibitor(d); + } +} + +static void release_inhibitor(struct daemon *d) +{ + d->want_inhibitor = false; + if (d->inhibitor_fd >= 0) { + close(d->inhibitor_fd); + d->inhibitor_fd = -1; + } +} + +static void renew_inhibitor(struct daemon *d) +{ + if (d->want_inhibitor) { + release_inhibitor(d); + take_inhibitor(d); + } +} + +/* Forward declarations */ +static void daemon_feed(struct daemon *d, enum pevent ev, bool has_when, double when); +static void sleep_began(struct daemon *d, const char *how); +static void sleep_finished(struct daemon *d, const char *how); +static void begin_sleep_record(struct daemon *d); + +static void handle_prepare_for_sleep(struct daemon *d, bool sleeping) +{ + d->logind_asleep = sleeping; + d->logind_busy_until = INFINITY; + if (sleeping && d->machine.inflight) { + sleep_began(d, "logind"); + } else if (sleeping) { + d->has_lit_at = false; + begin_sleep_record(d); + arm_wakeup(d); + daemon_feed(d, EV_SLEEP_SIGNAL, false, 0.0); + sleep_began(d, "logind"); + } else { + sleep_finished(d, "logind"); + } +} + +#ifdef HAVE_SD_BUS +static int on_prepare_for_sleep(sd_bus_message *m, void *userdata, sd_bus_error *ret_err) +{ + (void)ret_err; + struct daemon *d = userdata; + int sleeping = 0; + if (sd_bus_message_read(m, "b", &sleeping) >= 0) + handle_prepare_for_sleep(d, sleeping != 0); + return 0; +} + +static int on_name_owner_changed(sd_bus_message *m, void *userdata, sd_bus_error *ret_err) +{ + (void)ret_err; + struct daemon *d = userdata; + const char *name = NULL, *old_owner = NULL, *new_owner = NULL; + if (sd_bus_message_read(m, "sss", &name, &old_owner, &new_owner) >= 0) { + if (name && strcmp(name, LOGIND_BUS) == 0 && new_owner && *new_owner) { + log_msg("logind started"); + d->logind_asleep = false; + renew_inhibitor(d); + } + } + return 0; +} + +static void start_dbus(struct daemon *d) +{ + if (d->no_dbus) + return; + if (sd_bus_open_system(&d->bus) < 0) { + log_msg("sd-bus open failed"); + d->bus = NULL; + return; + } + sd_bus_add_match(d->bus, &d->slot_sleep, + "type='signal',interface='org.freedesktop.login1.Manager',member='PrepareForSleep'", + on_prepare_for_sleep, d); + sd_bus_add_match(d->bus, &d->slot_owner, + "type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.login1'", + on_name_owner_changed, d); +} +#else +static void start_dbus(struct daemon *d) +{ + (void)d; +} +#endif + +/* -------------------------------------------------------------------------- + * Worker threads: unit watcher, suspend request, session jobs, playback + * -------------------------------------------------------------------------- */ + +struct unit_watch_args { + struct daemon *d; + int record; +}; + +static bool query_suspend_unit_state(const struct daemon *d, char *out, size_t cap) +{ + out[0] = '\0'; +#ifdef HAVE_SD_BUS + if (!d->no_dbus) { + sd_bus *bus = NULL; + if (sd_bus_open_system(&bus) >= 0) { + char *val = NULL; + sd_bus_error err = SD_BUS_ERROR_NULL; + int r = sd_bus_get_property_string(bus, SYSTEMD_BUS, SYSTEMD_SUSPEND_OBJ, + SYSTEMD_UNIT_IFACE, "ActiveState", + &err, &val); + if (r >= 0 && val) { + snprintf(out, cap, "%s", val); + free(val); + sd_bus_error_free(&err); + sd_bus_unref(bus); + return true; + } + sd_bus_error_free(&err); + sd_bus_unref(bus); + } + } +#else + (void)d; +#endif + char *argv[] = { "systemctl", "show", "-p", "ActiveState", "--value", "systemd-suspend.service", NULL }; + char *buf = NULL; + if (run_cmd(argv, NULL, NULL, 5.0, &buf, NULL) == 0 && buf) { + snprintf(out, cap, "%s", trim_ws(buf)); + free(buf); + return true; + } + free(buf); + return false; +} + +static void *wait_for_unit_thread(void *arg) +{ + struct unit_watch_args *ua = arg; + struct daemon *d = ua->d; + int record = ua->record; + free(ua); + + bool running = false; + for (;;) { + pthread_mutex_lock(&d->lock); + bool go = !d->stopping && d->inflight_shared && d->sleep_record_shared == record; + bool k_att = d->kernel_attempted_shared; + pthread_mutex_unlock(&d->lock); + if (!go) + return NULL; + + char state[64]; + if (query_suspend_unit_state(d, state, sizeof(state))) { + if ((strcmp(state, "inactive") == 0 || strcmp(state, "failed") == 0) && + (running || k_att)) { + daemon_post_sleep_over(d, record); + return NULL; + } + if (strcmp(state, "activating") == 0 || + strcmp(state, "active") == 0 || + strcmp(state, "deactivating") == 0) + running = true; + } + sleep_ms(100); + } +} + +static bool query_block_inhibited(const struct daemon *d) +{ +#ifdef HAVE_SD_BUS + if (!d->no_dbus) { + sd_bus *bus = NULL; + if (sd_bus_open_system(&bus) >= 0) { + char *val = NULL; + sd_bus_error err = SD_BUS_ERROR_NULL; + int r = sd_bus_get_property_string(bus, LOGIND_BUS, LOGIND_PATH, + LOGIND_IFACE, "BlockInhibited", + &err, &val); + bool blocked = (r >= 0 && val && strstr(val, "sleep") != NULL); + free(val); + sd_bus_error_free(&err); + sd_bus_unref(bus); + if (r >= 0) + return blocked; + } + } +#else + (void)d; +#endif + char *argv[] = { "busctl", "get-property", LOGIND_BUS, LOGIND_PATH, LOGIND_IFACE, "BlockInhibited", NULL }; + char *buf = NULL; + int rc = run_cmd(argv, NULL, NULL, 5.0, &buf, NULL); + bool blocked = (rc == 0 && buf && strstr(buf, "sleep") != NULL); + free(buf); + return blocked; +} + +static bool query_can_suspend(const struct daemon *d, char *out, size_t cap) +{ + out[0] = '\0'; +#ifdef HAVE_SD_BUS + if (!d->no_dbus) { + sd_bus *bus = NULL; + if (sd_bus_open_system(&bus) >= 0) { + sd_bus_error err = SD_BUS_ERROR_NULL; + sd_bus_message *reply = NULL; + int r = sd_bus_call_method(bus, LOGIND_BUS, LOGIND_PATH, LOGIND_IFACE, + "CanSuspend", &err, &reply, ""); + if (r >= 0) { + const char *ans = NULL; + if (sd_bus_message_read(reply, "s", &ans) >= 0 && ans) { + snprintf(out, cap, "%s", ans); + sd_bus_message_unref(reply); + sd_bus_error_free(&err); + sd_bus_unref(bus); + return true; + } + } + sd_bus_message_unref(reply); + sd_bus_error_free(&err); + sd_bus_unref(bus); + } + } +#else + (void)d; +#endif + char *argv[] = { "busctl", "call", LOGIND_BUS, LOGIND_PATH, LOGIND_IFACE, "CanSuspend", NULL }; + char *buf = NULL; + int rc = run_cmd(argv, NULL, NULL, 5.0, &buf, NULL); + if (rc == 0 && buf) { + char *s = trim_ws(buf); + /* Parse `s "yes"` -> `yes` */ + char *q1 = strchr(s, '"'); + char *q2 = q1 ? strchr(q1 + 1, '"') : NULL; + if (q1 && q2) { + size_t len = (size_t)(q2 - q1 - 1); + if (len >= cap) len = cap - 1; + memcpy(out, q1 + 1, len); + out[len] = '\0'; + } + free(buf); + return true; + } + free(buf); + return false; +} + +static void *request_suspend_thread(void *arg) +{ + struct daemon *d = arg; + char ans[32] = ""; + query_can_suspend(d, ans, sizeof(ans)); + + if (strcmp(ans, "na") == 0 || strcmp(ans, "no") == 0) { + log_msg("no suspend on this board: CanSuspend s \"%s\"", ans); + daemon_post_event(d, EV_SUSPEND_UNAVAILABLE); + return NULL; + } + if (strcmp(ans, "yes") != 0) { + log_msg("suspend refused for now: CanSuspend %s", ans); + daemon_post_event(d, EV_SUSPEND_REFUSED); + return NULL; + } + if (query_block_inhibited(d)) { + daemon_post_event(d, EV_SUSPEND_BLOCKED); + return NULL; + } + pthread_mutex_lock(&d->lock); + bool cancelled = d->cancel_flag; + pthread_mutex_unlock(&d->lock); + if (cancelled) { + daemon_post_event(d, EV_TIMEOUT); + return NULL; + } + char *argv[] = { "systemctl", "suspend", NULL }; + if (run_cmd(argv, NULL, NULL, 10.0, NULL, NULL) != 0) { + log_msg("systemctl suspend failed"); + daemon_post_event(d, EV_SUSPEND_BUSY); + } + return NULL; +} + +static bool lock_session(const struct user_info *u) +{ + char *a1[] = { "omarchy-shell", "lock", "lock", NULL }; + char *out = NULL; + int rc = run_as_user(u, a1, 5.0, &out, NULL); + bool ok = (rc == 0 && out && strcmp(trim_ws(out), "ok") == 0); + free(out); + if (!ok) + return false; + + double deadline = monotonic_now() + 8.0; + while (monotonic_now() < deadline) { + char *a2[] = { "omarchy-shell", "lock", "status", NULL }; + size_t len = 0; + out = NULL; + if (run_as_user(u, a2, 5.0, &out, &len) == 0 && out && + json_has_secure_true(out, len)) { + free(out); + return true; + } + free(out); + sleep_ms(100); + } + return false; +} + +static void *session_worker_thread(void *arg) +{ + struct daemon *d = arg; + for (;;) { + pthread_mutex_lock(&d->lock); + while (d->job_count == 0 && !d->stopping) + pthread_cond_wait(&d->job_cv, &d->lock); + if (d->stopping && d->job_count == 0) { + pthread_mutex_unlock(&d->lock); + return NULL; + } + enum session_job job = d->job_q[d->job_head]; + d->job_head = (d->job_head + 1) % MAX_JOBS_Q; + d->job_count--; + pthread_mutex_unlock(&d->lock); + + struct user_info u; + bool has_user = get_session_user(&u); + if (job == JOB_LOCK) { + if (has_user) { + char *ka[] = { "omarchy-keyboard", "hide", NULL }; + run_as_user(&u, ka, 5.0, NULL, NULL); + } + bool locked = !has_user || lock_session(&u); + if (locked) + usb_new_devices(d->usb_devices_dir, false); + daemon_post_event(d, locked ? EV_LOCK_OK : EV_LOCK_FAILED); + } else if (has_user && job == JOB_WOKE) { + char *wa[] = { "omarchy-shell", "-q", "lock", "woke", NULL }; + run_as_user(&u, wa, 5.0, NULL, NULL); + } else if (has_user && job == JOB_SCREENSHOT) { + char *sa[] = { "omarchy-capture-screenshot", "fullscreen", NULL }; + run_as_user(&u, sa, 15.0, NULL, NULL); + } else if (has_user && job == JOB_NOTIFY) { + char *na[] = { "notify-send", "Unable to lock", "The screen stays on.", NULL }; + run_as_user(&u, na, 5.0, NULL, NULL); + } + } +} + +static void *playback_worker_thread(void *arg) +{ + struct daemon *d = arg; + for (;;) { + pthread_mutex_lock(&d->lock); + while (!d->dark_flag && !d->stopping) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += 1; + pthread_cond_timedwait(&d->dark_cv, &d->lock, &ts); + } + bool stop = d->stopping; + bool dark = d->dark_flag; + bool was_playing = d->playing_shared; + pthread_mutex_unlock(&d->lock); + if (stop) + return NULL; + if (!dark) + continue; + + struct user_info u; + bool has_user = get_session_user(&u); + bool playing = query_block_inhibited(d); + if (!playing && has_user) { + char *pa[] = { "pw-dump", NULL }; + char *out = NULL; + size_t len = 0; + if (run_as_user(&u, pa, 2.0, &out, &len) == 0 && out) + playing = streams_running(out, len); + free(out); + } + if (playing != was_playing) + daemon_post_event(d, playing ? EV_PLAYING : EV_NOT_PLAYING); + sleep_ms(1000); + } +} + +/* -------------------------------------------------------------------------- + * Machine action execution + * -------------------------------------------------------------------------- */ + +static void begin_sleep_record(struct daemon *d) +{ + pthread_mutex_lock(&d->lock); + d->sleep_record_shared++; + d->kernel_attempted_shared = false; + pthread_mutex_unlock(&d->lock); + + d->sleep_begun = false; + d->awake = 0.0; + d->sleep_started = boottime_now(); + read_sleep_counters(d, &d->counters_ok, &d->counters_fail); + d->seen_ok = d->counters_ok; + d->seen_fail = d->counters_fail; + d->watching_unit = false; +} + +static void sleep_began(struct daemon *d, const char *how) +{ + if (!d->sleep_begun) { + d->sleep_begun = true; + d->awake = 0.0; + log_msg("sleep began: %s", how); + } + if (!d->watching_unit) { + d->watching_unit = true; + struct unit_watch_args *ua = malloc(sizeof(*ua)); + if (ua) { + ua->d = d; + pthread_mutex_lock(&d->lock); + ua->record = d->sleep_record_shared; + pthread_mutex_unlock(&d->lock); + pthread_t tid; + if (pthread_create(&tid, NULL, wait_for_unit_thread, ua) == 0) + pthread_detach(tid); + else + free(ua); + } + } +} + +static void sleep_finished(struct daemon *d, const char *how) +{ + if (!d->machine.inflight) + return; + int ok = 0, fail = 0; + read_sleep_counters(d, &ok, &fail); + const char *result = (ok != d->counters_ok) ? "slept" + : (fail != d->counters_fail) ? "aborted" : "not-entered"; + char irq[64] = "none"; + if (read_text_file("/sys/power/pm_wakeup_irq", irq, sizeof(irq))) + trim_ws(irq); + log_msg("sleep-ended result=%s seconds=%.3f wakeup_irq=%s end=%s awake=%.1f", + result, boottime_now() - d->sleep_started, irq, how, d->awake); + if (strcmp(how, "logind") != 0 && d->logind_asleep) + d->logind_busy_until = monotonic_now() + LOGIND_END_WAIT_SECONDS; + daemon_feed(d, strcmp(result, "aborted") == 0 ? EV_SLEEP_ABORTED : EV_SLEEP_ENDED, + false, 0.0); +} + +static void do_dark(struct daemon *d, double now) +{ + char panel[PATH_MAX]; + if (find_backlight(d, panel, sizeof(panel))) { + int current = 0; + bl_read_int(panel, "brightness", ¤t); + if (current > 0 && !d->fade.active) { + d->saved = (d->has_dim && d->dim_saved > 0) ? d->dim_saved : current; + d->has_saved = true; + remember_brightness(d, d->saved); + } + d->has_dim = false; + start_fade(d, panel, 0, now); + } +} + +static void do_light(struct daemon *d, enum pstate origin, double now) +{ + char panel[PATH_MAX]; + if (find_backlight(d, panel, sizeof(panel))) { + int maximum = 100; + bl_read_int(panel, "max_brightness", &maximum); + int half = maximum / 2; + if (half < 1) half = 1; + int target = (d->has_saved && d->saved > 0) ? d->saved : half; + if (target > maximum) target = maximum; + start_fade(d, panel, target, now); + } + double lit = monotonic_now(); + d->lit_at = lit; + d->has_lit_at = true; + const char *came_from = (origin == ST_SUSPENDING) ? "ASLEEP-or-entering" : state_name(origin); + log_msg("wake from=%s press=%.6f lit=%.6f press_to_lit_ms=%.1f", + came_from, d->key_time, lit, (lit - d->key_time) * 1000.0); +} + +static void daemon_feed(struct daemon *d, enum pevent ev, bool has_when, double when) +{ + enum pstate before = d->machine.state; + if (ev == EV_POWER || ev == EV_HOME) { + d->machine.empty = battery_empty(d->power_supplies_dir); + if (d->machine.empty && before != ST_ON) + log_msg("%s: the battery is empty and not charging: stays asleep", EVENT_NAMES[ev]); + } + double now = has_when ? when : monotonic_now(); + d->key_time = now; + struct action_list al = machine_handle(&d->machine, ev); + + if (al.count > 0 || before != d->machine.state || ev != EV_WAKE) { + char abuf[256] = ""; + size_t pos = 0; + for (int i = 0; i < al.count; i++) { + int w = snprintf(abuf + pos, sizeof(abuf) - pos, "%s%s", + i ? " " : "", action_name(al.items[i])); + if (w > 0 && pos + (size_t)w < sizeof(abuf)) + pos += (size_t)w; + } + log_msg("t=%.6f %s: %s -> %s %s", now, EVENT_NAMES[ev], + state_name(before), state_name(d->machine.state), + al.count ? abuf : "-"); + } + + pthread_mutex_lock(&d->lock); + d->inflight_shared = d->machine.inflight; + d->playing_shared = d->machine.playing; + pthread_mutex_unlock(&d->lock); + + for (int i = 0; i < al.count; i++) { + double tnow = monotonic_now(); + switch (al.items[i]) { + case ACT_DARK: + do_dark(d, tnow); + break; + case ACT_LIGHT: + do_light(d, before, tnow); + break; + case ACT_LOCK: + daemon_push_job(d, JOB_LOCK); + break; + case ACT_WOKE: + daemon_push_job(d, JOB_WOKE); + break; + case ACT_NOTIFY: + daemon_push_job(d, JOB_NOTIFY); + break; + case ACT_ARM_GRACE: + d->has_grace_at = true; + d->grace_at = tnow + d->idle_grace_seconds; + break; + case ACT_CANCEL_GRACE: + d->has_grace_at = false; + break; + case ACT_ARM_SETTLE: + d->has_settle_at = true; + d->settle_at = tnow + d->settle_seconds; + break; + case ACT_ARM_BACKOFF: + log_msg("%d sleeps in a row aborted: asking again in %.0f s", + ABORTS_BEFORE_DARK, BACKOFF_SECONDS); + d->has_settle_at = true; + d->settle_at = tnow + BACKOFF_SECONDS; + break; + case ACT_CANCEL_SETTLE: + d->has_settle_at = false; + break; + case ACT_ARM_RETRY: + d->has_settle_at = true; + d->settle_at = tnow + RETRY_SECONDS; + break; + case ACT_TAKE_INHIBITOR: + take_inhibitor(d); + break; + case ACT_RELEASE_INHIBITOR: + finish_dark_fade(d); + release_inhibitor(d); + break; + case ACT_CANCEL_SUSPEND: + pthread_mutex_lock(&d->lock); + d->cancel_flag = true; + pthread_mutex_unlock(&d->lock); + break; + case ACT_SUSPEND: + finish_dark_fade(d); + d->has_settle_at = false; + d->has_lit_at = false; + pthread_mutex_lock(&d->lock); + d->cancel_flag = false; + pthread_mutex_unlock(&d->lock); + begin_sleep_record(d); + release_inhibitor(d); + if (!arm_wakeup(d)) { + daemon_post_event(d, EV_SUSPEND_BUSY); + } else { + pthread_t tid; + if (pthread_create(&tid, NULL, request_suspend_thread, d) == 0) + pthread_detach(tid); + } + break; + } + } + + pthread_mutex_lock(&d->lock); + bool is_dark = (d->machine.state == ST_SETTLING || d->machine.state == ST_DARK); + d->dark_flag = is_dark; + if (is_dark) + pthread_cond_signal(&d->dark_cv); + pthread_mutex_unlock(&d->lock); +} + +/* -------------------------------------------------------------------------- + * Input devices, uevents, control socket, home action + * -------------------------------------------------------------------------- */ + +static int open_input(const char *path) +{ + int fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (fd < 0) + return -1; + int clkid = CLOCK_MONOTONIC; + if (ioctl(fd, EVIOCSCLOCKID, &clkid) < 0) { + close(fd); + return -1; + } + return fd; +} + +static bool cover_is_closed(int fd, bool *out_closed) +{ + unsigned long bits = 0; + if (ioctl(fd, EVIOCGSW(sizeof(bits)), &bits) < 0) + return false; + *out_closed = ((bits >> SW_MACHINE_COVER) & 1UL) != 0; + return true; +} + +static bool path_already_open(const struct daemon *d, const char *path) +{ + for (int i = 0; i < d->key_count; i++) + if (strcmp(d->keys[i].path, path) == 0) return true; + for (int i = 0; i < d->cover_count; i++) + if (strcmp(d->covers[i].path, path) == 0) return true; + return false; +} + +static void scan_keys(struct daemon *d) +{ + if (getenv("OMARCHY_POWERD_NO_SCAN")) + return; + DIR *dir = opendir("/sys/class/input"); + if (!dir) + return; + struct dirent *de; + while ((de = readdir(dir)) != NULL) { + if (strncmp(de->d_name, "event", 5) != 0) + continue; + char path[128]; + if (snprintf(path, sizeof(path), "/dev/input/%s", de->d_name) >= (int)sizeof(path)) + continue; + if (path_already_open(d, path)) + continue; + + char sw_path[PATH_MAX], key_path[PATH_MAX]; + char sw_buf[256], key_buf[512]; + snprintf(sw_path, sizeof(sw_path), "/sys/class/input/%s/device/capabilities/sw", de->d_name); + snprintf(key_path, sizeof(key_path), "/sys/class/input/%s/device/capabilities/key", de->d_name); + if (!read_text_file(sw_path, sw_buf, sizeof(sw_buf)) || + !read_text_file(key_path, key_buf, sizeof(key_buf))) + continue; + + if (reports_cover(sw_buf) && d->cover_count < MAX_INPUT_FDS) { + int fd = open_input(path); + bool closed = false; + if (fd < 0 || !cover_is_closed(fd, &closed)) { + if (fd >= 0) close(fd); + log_msg("cannot read %s: %s", path, strerror(errno)); + continue; + } + d->covers[d->cover_count].fd = fd; + snprintf(d->covers[d->cover_count].path, sizeof(d->covers[0].path), "%s", path); + d->covers[d->cover_count].dropped = false; + d->cover_count++; + cover_set_initial(&d->cover, fd, closed); + log_msg("cover: %s (%s)", path, closed ? "closed" : "open"); + continue; + } + if (reports_keys(key_buf) && d->key_count < MAX_INPUT_FDS) { + int fd = open_input(path); + if (fd < 0) { + log_msg("cannot read %s: %s", path, strerror(errno)); + continue; + } + d->keys[d->key_count].fd = fd; + snprintf(d->keys[d->key_count].path, sizeof(d->keys[0].path), "%s", path); + d->keys[d->key_count].dropped = false; + d->key_count++; + log_msg("keys: %s", path); + } + } + closedir(dir); +} + +static void home_action(struct daemon *d, double when) +{ + if (d->machine.state != ST_ON) { + log_msg("t=%.6f home-up: %s, nothing", when, state_name(d->machine.state)); + return; + } + struct user_info u; + if (!get_session_user(&u)) + return; + char uid_s[32]; + snprintf(uid_s, sizeof(uid_s), "%lu", (unsigned long)u.uid); + char *argv[] = { "pgrep", "-u", uid_s, "-x", "labwc", NULL }; + char *out = NULL; + char labwc_pid[32] = ""; + if (run_cmd(argv, NULL, NULL, 2.0, &out, NULL) == 0 && out) { + char *s = trim_ws(out); + char *sp = s; + while (*sp && !isspace((unsigned char)*sp)) sp++; + *sp = '\0'; + snprintf(labwc_pid, sizeof(labwc_pid), "%s", s); + } + free(out); + spawn_as_user(&u, "omarchy-home-button", labwc_pid[0] ? labwc_pid : NULL); + log_msg("t=%.6f home-up: omarchy-home-button", when); +} + +static void start_uevents(struct daemon *d) +{ + DIR *dir = opendir(d->power_supplies_dir); + if (dir) { + struct dirent *de; + while ((de = readdir(dir)) != NULL) { + if (de->d_name[0] == '.') continue; + char p[PATH_MAX]; + char buf[32]; + if (snprintf(p, sizeof(p), "%s/%s/online", d->power_supplies_dir, de->d_name) < (int)sizeof(p) && + read_text_file(p, buf, sizeof(buf))) { + supply_plugged_in(&d->supplies, de->d_name, strcmp(trim_ws(buf), "1") == 0); + } + } + closedir(dir); + } + if (d->no_dbus) + return; + int fd = socket(AF_NETLINK, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT); + if (fd < 0) + return; + struct sockaddr_nl nl; + memset(&nl, 0, sizeof(nl)); + nl.nl_family = AF_NETLINK; + nl.nl_groups = 1; + if (bind(fd, (struct sockaddr *)&nl, sizeof(nl)) < 0) { + close(fd); + return; + } + d->uevents_fd = fd; +} + +static void read_uevents(struct daemon *d) +{ + char buf[8192]; + for (;;) { + ssize_t n = recv(d->uevents_fd, buf, sizeof(buf), 0); + if (n <= 0) + break; + char name[64]; + bool online = false; + if (parse_supply_uevent(buf, (size_t)n, name, sizeof(name), &online)) { + if (supply_plugged_in(&d->supplies, name, online)) + daemon_feed(d, EV_WAKE, false, 0.0); + } + } +} + +static void undim(struct daemon *d) +{ + char panel[PATH_MAX]; + if (d->has_dim && find_backlight(d, panel, sizeof(panel))) { + if (d->machine.state == ST_ON) + bl_write_int(panel, d->dim_saved); + } + d->has_dim = false; +} + +static bool parse_ascii_digits(const char *s, int *out) +{ + if (!s || !*s) + return false; + for (const char *c = s; *c; c++) { + if (*c < '0' || *c > '9') + return false; + } + errno = 0; + long v = strtol(s, NULL, 10); + if (errno != 0 || v < 0 || v > INT_MAX) + return false; + *out = (int)v; + return true; +} + +static void handle_control(struct daemon *d, int server_fd) +{ + int conn = accept(server_fd, NULL, NULL); + if (conn < 0) + return; + struct timeval tv = { .tv_sec = 0, .tv_usec = 200000 }; + setsockopt(conn, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(conn, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + + char buf[128]; + ssize_t n = recv(conn, buf, sizeof(buf) - 1, 0); + if (n <= 0) { + close(conn); + return; + } + buf[n] = '\0'; + char *req = trim_ws(buf); + const char *reply = "unknown\n"; + char status_reply[32]; + + if (strcmp(req, "input") == 0) { + if (d->machine.state == ST_GRACE) + daemon_feed(d, EV_WAKE, false, 0.0); + reply = (d->machine.state == ST_ON) ? "lit\n" : "dark\n"; + } else if (strcmp(req, "unlocked") == 0) { + usb_new_devices(d->usb_devices_dir, true); + reply = "ok\n"; + } else if (strcmp(req, "status") == 0) { + snprintf(status_reply, sizeof(status_reply), "%s\n", state_name(d->machine.state)); + reply = status_reply; + } else if (strncmp(req, "brightness ", 11) == 0) { + reply = "held\n"; + char copy[128]; + snprintf(copy, sizeof(copy), "%s", req); + char *tok[5]; + int tc = 0; + char *p = copy; + while (*p && tc < 5) { + while (*p && isspace((unsigned char)*p)) p++; + if (!*p) break; + tok[tc++] = p; + while (*p && !isspace((unsigned char)*p)) p++; + if (*p) *p++ = '\0'; + } + char panel[PATH_MAX]; + int level = 0, expected = 0; + if (tc == 4 && find_backlight(d, panel, sizeof(panel)) && + parse_ascii_digits(tok[2], &level) && + parse_ascii_digits(tok[3], &expected)) { + const char *base = strrchr(panel, '/'); + const char *pname = base ? base + 1 : panel; + int current = 0, maximum = 0; + if (strcmp(tok[1], pname) == 0 && + bl_read_int(panel, "brightness", ¤t) && + bl_read_int(panel, "max_brightness", &maximum) && + d->machine.state == ST_ON && !d->fade.active && !d->has_dim && + current > 0 && current == expected && + level >= 1 && level <= maximum) { + bl_write_int(panel, level); + reply = "ok\n"; + } + } + } else if (strcmp(req, "als-state") == 0) { + reply = (d->machine.state == ST_ON && !d->fade.active && !d->has_dim) ? "lit\n" : "dark\n"; + } else if (strcmp(req, "dim") == 0) { + char panel[PATH_MAX]; + if (d->machine.state == ST_ON && !d->has_dim && find_backlight(d, panel, sizeof(panel))) { + int current = 0, maximum = 0; + if (bl_read_int(panel, "brightness", ¤t) && + bl_read_int(panel, "max_brightness", &maximum)) { + int level = maximum / 2; + if (level < 1) level = 1; + if (current > level) { + d->has_dim = true; + d->dim_saved = current; + d->dim_level = level; + bl_write_int(panel, level); + } + } + } + reply = "ok\n"; + } else if (strcmp(req, "undim") == 0) { + undim(d); + reply = "ok\n"; + } else if (strcmp(req, "wake") == 0 && d->machine.state != ST_ON && + battery_empty(d->power_supplies_dir)) { + reply = "ok\n"; + } else if (strcmp(req, "idle") == 0 || strcmp(req, "wake") == 0 || strcmp(req, "lock") == 0) { + daemon_feed(d, parse_event(req), false, 0.0); + reply = "ok\n"; + } else if (strcmp(req, "test-state") == 0) { + snprintf(status_reply, sizeof(status_reply), "%s %d %d %d %d %.6f\n", + state_name(d->machine.state), + d->machine.inflight ? 1 : 0, + d->sleep_begun ? 1 : 0, + d->logind_asleep ? 1 : 0, + d->buttons.home_in_combo ? 1 : 0, + d->has_lit_at ? d->lit_at : 0.0); + reply = status_reply; + } + + ssize_t r = send(conn, reply, strlen(reply), MSG_NOSIGNAL); + (void)r; + close(conn); +} + +static int open_control_socket(const struct daemon *d) +{ + char staging[PATH_MAX + 16]; + snprintf(staging, sizeof(staging), "%s.new", d->socket_path); + unlink(staging); + + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + if (strlen(staging) >= sizeof(addr.sun_path)) + return -1; + memcpy(addr.sun_path, staging, strlen(staging) + 1); + + int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) + return -1; + if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + close(fd); + return -1; + } + if (!d->no_chown) { + struct group *gr = getgrnam("video"); + if (gr) { + if (chown(staging, 0, gr->gr_gid) != 0) + log_msg("chown %s: %s", staging, strerror(errno)); + } + } + chmod(staging, 0660); + if (listen(fd, 8) < 0) { + close(fd); + unlink(staging); + return -1; + } + if (rename(staging, d->socket_path) < 0) { + close(fd); + unlink(staging); + return -1; + } + return fd; +} + +static void watch_kernel(struct daemon *d) +{ + if (!d->machine.inflight) + return; + int ok = 0, fail = 0; + read_sleep_counters(d, &ok, &fail); + if (ok == d->seen_ok && fail == d->seen_fail) + return; + if (fail != d->seen_fail) { + char dev[128] = "?", err_s[64] = "?", step[64] = "?"; + char p[PATH_MAX + 32]; + snprintf(p, sizeof(p), "%s/last_failed_dev", d->stats_dir); + if (read_text_file(p, dev, sizeof(dev))) trim_ws(dev); + snprintf(p, sizeof(p), "%s/last_failed_errno", d->stats_dir); + if (read_text_file(p, err_s, sizeof(err_s))) trim_ws(err_s); + snprintf(p, sizeof(p), "%s/last_failed_step", d->stats_dir); + if (read_text_file(p, step, sizeof(step))) trim_ws(step); + log_msg("kernel attempt failed: suspend_stats (%d, %d) device %s errno %s step %s", + ok, fail, dev[0] ? dev : "-", err_s, step); + arm_wakeup(d); + } + d->seen_ok = ok; + d->seen_fail = fail; + pthread_mutex_lock(&d->lock); + d->kernel_attempted_shared = true; + pthread_mutex_unlock(&d->lock); + sleep_began(d, "kernel"); +} + +static void count_awake(struct daemon *d, double now) +{ + double step = now - d->last_turn; + d->last_turn = now; + if (!d->machine.inflight) + return; + if (step < 0.0) step = 0.0; + if (step > AWAKE_STEP_MAX) step = AWAKE_STEP_MAX; + d->awake += step; + if (!d->sleep_begun && d->awake > SUSPEND_AWAKE_SECONDS) { + log_msg("suspend did not happen: not begun in %.1f s awake", d->awake); + daemon_feed(d, EV_TIMEOUT, false, 0.0); + } else if (d->sleep_begun && d->awake > SLEEP_END_AWAKE_SECONDS) { + log_msg("no end of the sleep seen in %.1f s awake", d->awake); + sleep_finished(d, "none"); + } +} + +static void start_lit(struct daemon *d) +{ + if (access(d->socket_path, F_OK) != 0) + restore_brightness(d); + char panel[PATH_MAX]; + int current = 0; + if (find_backlight(d, panel, sizeof(panel)) && + bl_read_int(panel, "brightness", ¤t) && current == 0) { + if (!d->has_saved || d->saved <= 0) { + d->saved = remembered_level(d, panel); + d->has_saved = true; + } + d->key_time = monotonic_now(); + do_light(d, ST_ON, d->key_time); + } +} + +static void handle_test_monitor_line(struct daemon *d, const char *line) +{ + if (strstr(line, "PrepareForSleep")) { + if (strstr(line, "true")) + handle_prepare_for_sleep(d, true); + else if (strstr(line, "false")) + handle_prepare_for_sleep(d, false); + } else if (strstr(line, "NameOwnerChanged") && strstr(line, LOGIND_BUS)) { + log_msg("logind started"); + d->logind_asleep = false; + renew_inhibitor(d); + } +} + +static void read_test_monitor(struct daemon *d) +{ + char chunk[4096]; + ssize_t n = read(d->test_monitor_fd, chunk, sizeof(chunk)); + if (n <= 0) + return; + for (ssize_t i = 0; i < n; i++) { + if (chunk[i] == '\n') { + d->monitor_buf[d->monitor_buf_len] = '\0'; + handle_test_monitor_line(d, d->monitor_buf); + d->monitor_buf_len = 0; + } else if (d->monitor_buf_len + 1 < sizeof(d->monitor_buf)) { + d->monitor_buf[d->monitor_buf_len++] = chunk[i]; + } + } +} + +static void daemon_run(struct daemon *d) +{ + g_sig_wake_fd = d->wake_write; + struct sigaction sa_t, sa_i; + memset(&sa_t, 0, sizeof(sa_t)); + sa_t.sa_handler = handle_sigterm; + sigaction(SIGTERM, &sa_t, NULL); + memset(&sa_i, 0, sizeof(sa_i)); + sa_i.sa_handler = handle_sigint; + sigaction(SIGINT, &sa_i, NULL); + + /* Test overrides for key/monitor fds */ + const char *kfd_s = getenv("OMARCHY_POWERD_KEY_FD"); + if (kfd_s && *kfd_s) { + int kfd = atoi(kfd_s); + fcntl(kfd, F_SETFL, O_NONBLOCK); + d->keys[d->key_count].fd = kfd; + snprintf(d->keys[d->key_count].path, sizeof(d->keys[0].path), "fake"); + d->key_count++; + } + const char *mfd_s = getenv("OMARCHY_POWERD_MONITOR_FD"); + if (mfd_s && *mfd_s) { + d->test_monitor_fd = atoi(mfd_s); + fcntl(d->test_monitor_fd, F_SETFL, O_NONBLOCK); + } + + start_lit(d); + int server_fd = open_control_socket(d); + if (server_fd < 0) { + perror("open_control_socket"); + return; + } + start_dbus(d); + take_inhibitor(d); + start_uevents(d); + + pthread_t sess_tid, play_tid; + pthread_create(&sess_tid, NULL, session_worker_thread, d); + pthread_detach(sess_tid); + pthread_create(&play_tid, NULL, playback_worker_thread, d); + pthread_detach(play_tid); + + log_msg("ready: ON"); + + while (!g_sigterm && !g_sigint) { + double now = monotonic_now(); + if (now >= d->next_scan) { + scan_keys(d); + d->next_scan = now + 5.0; + } + double delay = d->machine.inflight ? TICK_SECONDS : 1.0; + if (d->fade.active) { + double nf = next_frame(d, now); + if (nf < delay) delay = nf; + } + if (d->has_settle_at) { + double rem = d->settle_at - now; + if (rem < 0.0) rem = 0.0; + if (rem < delay) delay = rem; + } + if (d->has_grace_at) { + double rem = d->grace_at - now; + if (rem < 0.0) rem = 0.0; + if (rem < delay) delay = rem; + } + + struct pollfd pfds[MAX_INPUT_FDS * 2 + 5]; + int nfds = 0; + int key_start = nfds; + for (int i = 0; i < d->key_count; i++) { + pfds[nfds].fd = d->keys[i].fd; + pfds[nfds].events = POLLIN; + nfds++; + } + int cover_start = nfds; + for (int i = 0; i < d->cover_count; i++) { + pfds[nfds].fd = d->covers[i].fd; + pfds[nfds].events = POLLIN; + nfds++; + } + int idx_server = nfds; + pfds[nfds++] = (struct pollfd){ .fd = server_fd, .events = POLLIN }; + int idx_wake = nfds; + pfds[nfds++] = (struct pollfd){ .fd = d->wake_read, .events = POLLIN }; + int idx_bus = -1; +#ifdef HAVE_SD_BUS + if (d->bus) { + idx_bus = nfds; + pfds[nfds++] = (struct pollfd){ .fd = sd_bus_get_fd(d->bus), .events = POLLIN }; + } +#endif + int idx_mon = -1; + if (d->test_monitor_fd >= 0) { + idx_mon = nfds; + pfds[nfds++] = (struct pollfd){ .fd = d->test_monitor_fd, .events = POLLIN }; + } + int idx_uev = -1; + if (d->uevents_fd >= 0) { + idx_uev = nfds; + pfds[nfds++] = (struct pollfd){ .fd = d->uevents_fd, .events = POLLIN }; + } + + int timeout_ms = (int)(delay * 1000.0); + if (timeout_ms < 0) timeout_ms = 0; + if (delay > 0.0 && timeout_ms == 0) timeout_ms = 1; + poll(pfds, (nfds_t)nfds, timeout_ms); + + if (g_sigterm || g_sigint) + break; + + /* Keys first */ + for (int i = d->key_count - 1; i >= 0; i--) { + short rev = pfds[key_start + i].revents; + if (!(rev & (POLLIN | POLLHUP | POLLERR))) + continue; + struct input_event evs[64]; + ssize_t n = read(d->keys[i].fd, evs, sizeof(evs)); + if (n <= 0) { + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) + continue; + log_msg("keys lost: %s", strerror(errno)); + close(d->keys[i].fd); + d->keys[i] = d->keys[--d->key_count]; + continue; + } + int count = (int)(n / (ssize_t)sizeof(struct input_event)); + for (int j = 0; j < count; j++) { + if (evs[j].type != EV_KEY || (evs[j].value != 0 && evs[j].value != 1)) + continue; + if (evs[j].code != KEY_POWER && evs[j].code != KEY_HOMEPAGE && + evs[j].code != KEY_VOLUMEDOWN) + continue; + double when = (double)evs[j].time.tv_sec + (double)evs[j].time.tv_usec / 1e6; + enum button_result br = buttons_edge(&d->buttons, evs[j].code, + evs[j].value == 1, when, + d->machine.state == ST_ON); + if (br == BTN_NONE) + continue; + if (br == BTN_SCREENSHOT) { + log_msg("t=%.6f screenshot", when); + daemon_push_job(d, JOB_SCREENSHOT); + continue; + } + if (br == BTN_HOME_UP) { + home_action(d, when); + continue; + } + enum pevent pev = (br == BTN_POWER) ? EV_POWER : EV_HOME; + if (d->machine.inflight && d->has_lit_at && when <= d->lit_at) + log_msg("t=%.6f %s: consumed by the wake", when, EVENT_NAMES[pev]); + else + daemon_feed(d, pev, true, when); + } + } + + /* Smart Cover switches */ + for (int i = d->cover_count - 1; i >= 0; i--) { + short rev = pfds[cover_start + i].revents; + if (!(rev & (POLLIN | POLLHUP | POLLERR))) + continue; + struct input_event evs[64]; + ssize_t n = read(d->covers[i].fd, evs, sizeof(evs)); + if (n <= 0) { + if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) + continue; + log_msg("cover lost: %s", strerror(errno)); + cover_forget(&d->cover, d->covers[i].fd); + close(d->covers[i].fd); + d->covers[i] = d->covers[--d->cover_count]; + continue; + } + int count = (int)(n / (ssize_t)sizeof(struct input_event)); + bool dropped = d->covers[i].dropped; + bool resync = dropped; + for (int j = 0; j < count; j++) { + if (evs[j].type == EV_SYN && evs[j].code == SYN_DROPPED) + dropped = resync = true; + else if (evs[j].type == EV_SYN && evs[j].code == SYN_REPORT) + dropped = false; + } + if (dropped) { + d->covers[i].dropped = true; + continue; + } + d->covers[i].dropped = false; + if (resync) { + bool closed = false; + if (cover_is_closed(d->covers[i].fd, &closed)) { + double when = monotonic_now(); + enum pevent pev = cover_change(&d->cover, d->covers[i].fd, closed); + if (pev != EV_INVALID) { + log_msg("t=%.6f cover %s", when, closed ? "closed" : "opened"); + daemon_feed(d, pev, true, when); + } + } + } else { + for (int j = 0; j < count; j++) { + if (evs[j].type == EV_SW && evs[j].code == SW_MACHINE_COVER && + (evs[j].value == 0 || evs[j].value == 1)) { + bool closed = (evs[j].value == 1); + double when = (double)evs[j].time.tv_sec + + (double)evs[j].time.tv_usec / 1e6; + enum pevent pev = cover_change(&d->cover, d->covers[i].fd, closed); + if (pev != EV_INVALID) { + log_msg("t=%.6f cover %s", when, closed ? "closed" : "opened"); + daemon_feed(d, pev, true, when); + } + } + } + } + } + + /* Posted worker events */ + if (pfds[idx_wake].revents & POLLIN) { + char drain[256]; + while (read(d->wake_read, drain, sizeof(drain)) > 0) + ; + for (;;) { + pthread_mutex_lock(&d->lock); + if (d->ev_count == 0) { + pthread_mutex_unlock(&d->lock); + break; + } + struct event_item item = d->ev_q[d->ev_head]; + d->ev_head = (d->ev_head + 1) % MAX_EVENTS_Q; + d->ev_count--; + int cur_rec = d->sleep_record_shared; + pthread_mutex_unlock(&d->lock); + + if (item.is_sleep_over) { + if (item.sleep_record == cur_rec) + sleep_finished(d, "unit"); + } else { + daemon_feed(d, item.ev, false, 0.0); + } + } + } + +#ifdef HAVE_SD_BUS + if (idx_bus >= 0 && (pfds[idx_bus].revents & POLLIN)) { + while (sd_bus_process(d->bus, NULL) > 0) + ; + } +#else + (void)idx_bus; +#endif + if (idx_mon >= 0 && (pfds[idx_mon].revents & POLLIN)) + read_test_monitor(d); + if (pfds[idx_server].revents & POLLIN) + handle_control(d, server_fd); + if (idx_uev >= 0 && (pfds[idx_uev].revents & POLLIN)) + read_uevents(d); + + double tnow = monotonic_now(); + tick_fade(d, tnow); + watch_kernel(d); + keep_inhibitor(d, tnow); + if (d->has_grace_at && tnow >= d->grace_at) { + d->has_grace_at = false; + daemon_feed(d, EV_GRACE_ENDED, false, 0.0); + } + if (d->has_settle_at && tnow >= d->settle_at) { + d->has_settle_at = false; + daemon_feed(d, EV_SETTLE, false, 0.0); + } + count_awake(d, tnow); + } + + pthread_mutex_lock(&d->lock); + d->stopping = true; + pthread_cond_broadcast(&d->dark_cv); + pthread_cond_broadcast(&d->job_cv); + pthread_mutex_unlock(&d->lock); + + if (g_sigterm) + stop_brightness(d); + release_inhibitor(d); + close(server_fd); +#ifdef HAVE_SD_BUS + if (d->bus) { + sd_bus_slot_unref(d->slot_sleep); + sd_bus_slot_unref(d->slot_owner); + sd_bus_unref(d->bus); + } +#endif +} + +/* -------------------------------------------------------------------------- + * Unit-test harness (--test) + * -------------------------------------------------------------------------- */ + +static int run_test_mode(void) +{ + struct machine m; + machine_init(&m); + struct buttons btns; + memset(&btns, 0, sizeof(btns)); + struct cover_state cov; + memset(&cov, 0, sizeof(cov)); + struct supply_map smap; + memset(&smap, 0, sizeof(smap)); + struct daemon d; + daemon_init(&d); + + char line[4096]; + 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 (strcmp(line, "m_reset") == 0) { + machine_init(&m); + printf("OK\n"); + } else if (strncmp(line, "m_set ", 6) == 0) { + char st[32]; + int lok, sdue, inf, pl, ns, hr, ab, emp; + if (sscanf(line + 6, "%31s %d %d %d %d %d %d %d %d", + st, &lok, &sdue, &inf, &pl, &ns, &hr, &ab, &emp) == 9 && + parse_state_name(st, &m.state)) { + m.lock_ok = lok != 0; + m.settle_due = sdue != 0; + m.inflight = inf != 0; + m.playing = pl != 0; + m.no_suspend = ns != 0; + m.hold_release = hr != 0; + m.aborts = ab; + m.empty = emp != 0; + printf("OK\n"); + } else { + printf("ERR\n"); + } + } else if (strncmp(line, "m_handle ", 9) == 0) { + enum pevent ev = parse_event(line + 9); + if (ev == EV_INVALID) { + printf("ERR\n"); + } else { + struct action_list al = machine_handle(&m, ev); + printf("M %s %d %d %d %d %d %d %d %d |", + state_name(m.state), m.lock_ok, m.settle_due, + m.inflight, m.playing, m.no_suspend, + m.hold_release, m.aborts, m.empty); + for (int i = 0; i < al.count; i++) + printf(" %s", action_name(al.items[i])); + putchar('\n'); + } + } else if (strcmp(line, "b_reset") == 0) { + memset(&btns, 0, sizeof(btns)); + printf("OK\n"); + } else if (strncmp(line, "b_edge ", 7) == 0) { + char name[32]; + int down = 0, lit = 0; + double when = 0.0; + if (sscanf(line + 7, "%31s %d %lf %d", name, &down, &when, &lit) == 4) { + int code = strcmp(name, "power") == 0 ? KEY_POWER + : strcmp(name, "home") == 0 ? KEY_HOMEPAGE : KEY_VOLUMEDOWN; + enum button_result r = buttons_edge(&btns, code, down != 0, when, lit != 0); + const char *rn = r == BTN_POWER ? "power" + : r == BTN_HOME ? "home" + : r == BTN_HOME_UP ? "home-up" + : r == BTN_SCREENSHOT ? "screenshot" : "none"; + printf("B %s %d %d\n", rn, btns.home_in_combo ? 1 : 0, btns.home_woke ? 1 : 0); + } else { + printf("ERR\n"); + } + } else if (strcmp(line, "c_reset") == 0) { + memset(&cov, 0, sizeof(cov)); + printf("OK\n"); + } else if (strncmp(line, "c_change ", 9) == 0) { + int k = 0, cl = 0; + sscanf(line + 9, "%d %d", &k, &cl); + enum pevent ev = cover_change(&cov, k, cl != 0); + printf("VAL %s\n", ev == EV_INVALID ? "none" : EVENT_NAMES[ev]); + } else if (strncmp(line, "c_forget ", 9) == 0) { + cover_forget(&cov, atoi(line + 9)); + printf("OK\n"); + } else if (strncmp(line, "reports_cover ", 14) == 0) { + printf("VAL %d\n", reports_cover(line + 14) ? 1 : 0); + } else if (strcmp(line, "reports_cover") == 0) { + printf("VAL 0\n"); + } else if (strncmp(line, "reports_keys ", 13) == 0) { + printf("VAL %d\n", reports_keys(line + 13) ? 1 : 0); + } else if (strcmp(line, "reports_keys") == 0) { + printf("VAL 0\n"); + } else if (strncmp(line, "streams ", 8) == 0) { + printf("VAL %d\n", streams_running(line + 8, strlen(line + 8)) ? 1 : 0); + } else if (strncmp(line, "battery_empty ", 14) == 0) { + printf("VAL %d\n", battery_empty(line + 14) ? 1 : 0); + } else if (strncmp(line, "usb ", 4) == 0) { + int allow = 0; + char path[PATH_MAX]; + if (sscanf(line + 4, "%d %4095s", &allow, path) == 2) + usb_new_devices(path, allow != 0); + printf("OK\n"); + } else if (strncmp(line, "uevent ", 7) == 0) { + /* Escaped \0 as \x00 using '|' separator */ + char raw[1024]; + size_t rlen = strlen(line + 7); + if (rlen >= sizeof(raw)) rlen = sizeof(raw) - 1; + memcpy(raw, line + 7, rlen); + raw[rlen] = '\0'; + for (size_t i = 0; i < rlen; i++) + if (raw[i] == '|') raw[i] = '\0'; + char name[64]; + bool on = false; + if (parse_supply_uevent(raw, rlen, name, sizeof(name), &on)) + printf("VAL %s %d\n", name, on ? 1 : 0); + else + printf("NONE\n"); + } else if (strcmp(line, "s_reset") == 0) { + memset(&smap, 0, sizeof(smap)); + printf("OK\n"); + } else if (strncmp(line, "s_plug ", 7) == 0) { + char name[64]; + int on = 0; + sscanf(line + 7, "%63s %d", name, &on); + printf("VAL %d\n", supply_plugged_in(&smap, name, on != 0) ? 1 : 0); + } else if (strncmp(line, "bl_init ", 8) == 0) { + static char bdir[PATH_MAX], bpath[PATH_MAX], spath[PATH_MAX]; + double fade = 0.0; + sscanf(line + 8, "%4095s %4095s %4095s %lf", bdir, bpath, spath, &fade); + daemon_init(&d); + d.backlights_dir = bdir; + d.brightness_path = bpath; + d.socket_path = spath; + d.fade_seconds = fade; + g_quiet_log = true; + printf("OK\n"); + } else if (strcmp(line, "bl_restore") == 0) { + restore_brightness(&d); + printf("OK\n"); + } else if (strncmp(line, "bl_dark ", 8) == 0) { + do_dark(&d, strtod(line + 8, NULL)); + printf("OK\n"); + } else if (strncmp(line, "bl_light ", 9) == 0) { + double t = strtod(line + 9, NULL); + d.key_time = t; + do_light(&d, ST_SETTLING, t); + printf("OK\n"); + } else if (strncmp(line, "bl_tick ", 8) == 0) { + tick_fade(&d, strtod(line + 8, NULL)); + printf("VAL %d %d\n", d.fade.active ? 1 : 0, d.saved); + } else if (strcmp(line, "bl_finish_dark") == 0) { + finish_dark_fade(&d); + printf("VAL %d\n", d.fade.active ? 1 : 0); + } else if (strcmp(line, "bl_stop") == 0) { + stop_brightness(&d); + printf("OK\n"); + } else if (strcmp(line, "bl_start_lit") == 0) { + start_lit(&d); + printf("OK\n"); + } else if (strncmp(line, "bl_set_dim ", 11) == 0) { + sscanf(line + 11, "%d %d", &d.dim_saved, &d.dim_level); + d.has_dim = true; + printf("OK\n"); + } else { + printf("ERR\n"); + } + fflush(stdout); + } + return 0; +} + +int main(int argc, char **argv) +{ + if (argc > 1 && strcmp(argv[1], "--test") == 0) + return run_test_mode(); + + struct daemon d; + daemon_init(&d); + daemon_run(&d); + return 0; +} diff --git a/desktop/install-tree b/desktop/install-tree index 178f1590..f3ac5a6e 100755 --- a/desktop/install-tree +++ b/desktop/install-tree @@ -19,7 +19,7 @@ here=$(cd "$(dirname "$0")" && pwd) project=$(dirname "$here") shell=$here/shell config=$here/configuration omarchy=$root/usr/share/omarchy -for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$upstream/themes" "$upstream/bin" \ +for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/omarchy-powerd" "$upstream/themes" "$upstream/bin" \ "$upstream/themes/jade-horse/colors.toml" "$upstream/icons/papercraft" "$upstream/applications/foot.desktop" "$upstream/default/hypr/toggles/bar-glassy.lua" \ "$upstream/default/i18n/en/cli.json" "$upstream/install/helpers/as-root.sh" "$upstream/install/helpers/browser-policy.sh" \ "$upstream/default/chromium/policies/omarchy.json" "$upstream/default/firefox/policies.json" "$upstream/config/chromium-flags.conf" \ @@ -107,10 +107,11 @@ for set in "$omarchy"/icons/*/; do if [[ -f $set/btop.svg.tpl && ! -e $set/omactivity.svg.tpl ]]; then ln -s btop.svg.tpl "$set/omactivity.svg.tpl"; fi done -# The keyboard and the startup cursor helper. +# The keyboard, the startup cursor helper, and the power daemon. put "$build/wvkbd-mobintl" "$omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state" 755 put "$build/wtype" "$root/usr/libexec/omarchy-wtype" 755 put "$build/wtype.LICENSE" "$root/usr/share/licenses/omarchy-wtype/LICENSE" +put "$build/omarchy-powerd" "$root/usr/libexec/omarchy-powerd" 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 diff --git a/release/audit.py b/release/audit.py index cd218a00..80345243 100644 --- a/release/audit.py +++ b/release/audit.py @@ -15,8 +15,9 @@ from .public_root import sha -# The two compiled helpers of the omarchy-a package, of the root's architecture. +# The compiled helpers of the omarchy-a package, of the root's architecture. HELPERS = {'usr/libexec/omarchy-wtype': 'startup cursor helper', + 'usr/libexec/omarchy-powerd': 'power, lock and sleep daemon', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state': 'on-screen keyboard'} def private_firmware(orchard=None): diff --git a/system/overlay/usr/libexec/omarchy-powerd b/system/overlay/usr/libexec/omarchy-powerd deleted file mode 100755 index 37b2ccc3..00000000 --- a/system/overlay/usr/libexec/omarchy-powerd +++ /dev/null @@ -1,1330 +0,0 @@ -#!/usr/bin/python3 -"""The one owner of screen, lock request and sleep. See docs/power-and-lock.md. - -Machine is the state machine: no I/O, no clocks, every input defined in every -state. Daemon around it reads the keys, drives the backlight and talks to -logind and the session. The state is never inferred from brightness or files. -""" -import fcntl -import grp -import json -import os -from pathlib import Path -import pwd -import queue -import select -import signal -import socket -import struct -import subprocess -import sys -import threading -import time - -ON, GRACE, SETTLING, DARK, SUSPENDING = 'ON', 'GRACE', 'SETTLING', 'DARK', 'SUSPENDING' -STATES = (ON, GRACE, SETTLING, DARK, SUSPENDING) -EVENTS = ('power', 'home', 'wake', 'idle', 'settle', 'lock-ok', 'lock-failed', 'playing', 'not-playing', - 'suspend-refused', 'suspend-unavailable', 'suspend-blocked', 'suspend-busy', 'sleep-signal', 'sleep-ended', - 'sleep-aborted', 'timeout', 'grace-ended', 'lock') -IDLE_GRACE_SECONDS = 8.0 -FADE_SECONDS = 0.24 -SETTLE_SECONDS = 10.0 -# A sleep refused for now is asked for again after this, dark and locked meanwhile. -# (A board that cannot sleep at all stays DARK until pressed instead.) -RETRY_SECONDS = 60.0 -# Kernel attempts that aborted in a row, nothing pressed, before it stops asking for a while: -# a board whose suspend never completes would otherwise freeze for every attempt, every settle. -ABORTS_BEFORE_DARK = 3 -# How long it then stays dark and locked before it asks again; a press or a real sleep ends it. -BACKOFF_SECONDS = 600.0 -TICK_SECONDS = 0.05 -# A suspend asked for and not seen to begin (no PrepareForSleep, no kernel attempt) in this -# much time awake did not happen. Once it began, only its end ends it: logind's -# PrepareForSleep(false) or systemd-suspend finishing, and the kernel's counters say how. -SUSPEND_AWAKE_SECONDS = 30.0 -# A sleep that began and whose end was never seen, as a last resort. -SLEEP_END_AWAKE_SECONDS = 120.0 -# Time awake is what the loop ran: a gap between two of its turns longer than this was a -# freeze or a sleep, and counts as this much, whatever a kernel's clocks do in sleep. -AWAKE_STEP_MAX = 1.0 -# Every backlight write is a kernel uevent (backlight_generate_event) on the socket this -# loop watches: a fade writes once a frame, else each write wakes the loop for the next. -FRAME_SECONDS = 1 / 60 -# logind refuses a delay inhibitor until its sleep is over (PrepareForSleep(false)); if -# that is never seen, it is asked anyway this long after the end of systemd-suspend. -LOGIND_END_WAIT_SECONDS = 5.0 -# CLOCK_MONOTONIC stops in a sleep. (getattr: the tests also run where there is no boot time.) -SLEEP_CLOCK = getattr(time, 'CLOCK_BOOTTIME', time.CLOCK_MONOTONIC) -LOGIND = 'org.freedesktop.login1' - - -class Machine: - """state: see the invariants in docs/power-and-lock.md. - - inflight: a suspend was asked for and has not ended. It survives a wake - press (state ON): the panel lights at once, while systemd-suspend finishes. - """ - - def __init__(self): - self.state = ON - self.lock_ok = False - self.settle_due = False - self.inflight = False - self.playing = False - self.no_suspend = False - self.hold_release = False - self.aborts = 0 - # The battery is empty and nothing charges it (battery_empty()): - # Power and Home leave a dark tablet dark, so it sleeps until a - # charger brings it back ('wake' from plugging in; the session's - # wake requests are held back too), never lit to sleep again at once. - self.empty = False - - def _darken(self): - self.lock_ok = self.settle_due = self.no_suspend = self.playing = False - self.state = SETTLING - return ['dark', 'lock', 'arm-settle'] - - def _light(self, *first): - self.state, self.aborts = ON, 0 - self.playing = self.settle_due = False - return [*first, 'light', 'woke'] - - def _settle_again(self): - self.state, self.settle_due = SETTLING, False - # Suspend keeps aborting here: ask again, but not before the backoff. - return ['arm-backoff' if self.aborts >= ABORTS_BEFORE_DARK else 'arm-settle'] - - def _begin_suspend(self): - self.state, self.inflight = SUSPENDING, True - return ['suspend'] - - def _external_sleep(self, *first): - # Someone else asked logind to sleep: dark and locked first, then let it. - actions = list(first) - if self.state in (ON, GRACE): - self.lock_ok = False - if self.state == GRACE: - actions += ['cancel-grace'] - actions += ['dark', 'lock'] - self.state, self.inflight = SUSPENDING, True - if self.lock_ok: - actions.append('release-inhibitor') - else: - self.hold_release = True - return actions - - def _lock_answer(self, ok): - actions = [] - self.lock_ok = ok - if self.hold_release: - self.hold_release = False - actions.append('release-inhibitor') - return actions - - def handle(self, event): - """The actions of EVENT, in order; the state afterwards is self.state.""" - if event not in EVENTS: - raise ValueError(event) - if event == 'sleep-ended': - self.aborts = 0 - # A suspend ending or failing is bookkeeping unless it is what SUSPENDING waits for. - if event in ('sleep-ended', 'sleep-aborted', 'suspend-refused', 'suspend-unavailable', 'suspend-blocked', - 'suspend-busy', 'timeout') and self.state != SUSPENDING: - if self.inflight: - self.inflight = False - # Pressed dark again while the last sleep was finishing, and settled since. - if self.state == SETTLING and self.settle_due and self.lock_ok: - return ['take-inhibitor'] + self._begin_suspend() - return ['take-inhibitor'] - return [] - return getattr(self, '_' + self.state.lower())(event) - - def _on(self, event): - if event in ('power', 'lock'): - return self._darken() - if event == 'idle': - self.state = GRACE - self.lock_ok = False - return ['dark', 'arm-grace'] - if event == 'sleep-signal': - return [] if self.inflight else self._external_sleep() - if event == 'lock-ok': - return self._lock_answer(True) - if event == 'lock-failed': - return self._lock_answer(False) - return [] # home and wake: already lit; playing, settle: not relevant while lit - - def _grace(self, event): - if event in ('power', 'home', 'wake'): - return self._light('cancel-grace') - if event == 'grace-ended': - return self._darken() - if event == 'lock': # asked for explicitly: no more grace - return ['cancel-grace'] + self._darken() - if event == 'sleep-signal': - return self._external_sleep() - return [] - - def _settling(self, event): - if event in ('power', 'home') and self.empty: - return [] - if event in ('power', 'home', 'wake'): - return self._light('cancel-settle') - if event == 'settle': - self.settle_due = True - return self._begin_suspend() if self.lock_ok and not self.inflight else [] - if event == 'lock-ok': - actions = self._lock_answer(True) - return actions + (self._begin_suspend() if self.settle_due and not self.inflight else []) - if event == 'lock-failed': - # Never an unsecured desktop that looks locked. - return self._lock_answer(False) + self._light('cancel-settle', 'notify') - if event == 'playing': - self.state, self.playing = DARK, True - return ['cancel-settle'] - if event == 'sleep-signal': - return self._external_sleep('cancel-settle') - return [] - - def _dark(self, event): - if event in ('power', 'home') and self.empty: - return [] - if event in ('power', 'home', 'wake'): - return self._light() - if event == 'lock-ok': - return self._lock_answer(True) - if event == 'lock-failed': - return self._lock_answer(False) + self._light('notify') - if event == 'playing': - self.playing = True - return [] - if event == 'not-playing': - self.playing = False - return [] if self.no_suspend else self._settle_again() - if event == 'sleep-signal': - return self._external_sleep() - return [] - - def _suspending(self, event): - if event in ('power', 'home') and self.empty: - # The press woke the kernel; sleep-ended settles it again. - return [] - if event in ('power', 'home', 'wake'): - # The kernel aborts or ends the sleep for this press (wakeup_count). - return self._light('cancel-suspend') - if event == 'lock-ok': - return self._lock_answer(True) - if event == 'lock-failed': - return self._lock_answer(False) - if event in ('sleep-ended', 'sleep-aborted'): - # Nothing pressed: a charger, an alarm, an aborted attempt. Stay dark. - # Aborted with nothing pressed counts: a press aborts it too, but lands in ON. - if event == 'sleep-aborted': - self.aborts = min(self.aborts + 1, ABORTS_BEFORE_DARK) - self.inflight = False - return ['take-inhibitor'] + self._settle_again() - if event in ('suspend-busy', 'timeout'): - # It did not happen this time: try again, never dark for no reason. - self.inflight = False - return ['take-inhibitor'] + self._settle_again() - if event == 'suspend-refused': - # Refused this time (logind's CanSuspend): never dark and awake - # for good. Stay dark and locked, and ask again later. - self.inflight, self.state, self.settle_due = False, SETTLING, False - return ['take-inhibitor', 'arm-retry'] - if event == 'suspend-unavailable': - # This board cannot sleep: asking again changes nothing. Dark until pressed. - self.inflight, self.no_suspend, self.state = False, True, DARK - return ['take-inhibitor'] - if event == 'suspend-blocked': - self.inflight, self.playing, self.state = False, True, DARK - return ['take-inhibitor'] - return [] - - -def log(message): - print(message, flush=True) - - -POWER_SUPPLIES = Path('/sys/class/power_supply') -# UPower's PercentageAction: where it puts the tablet to sleep. -EMPTY_PERCENT = 2 - - -def battery_empty(supplies=POWER_SUPPLIES): - """Whether a battery is at UPower's action level and nothing charges it.""" - for supply in supplies.glob('*'): - try: - if (supply / 'type').read_text().strip() != 'Battery': - continue - if (supply / 'status').read_text().strip() != 'Discharging': - continue - if int((supply / 'capacity').read_text()) <= EMPTY_PERCENT: - return True - except (OSError, ValueError): - continue - return False - - -def parse_supply_uevent(message): - """(name, online) from a kernel uevent of a power supply that has an online state, else None.""" - fields = dict(item.split('=', 1) for item in message.decode(errors='replace').split('\0') if '=' in item) - if fields.get('SUBSYSTEM') != 'power_supply' or 'POWER_SUPPLY_ONLINE' not in fields: - return None - return fields.get('POWER_SUPPLY_NAME', ''), fields['POWER_SUPPLY_ONLINE'] == '1' - - -def plugged_in(known, name, online): - """Whether this report is a source being plugged in; remembers it in known.""" - was = known.get(name, False) - known[name] = online - return online and not was - - -def parse_sleep_signal(line): - """True or False from a `busctl --json=short monitor` line of PrepareForSleep, else None.""" - try: - message = json.loads(line) - if message.get('member') == 'PrepareForSleep': - return bool(message['payload']['data'][0]) - except (ValueError, KeyError, IndexError, TypeError, AttributeError): - pass - return None - - -def parse_logind_started(line): - """Whether a `busctl --json=short monitor` line says logind just took its name.""" - try: - message = json.loads(line) - if message.get('member') == 'NameOwnerChanged': - name, _, owner = message['payload']['data'] - return name == LOGIND and bool(owner) - except (ValueError, KeyError, TypeError, AttributeError): - pass - return False - - -def streams_running(dump): - """Whether `pw-dump` output has an audio or video playback stream that is running.""" - try: - for item in json.loads(dump): - info = item.get('info') or {} - media = (info.get('props') or {}).get('media.class', '') - if media.startswith('Stream/Output/') and info.get('state') == 'running': - return True - except (ValueError, AttributeError): - pass - return False - - -EV_KEY, KEY_VOLUMEDOWN, KEY_POWER, KEY_HOMEPAGE = 1, 114, 116, 172 -KEY_NAMES = {KEY_POWER: 'power', KEY_HOMEPAGE: 'home', KEY_VOLUMEDOWN: 'volume-down'} -EV_SW, SW_MACHINE_COVER = 5, 0x10 -EV_SYN, SYN_REPORT, SYN_DROPPED = 0, 0, 3 -# struct input_event: the time is two longs, of the kernel's width (16 bytes -# on 32-bit ARM, 24 on arm64), as in omarchy-mute-switch. -INPUT_EVENT = struct.Struct('llHHi') -EVIOCSCLOCKID = 0x400445a0 -SWITCH_BITMAP = struct.Struct('@L') -EVIOCGSW = 0x8000451b | (SWITCH_BITMAP.size << 16) -SOCKET = '/run/omarchy-powerd.sock' -# OMARCHY_PATH: the omarchy-a package's Omarchy tree. -SHELL_ROOT = '/usr/share/omarchy' -STATS = Path('/sys/power/suspend_stats') -WAKEUP_COUNT = Path('/sys/power/wakeup_count') -BACKLIGHTS = Path('/sys/class/backlight') -BRIGHTNESS = Path('/var/lib/omarchy-powerd/brightness') -USB_DEVICES = Path('/sys/bus/usb/devices') - - -def usb_new_devices(allowed): - """Whether newly plugged USB devices are enabled, on every USB host. - - Off while the screen is locked: a stick or a USB keyboard plugged into a - locked tablet stays off, also after the unlock, until it is plugged in - again unlocked. Devices already enabled stay as they are. - """ - for switch in sorted(USB_DEVICES.glob('usb*/authorized_default')): - try: - switch.write_text('1' if allowed else '0') - except OSError as error: - log(f'{switch}: {error}') - - -# A longer hold of Power is not a press: it is the start of a forced restart or DFU. -LONG_HOLD_SECONDS = 1.5 - - -def key_edges(data): - """(key name, down, kernel seconds) of every Power, Home and Volume Down press and release in evdev bytes.""" - edges = [] - for sec, usec, kind, code, value in INPUT_EVENT.iter_unpack(data): - if kind == EV_KEY and value in (0, 1) and code in KEY_NAMES: - edges.append((KEY_NAMES[code], value == 1, sec + usec / 1e6)) - return edges - - -def cover_edges(data): - """(closed, kernel seconds) of every Smart Cover switch change in evdev bytes.""" - return [(value == 1, sec + usec / 1e6) for sec, usec, kind, code, value in INPUT_EVENT.iter_unpack(data) - if kind == EV_SW and code == SW_MACHINE_COVER and value in (0, 1)] - - -def reports_cover(capabilities_sw): - """Whether an input device's sysfs capabilities/sw bitmap includes SW_MACHINE_COVER.""" - words = capabilities_sw.split() - if not words: - return False - # Hex words, most significant first; the last word holds bits 0-63 (or 0-31). - bits = int(words[-1], 16) - return bool(bits >> SW_MACHINE_COVER & 1) - - -def reports_keys(capabilities_key): - """Whether an input device's sysfs capabilities/key bitmap has Power, Home or Volume Down.""" - words = capabilities_key.split() - # Hex words of the kernel's long, most significant first. - width = struct.calcsize('L') * 8 - bits = 0 - for word in words: - bits = bits << width | int(word, 16) - return any(bits >> code & 1 for code in KEY_NAMES) - - -def open_input(path): - fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK) - try: - fcntl.ioctl(fd, EVIOCSCLOCKID, struct.pack('i', time.CLOCK_MONOTONIC)) - except OSError: - os.close(fd) - raise - return fd - - -def cover_is_closed(fd): - bits = bytearray(SWITCH_BITMAP.size) - fcntl.ioctl(fd, EVIOCGSW, bits) - return bool(SWITCH_BITMAP.unpack(bits)[0] & (1 << SW_MACHINE_COVER)) - - -class Cover: - """The Smart Cover from its switches: closing locks, opening wakes. - - An iPad has two hall sensors, each its own input device. The cover is - closed while any of them reports closed; the machine sees one 'lock' - when it closes and one 'wake' when it opens again. - """ - - def __init__(self): - self.closed = {} - - def change(self, source, closed): - """The machine event of one switch report ('lock', 'wake'), or None.""" - before = any(self.closed.values()) - self.closed[source] = closed - after = any(self.closed.values()) - if after == before: - return None - return 'lock' if after else 'wake' - - def forget(self, source): - self.closed.pop(source, None) - - -class Buttons: - """The machine's key events from Power and Home edges. - - Home and a Power press on a dark screen act at once, so a wake stays as - fast as the press. On a lit screen Power darkens on release, and only - after a short press alone. Home and Power pressed together on a lit - screen take a screenshot when the first of them comes up, if that is - soon: held (the DFU and restart combination), they do nothing, and a - restart never releases them at all. Volume Down and Power do the same, - for a phone without Home; Volume Down alone stays labwc's. Home let go after a press alone on a - lit screen is 'home-up': the session's Home action (omarchy-home-button). - It comes from the button itself, so no keyboard state, compositor - binding or held modifier stands between the press and the action. - """ - - def __init__(self): - self.held = None # Power down on a lit screen since - self.spoiled = False # that Power press is not a press alone - self.home_down = None # Home down since - self.volume_down = None # Volume Down down since - self.combo = None # both down on a lit screen since - self.combo_spent = False - self.home_in_combo = False # the last Home press was part of a combination - self.home_woke = False # the last Home press came on a dark screen and woke it - - def _start_combo(self, when): - self.spoiled = True - self.combo, self.combo_spent = when, False - if self.home_down is not None: - self.home_in_combo = True - - def _end_combo(self, when): - if self.combo is None or self.combo_spent: - return None - self.combo_spent = True - return 'screenshot' if when - self.combo < LONG_HOLD_SECONDS else None - - def _both_up(self): - if self.held is None and self.home_down is None and self.volume_down is None: - self.combo = None - - def edge(self, name, down, when, lit): - """The event of one edge (a machine event or 'screenshot'), or None.""" - if name == 'volume-down': - if down: - self.volume_down = when - if self.held is not None: - self._start_combo(when) - return None - self.volume_down = None - event = self._end_combo(when) - self._both_up() - return event - if name == 'home': - if down: - self.home_down, self.home_in_combo, self.home_woke = when, False, not lit - if self.held is not None: - self._start_combo(when) - return 'home' - pressed = self.home_down is not None - self.home_down = None - event = self._end_combo(when) - self._both_up() - if event is None and pressed and not self.home_in_combo and not self.home_woke: - return 'home-up' - return event - if down: - if not lit: - self.held = None - return 'power' - self.held, self.spoiled = when, False - if self.home_down is not None or self.volume_down is not None: - self._start_combo(when) - return None - if self.held is None: - return None - event = self._end_combo(when) - short = when - self.held < LONG_HOLD_SECONDS and not self.spoiled - self.held = None - self._both_up() - if event or self.combo is not None or self.spoiled: - return event - return 'power' if short else None - - -def command(*argv, timeout=5, **options): - return subprocess.run(argv, capture_output=True, text=True, timeout=timeout, **options) - - -def session_user(): - """The desktop user on seat0, or None for the greeter (nothing to lock) or no session.""" - session = command('loginctl', 'show-seat', 'seat0', '-p', 'ActiveSession', '--value').stdout.strip() - if not session: - return None - fields = dict(line.split('=', 1) for line in - command('loginctl', 'show-session', session, '-p', 'Name', '-p', 'Class').stdout.splitlines() - if '=' in line) - if fields.get('Class') != 'user' or not fields.get('Name'): - return None - return pwd.getpwnam(fields['Name']) - - -def user_env(user): - return {'HOME': user.pw_dir, 'USER': user.pw_name, 'XDG_RUNTIME_DIR': f'/run/user/{user.pw_uid}', - 'OMARCHY_PATH': SHELL_ROOT, 'PATH': '/usr/local/bin:/usr/bin'} - - -def spawn_as_user(user, *argv, env=None): - """Start ARGV as the user and return at once (as_user waits for it).""" - return subprocess.Popen(('setpriv', f'--reuid={user.pw_uid}', f'--regid={user.pw_gid}', '--init-groups', '--', - *argv), env={**user_env(user), **(env or {})}, cwd='/', - stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - start_new_session=True) - - -def as_user(user, *argv, timeout=5): - env = user_env(user) - # setpriv looks the groups up in the child. In here, os.getgrouplist holds - # Python's interpreter lock through NSS, and nss-systemd (group merges - # with it) answers only once systemd has finished a sleep: the whole - # daemon, the wake's backlight fade included, stood still up to a second. - return command('setpriv', f'--reuid={user.pw_uid}', f'--regid={user.pw_gid}', '--init-groups', '--', - *argv, timeout=timeout, env=env, cwd='/') - - -class Daemon: - def __init__(self): - self.machine = Machine() - self.cover = Cover() - self.covers = {} - self.cover_dropped = set() - self.events = queue.Queue() - self.wake_read, self.wake_write = os.pipe() - os.set_blocking(self.wake_read, False) - self.keys = {} - self.next_scan = 0.0 - self.settle_at = None - self.grace_at = None - self.fade = None - self.saved = None - self.counters = None - self.sleep_started = None - self.buttons = Buttons() - self.sleep_record = 0 # which sleep the unit watcher's end belongs to - self.sleep_begun = False # logind or the kernel is on it: only its end ends it - self.kernel_attempted = False - self.awake = 0.0 # seconds this loop ran since the sleep was asked for (or began) - self.last_turn = time.monotonic() - self.logind_asleep = False # PrepareForSleep(true) seen, (false) not yet - self.logind_busy_until = float('inf') - self.monitor_buffer = b'' - self.cancel = threading.Event() - self.dim_saved = None - self.dim_level = None - self.dark = threading.Event() - self.session_jobs = queue.Queue() - self.inhibitor = None - self.monitor = None - self.key_time = None - self.stopping = False - self.want_inhibitor = False - self.next_inhibitor = 0.0 - self.lit_at = None - self.watching_unit = False - self.supplies = {} - self.uevents = None - - # --- plumbing ----------------------------------------------------------- - def post(self, event): - self.events.put(event) - os.write(self.wake_write, b'.') - - def backlight(self): - panels = sorted(BACKLIGHTS.iterdir()) - return panels[0] if len(panels) == 1 else None - - def start_uevents(self): - """Being plugged in lights the screen, as on any tablet; being unplugged does not.""" - for supply in Path('/sys/class/power_supply').glob('*'): - try: - self.supplies[supply.name] = (supply / 'online').read_text().strip() == '1' - except OSError: - pass # a battery has no online state - try: - self.uevents = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM | socket.SOCK_NONBLOCK, 15) - self.uevents.bind((0, 1)) - except (AttributeError, OSError) as error: # AttributeError: no netlink on this system - log(f'no power supply events: {error}') - self.uevents = None - - def read_uevents(self): - try: - while True: - report = parse_supply_uevent(self.uevents.recv(8192)) - if report and plugged_in(self.supplies, *report): - self.feed('wake') - except BlockingIOError: - pass - except OSError as error: # the kernel dropped some: the next report sets it right - log(f'power supply events: {error}') - - def scan_keys(self): - for device in Path('/sys/class/input').glob('event*'): - path = f'/dev/input/{device.name}' - if path in self.covers.values() or path in self.keys.values(): - continue - try: - sw = (device / 'device/capabilities/sw').read_text() - key = (device / 'device/capabilities/key').read_text() - except OSError: - continue - if reports_cover(sw): - fd = None - try: - fd = open_input(path) - closed = cover_is_closed(fd) - except OSError as error: - if fd is not None: - os.close(fd) - log(f'cannot read {path}: {error}') - continue - self.covers[fd] = path - log(f'cover: {path} ({"closed" if closed else "open"})') - # Only remember the state: a cover found closed is no reason to lock. - self.cover.closed[fd] = closed - continue - # The iPad's buttons are gpio-keys; a keyboard's Power or Home key, or - # the simulator's buttons on QEMU's virtual keyboard, count the same. - if not reports_keys(key): - continue - try: - fd = open_input(path) - except OSError as error: - log(f'cannot read {path}: {error}') - continue - self.keys[fd] = path - log(f'keys: {path}') - - def read_cover(self, fd): - data = os.read(fd, INPUT_EVENT.size * 64) - if not data: - raise OSError('end of cover input') - - # After an overrun, wait for the first complete packet. EVIOCGSW - # samples current state and flushes queued switch events. Discard - # this batch as well since the snapshot already accounts for it. - dropped = fd in self.cover_dropped - resync = dropped - for _, _, kind, code, _ in INPUT_EVENT.iter_unpack(data): - if kind == EV_SYN and code == SYN_DROPPED: - dropped = resync = True - elif kind == EV_SYN and code == SYN_REPORT: - dropped = False - if dropped: - self.cover_dropped.add(fd) - return - self.cover_dropped.discard(fd) - edges = ([(cover_is_closed(fd), time.monotonic())] - if resync else cover_edges(data)) - for closed, when in edges: - event = self.cover.change(fd, closed) - if event: - log(f't={when:.6f} cover {"closed" if closed else "opened"}') - self.feed(event, when) - - def logind_busy(self): - """logind is still in its sleep: it refuses delay inhibitors ("already running").""" - return self.logind_asleep and time.monotonic() < self.logind_busy_until - - def take_inhibitor(self): - """Not while logind is still in a sleep: keep_inhibitor() takes it once it is over, or again if refused.""" - self.want_inhibitor = True - if self.logind_busy(): - return - if self.inhibitor is None or self.inhibitor.poll() is not None: - self.inhibitor = subprocess.Popen(['systemd-inhibit', '--what=sleep', '--mode=delay', - '--who=omarchy-powerd', '--why=Lock and darken first', - 'sleep', 'infinity']) - - def keep_inhibitor(self): - # Not during a sleep: after it ended, then slowly if logind still refused. - if (self.want_inhibitor and not self.machine.inflight and not self.logind_busy() - and (self.inhibitor is None or self.inhibitor.poll() is not None) - and time.monotonic() >= self.next_inhibitor): - self.next_inhibitor = time.monotonic() + 2 - self.take_inhibitor() - - def release_inhibitor(self): - self.want_inhibitor = False - if self.inhibitor is not None: - self.inhibitor.terminate() - self.inhibitor.wait() - self.inhibitor = None - - def renew_inhibitor(self): - """A logind that started again owes us nothing: ask the new one.""" - if self.want_inhibitor: - self.release_inhibitor() - self.take_inhibitor() - - def start_monitor(self): - # Unbuffered bytes: read_monitor() takes every line a read brings. A buffered - # readline() left the later lines of a read behind, unseen by select(). - self.monitor_buffer = b'' - self.monitor = subprocess.Popen( - ['busctl', '--json=short', 'monitor', LOGIND, - "--match=type='signal',interface='org.freedesktop.login1.Manager',member='PrepareForSleep'", - f"--match=type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='{LOGIND}'"], - stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0) - - def read_monitor(self): - chunk = os.read(self.monitor.stdout.fileno(), 65536) - if not chunk: - self.monitor.wait() - self.start_monitor() - return - *lines, self.monitor_buffer = (self.monitor_buffer + chunk).split(b'\n') - for line in lines: - self.monitor_line(line.decode(errors='replace')) - - def monitor_line(self, line): - if parse_logind_started(line): - log('logind started') - self.logind_asleep = False # a new logind is in no sleep - self.renew_inhibitor() - return - sleeping = parse_sleep_signal(line) - if sleeping is None: - return - self.logind_asleep, self.logind_busy_until = sleeping, float('inf') - if sleeping and self.machine.inflight: - self.sleep_began('logind') # ours: logind is on it - elif sleeping: - # Someone else's suspend: a press must end it just the same. - self.lit_at = None - self.begin_sleep_record() - self.arm_wakeup() - self.feed('sleep-signal') - self.sleep_began('logind') - else: - self.sleep_finished('logind') - - def sleep_counters(self): - return tuple(int((STATS / name).read_text()) for name in ('success', 'fail')) - - # --- the machine -------------------------------------------------------- - def feed(self, event, when=None): - before = self.machine.state - if event in ('power', 'home'): - self.machine.empty = battery_empty() - if self.machine.empty and before != ON: - log(f'{event}: the battery is empty and not charging: stays asleep') - when = time.monotonic() if when is None else when - self.key_time = when - actions = self.machine.handle(event) - # A lock-screen swipe sends many a wake; keys are always logged, consumed ones too. - if actions or before != self.machine.state or event != 'wake': - log(f't={when:.6f} {event}: {before} -> {self.machine.state} {" ".join(actions) or "-"}') - for action in actions: - getattr(self, 'do_' + action.replace('-', '_'))(before) - self.dark.set() if self.machine.state in (SETTLING, DARK) else self.dark.clear() - - def undim(self): - panel = self.backlight() - if self.dim_saved is not None and panel: - current = int((panel / 'brightness').read_text()) - if self.machine.state == ON: - (panel / 'brightness').write_text(f'{self.dim_saved}\n') - self.dim_saved = self.dim_level = None - - def do_dark(self, _): - panel = self.backlight() - if panel: - current = int((panel / 'brightness').read_text()) - if current > 0 and self.fade is None: - self.saved = self.dim_saved or current - self.remember_brightness(self.saved) - self.dim_saved = self.dim_level = None - self.start_fade(panel, 0) - - def start_fade(self, panel, target): - current = int((panel / 'brightness').read_text()) - if FADE_SECONDS <= 0 or current == target: - self.fade = None - (panel / 'brightness').write_text(f'{target}\n') - return - # (panel, from, to, began, last write): the first frame is written at once. - self.fade = (panel, current, target, time.monotonic(), float('-inf')) - - def next_frame(self): - """Seconds until the fade's next write is due (0 without a fade written yet).""" - return max(0.0, self.fade[4] + FRAME_SECONDS - time.monotonic()) - - def tick_fade(self): - if self.fade is None: - return - panel, start, target, began, written = self.fade - now = time.monotonic() - t = min(1.0, max(0.0, (now - began) / FADE_SECONDS)) - # One write a frame: each write's uevent wakes this loop, which must not write again at once. - if t < 1.0 and now - written < FRAME_SECONDS: - return - eased = t * t * (3.0 - 2.0 * t) - (panel / 'brightness').write_text(f'{round(start + (target - start) * eased)}\n') - self.fade = None if t >= 1.0 else (panel, start, target, began, now) - - def finish_dark_fade(self): - # A suspend must never freeze halfway through a visual transition. - if self.fade is not None and self.fade[2] == 0: - (self.fade[0] / 'brightness').write_text('0\n') - self.fade = None - - def remember_brightness(self, level): - """The last lit level, for the next boot; a hard reset keeps it too.""" - try: - BRIGHTNESS.parent.mkdir(parents=True, exist_ok=True) - temporary = BRIGHTNESS.with_suffix('.new') - temporary.write_text(f'{level}\n') - os.replace(temporary, BRIGHTNESS) - except OSError as error: - log(f'brightness not remembered: {error}') - - def remembered_level(self, panel): - """The remembered level, never too dim to see; full without one.""" - maximum = int((panel / 'max_brightness').read_text()) - try: - level = max(int(BRIGHTNESS.read_text()), max(1, maximum // 20)) - except (OSError, ValueError): - level = maximum - return min(level, maximum) - - def restore_brightness(self): - """First start of a boot: the remembered level; full on the first boot.""" - panel = self.backlight() - if not panel: - return - self.saved = self.remembered_level(panel) - (panel / 'brightness').write_text(f'{self.saved}\n') - - def stop_brightness(self, *_): - """Shutdown or restart: a level changed since the last dark, unless the panel is dark now. - - A restart (an update of the package) starts the next daemon in ON with - the panel as it finds it, and it knows nothing of a dim or a fade: the - panel is left at the level the user set, or dark for it to light.""" - panel = self.backlight() - if panel: - if self.dim_saved is not None and self.machine.state == ON and self.fade is None: - (panel / 'brightness').write_text(f'{self.dim_saved}\n') - elif self.fade is not None: - (panel / 'brightness').write_text(f'{self.fade[2]}\n') - current = int((panel / 'brightness').read_text()) - if self.fade is not None and self.saved: - self.remember_brightness(self.saved) - elif current > 0: - self.remember_brightness(current) - raise SystemExit(0) - - def do_light(self, origin): - panel = self.backlight() - if panel: - maximum = int((panel / 'max_brightness').read_text()) - self.start_fade(panel, min(self.saved or max(1, maximum // 2), maximum)) - lit = self.lit_at = time.monotonic() - came_from = 'ASLEEP-or-entering' if origin == SUSPENDING else origin - log(f'wake from={came_from} press={self.key_time:.6f} lit={lit:.6f} ' - f'press_to_lit_ms={(lit - self.key_time) * 1000:.1f}') - - def do_lock(self, _): - self.session_jobs.put('lock') - - def do_woke(self, _): - self.session_jobs.put('woke') - - def do_notify(self, _): - self.session_jobs.put('notify') - - def do_arm_grace(self, _): - self.grace_at = time.monotonic() + IDLE_GRACE_SECONDS - - def do_cancel_grace(self, _): - self.grace_at = None - - def do_arm_settle(self, _): - self.settle_at = time.monotonic() + SETTLE_SECONDS - - def do_arm_backoff(self, _): - log(f'{ABORTS_BEFORE_DARK} sleeps in a row aborted: asking again in {BACKOFF_SECONDS:.0f} s') - self.settle_at = time.monotonic() + BACKOFF_SECONDS - - def do_cancel_settle(self, _): - self.settle_at = None - - def do_arm_retry(self, _): - self.settle_at = time.monotonic() + RETRY_SECONDS - - def do_take_inhibitor(self, _): - self.take_inhibitor() - - def do_release_inhibitor(self, _): - self.finish_dark_fade() - self.release_inhibitor() - - def do_cancel_suspend(self, _): - self.cancel.set() - - def arm_wakeup(self): - """From here on the kernel aborts or ends the sleep for any key press.""" - try: - WAKEUP_COUNT.write_text(WAKEUP_COUNT.read_text().strip() + '\n') - return True - except OSError as error: - log(f'wakeup_count: {error}') - return False - - def begin_sleep_record(self): - self.sleep_record += 1 - self.sleep_begun = self.kernel_attempted = False - self.awake = 0.0 - self.sleep_started = time.clock_gettime(SLEEP_CLOCK) - self.counters = self.seen_counters = self.sleep_counters() - self.watching_unit = False - - def sleep_began(self, how): - """logind announced it, or the kernel attempted it: from now on only its end ends it.""" - if not self.sleep_begun: - self.sleep_begun, self.awake = True, 0.0 - log(f'sleep began: {how}') - if not self.watching_unit: - self.watching_unit = True - threading.Thread(target=self.wait_for_unit, args=(self.sleep_record,), daemon=True).start() - - def do_suspend(self, _): - self.finish_dark_fade() - self.settle_at = None - self.lit_at = None - self.cancel.clear() - self.begin_sleep_record() - self.release_inhibitor() - if not self.arm_wakeup(): - self.post('suspend-busy') - return - threading.Thread(target=self.request_suspend, daemon=True).start() - - # --- workers: never in the event loop ----------------------------------- - def block_inhibited(self): - result = command('busctl', 'get-property', 'org.freedesktop.login1', '/org/freedesktop/login1', - 'org.freedesktop.login1.Manager', 'BlockInhibited') - return 'sleep' in result.stdout - - def request_suspend(self): - try: - answer = command('busctl', 'call', 'org.freedesktop.login1', '/org/freedesktop/login1', - 'org.freedesktop.login1.Manager', 'CanSuspend').stdout.strip() - if answer in ('s "na"', 's "no"'): - log(f'no suspend on this board: CanSuspend {answer}') - self.post('suspend-unavailable') - elif answer != 's "yes"': - log(f'suspend refused for now: CanSuspend {answer}') - self.post('suspend-refused') - elif self.block_inhibited(): - self.post('suspend-blocked') - elif self.cancel.is_set(): - self.post('timeout') # pressed before it was asked for: nothing will end it - elif command('systemctl', 'suspend', timeout=10).returncode: - log('systemctl suspend failed') - self.post('suspend-busy') - except (OSError, subprocess.SubprocessError) as error: - log(f'suspend request: {error}') - self.post('suspend-busy') - - def session_worker(self): - while True: - job = self.session_jobs.get() - try: - user = session_user() - if job == 'lock': - if user is not None: - # The on-screen keyboard must not stay up over the lock screen. - as_user(user, 'omarchy-keyboard', 'hide') - locked = user is None or self.lock_session(user) - if locked: - usb_new_devices(False) - self.post('lock-ok' if locked else 'lock-failed') - elif user is not None and job == 'woke': - as_user(user, 'omarchy-shell', '-q', 'lock', 'woke') - elif user is not None and job == 'screenshot': - # Omarchy's capture service; it flashes the screen once the shot is taken. - as_user(user, 'omarchy-capture-screenshot', 'fullscreen', timeout=15) - elif user is not None and job == 'notify': - as_user(user, 'notify-send', 'Unable to lock', 'The screen stays on.') - except (OSError, KeyError, ValueError, subprocess.SubprocessError) as error: - log(f'session {job}: {error}') - if job == 'lock': - self.post('lock-failed') - - def home_action(self, when): - """Home let go after a press alone: the session's Home, at once. - - Started, not waited for: the script tells one press from two by - when each starts. Only on a lit screen (a wake's press was handled - above); the script itself leaves a locked session alone. - """ - if self.machine.state != ON: - log(f't={when:.6f} home-up: {self.machine.state}, nothing') - return - try: - user = session_user() - if user is None: - return - labwc = command('pgrep', '-u', str(user.pw_uid), '-x', 'labwc').stdout.split() - spawn_as_user(user, 'omarchy-home-button', env={'LABWC_PID': labwc[0]} if labwc else None) - log(f't={when:.6f} home-up: omarchy-home-button') - except (OSError, KeyError, ValueError, subprocess.SubprocessError) as error: - log(f'home: {error}') - - def lock_session(self, user): - if as_user(user, 'omarchy-shell', 'lock', 'lock').stdout.strip() != 'ok': - return False - deadline = time.monotonic() + 8 - while time.monotonic() < deadline: - if json.loads(as_user(user, 'omarchy-shell', 'lock', 'status').stdout or '{}').get('secure'): - return True - time.sleep(0.1) - return False - - def playback_worker(self): - while not self.stopping: - self.dark.wait(1) - if not self.dark.is_set(): - continue - try: - user = session_user() - playing = self.block_inhibited() or ( - user is not None and streams_running(as_user(user, 'pw-dump', timeout=2).stdout)) - except (OSError, KeyError, ValueError, subprocess.SubprocessError) as error: - # No answer is not "nothing is playing". - log(f'playback check: {error}') - time.sleep(1) - continue - if playing != self.machine.playing: - self.post('playing' if playing else 'not-playing') - time.sleep(1) - - # --- control socket ----------------------------------------------------- - def control(self, server): - connection, _ = server.accept() - with connection: - connection.settimeout(0.2) - try: - request = connection.recv(64).decode().strip() - if request == 'input': - if self.machine.state == GRACE: - self.feed('wake') - connection.sendall(b'lit\n' if self.machine.state == ON else b'dark\n') - elif request == 'unlocked': - # The lock screen let the user in: new USB devices work again. - usb_new_devices(True) - connection.sendall(b'ok\n') - elif request == 'status': - connection.sendall(self.machine.state.encode() + b'\n') - elif request.startswith('brightness '): - parts = request.split() - panel = self.backlight() - reply = b'held\n' - if (len(parts) == 4 and panel and parts[1] == panel.name and - parts[2].isascii() and parts[2].isdigit() and - parts[3].isascii() and parts[3].isdigit()): - level, expected = int(parts[2]), int(parts[3]) - current = int((panel / 'brightness').read_text()) - maximum = int((panel / 'max_brightness').read_text()) - if self.machine.state == ON and self.fade is None and self.dim_saved is None and current > 0 and current == expected and 1 <= level <= maximum: - (panel / 'brightness').write_text(f'{level}\n') - reply = b'ok\n' - connection.sendall(reply) - elif request == 'als-state': - connection.sendall(b'lit\n' if self.machine.state == ON and self.fade is None and self.dim_saved is None else b'dark\n') - elif request == 'dim': - panel = self.backlight() - if self.machine.state == ON and self.dim_saved is None and panel: - # Half the panel's range, never brighter than it is. - current = int((panel / 'brightness').read_text()) - level = max(1, int((panel / 'max_brightness').read_text()) // 2) - if current > level: - self.dim_saved, self.dim_level = current, level - (panel / 'brightness').write_text(f'{level}\n') - connection.sendall(b'ok\n') - elif request == 'undim': - self.undim() - connection.sendall(b'ok\n') - elif request == 'wake' and self.machine.state != ON and battery_empty(): - # A touch on the dark screen of an empty tablet: it stays - # asleep, as for Power and Home. Plugging in still wakes. - connection.sendall(b'ok\n') - elif request in ('idle', 'wake', 'lock'): - self.feed(request) - connection.sendall(b'ok\n') - else: - connection.sendall(b'unknown\n') - except (OSError, UnicodeDecodeError) as error: - log(f'control: {error}') - - def open_socket(self): - # Bound and listening under a temporary name, then renamed: a client - # that sees SOCKET can connect, never a socket that is not listening. - staging = f'{SOCKET}.new' - Path(staging).unlink(missing_ok=True) - server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - server.bind(staging) - os.chown(staging, 0, grp.getgrnam('video').gr_gid) # the tablet user's session - os.chmod(staging, 0o660) - server.listen(8) - os.replace(staging, SOCKET) - return server - - # --- event loop --------------------------------------------------------- - def timeout(self): - now = time.monotonic() - if now >= self.next_scan: - self.scan_keys() - self.next_scan = now + 5 - delay = TICK_SECONDS if self.machine.inflight else 1.0 - if self.fade is not None: - delay = min(delay, self.next_frame()) - for deadline in (self.settle_at, self.grace_at): - if deadline is not None: - delay = min(delay, max(0.0, deadline - now)) - return delay - - def watch_kernel(self): - """A kernel attempt ending is not the sleep ending: systemd-sleep may try again.""" - if not self.machine.inflight: - return - now = self.sleep_counters() - if now == self.seen_counters: - return - if now[1] != self.seen_counters[1]: - last = {} - for name in ('last_failed_dev', 'last_failed_errno', 'last_failed_step'): - try: - last[name] = (STATS / name).read_text().strip() - except OSError: - last[name] = '?' - log(f'kernel attempt failed: suspend_stats {now} device {last["last_failed_dev"] or "-"} ' - f'errno {last["last_failed_errno"]} step {last["last_failed_step"]}') - self.arm_wakeup() # the failed attempt used it up - self.seen_counters = now - self.kernel_attempted = True - self.sleep_began('kernel') - - def wait_for_unit(self, record): - """Posts the end of systemd-suspend for this sleep: once seen running, or the kernel attempted it. - - Started when logind announces the sleep, systemd-suspend may not have started yet: - its inactive state then is not its end. - """ - running = False - while not self.stopping and self.machine.inflight and self.sleep_record == record: - try: - state = command('systemctl', 'show', '-p', 'ActiveState', '--value', - 'systemd-suspend.service').stdout.strip() - if state in ('inactive', 'failed') and (running or self.kernel_attempted): - self.post(f'sleep-over {record}') - return - running = running or state in ('activating', 'active', 'deactivating') - except (OSError, subprocess.SubprocessError) as error: - log(f'watching systemd-suspend: {error}') - time.sleep(0.1) - - def sleep_finished(self, how): - """systemd-suspend finished, or logind says so: every attempt of this sleep is over. - - The verdict is the kernel's: suspend_stats now against before the sleep was asked for. - """ - if not self.machine.inflight: - return - now = self.sleep_counters() - result = 'slept' if now[0] != self.counters[0] else 'aborted' if now != self.counters else 'not-entered' - try: - irq = Path('/sys/power/pm_wakeup_irq').read_text().strip() - except OSError: - irq = 'none' - log(f'sleep-ended result={result} seconds={time.clock_gettime(SLEEP_CLOCK) - self.sleep_started:.3f} ' - f'wakeup_irq={irq} end={how} awake={self.awake:.1f}') - if how != 'logind' and self.logind_asleep: - # logind's own end not seen (yet): its inhibitor waits for it, a while. - self.logind_busy_until = time.monotonic() + LOGIND_END_WAIT_SECONDS - self.feed('sleep-aborted' if result == 'aborted' else 'sleep-ended') - - def count_awake(self, now): - """Adds the time the loop ran since its last turn; the safeties of a suspend in flight.""" - step, self.last_turn = now - self.last_turn, now - if not self.machine.inflight: - return - self.awake += min(max(step, 0.0), AWAKE_STEP_MAX) - if not self.sleep_begun and self.awake > SUSPEND_AWAKE_SECONDS: - log(f'suspend did not happen: not begun in {self.awake:.1f} s awake') - self.feed('timeout') - elif self.sleep_begun and self.awake > SLEEP_END_AWAKE_SECONDS: - log(f'no end of the sleep seen in {self.awake:.1f} s awake') - self.sleep_finished('none') - - def start_lit(self): - """State ON at the start, the panel lit: the level of the last dark.""" - if not os.path.exists(SOCKET): # /run: gone only at boot, kept by a restart - self.restore_brightness() - panel = self.backlight() - if panel and int((panel / 'brightness').read_text()) == 0: - # A restart (an update, a crash) found it dark: never dark without an owner. - self.saved = self.saved or self.remembered_level(panel) - self.key_time = time.monotonic() - self.do_light(ON) - - def run(self): - self.start_lit() - server = self.open_socket() - self.take_inhibitor() - self.start_monitor() - self.start_uevents() - for worker in (self.session_worker, self.playback_worker): - threading.Thread(target=worker, daemon=True).start() - log('ready: ON') - while not self.stopping: - delay = self.timeout() - watched = [*self.keys, *self.covers, server, self.wake_read, self.monitor.stdout] - if self.uevents: - watched.append(self.uevents) - readable, _, _ = select.select(watched, [], [], delay) - # Keys first: a press that woke the tablet decides before the sleep's end is seen. - for fd in [fd for fd in readable if fd in self.keys]: - try: - for key, down, when in key_edges(os.read(fd, INPUT_EVENT.size * 64)): - name = self.buttons.edge(key, down, when, self.machine.state == ON) - if name is None: - continue - if name == 'screenshot': - log(f't={when:.6f} screenshot') - self.session_jobs.put('screenshot') - continue - if name == 'home-up': - self.home_action(when) - continue - # Pressed before this wake's panel lit: that wake took care of it. - if self.machine.inflight and self.lit_at is not None and when <= self.lit_at: - log(f't={when:.6f} {name}: consumed by the wake') - else: - self.feed(name, when) - except OSError as error: - log(f'keys lost: {error}') - os.close(fd) - del self.keys[fd] - for fd in [fd for fd in readable if fd in self.covers]: - try: - self.read_cover(fd) - except BlockingIOError: - continue - except OSError as error: - log(f'cover lost: {error}') - os.close(fd) - del self.covers[fd] - self.cover_dropped.discard(fd) - self.cover.forget(fd) - if self.wake_read in readable: - os.read(self.wake_read, 512) - while not self.events.empty(): - event = self.events.get() - if event.startswith('sleep-over '): - if int(event.split()[1]) == self.sleep_record: - self.sleep_finished('unit') - else: - self.feed(event) - if self.monitor.stdout in readable: - self.read_monitor() - if server in readable: - self.control(server) - if self.uevents in readable: - self.read_uevents() - self.tick_fade() - self.watch_kernel() - self.keep_inhibitor() - if self.grace_at is not None and time.monotonic() >= self.grace_at: - self.grace_at = None - self.feed('grace-ended') - if self.settle_at is not None and time.monotonic() >= self.settle_at: - self.settle_at = None - self.feed('settle') - self.count_awake(time.monotonic()) - - -if __name__ == '__main__': - try: - daemon = Daemon() - signal.signal(signal.SIGTERM, daemon.stop_brightness) - daemon.run() - except KeyboardInterrupt: - sys.exit(0) diff --git a/tests/package_tree.py b/tests/package_tree.py index 46caa702..456e7e58 100644 --- a/tests/package_tree.py +++ b/tests/package_tree.py @@ -32,7 +32,7 @@ def inputs(base): """BUILD, OMARCHY and DBUS_NEXT for install-tree, under BASE.""" build, upstream, wheel = base / 'build', base / 'omarchy', base / 'wheel' build.mkdir() - for name in ('wvkbd-mobintl', 'wtype'): + for name in ('wvkbd-mobintl', 'wtype', 'omarchy-powerd'): (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_low_battery.py b/tests/test_low_battery.py index e8959032..17cc12cf 100644 --- a/tests/test_low_battery.py +++ b/tests/test_low_battery.py @@ -1,18 +1,44 @@ """An empty battery sleeps the tablet and keeps it asleep; it never powers it off.""" +import atexit import configparser -import importlib.machinery -import importlib.util +import functools +import os from pathlib import Path +import shlex +import shutil +import subprocess +import sys import tempfile import unittest PROJECT = Path(__file__).resolve().parents[1] CONF = PROJECT / 'system/overlay/etc/UPower/UPower.conf.d/60-omarchy-a.conf' -DAEMON = PROJECT / 'system/overlay/usr/libexec/omarchy-powerd' -loader = importlib.machinery.SourceFileLoader('omarchy_powerd_low_battery', str(DAEMON)) -spec = importlib.util.spec_from_loader(loader.name, loader) -powerd = importlib.util.module_from_spec(spec) -loader.exec_module(powerd) +SOURCE = PROJECT / 'desktop/configuration/powerd.c' + + +@functools.lru_cache(maxsize=1) +def compiled_binary(): + tmp = Path(tempfile.mkdtemp(prefix='omarchy-powerd-test-')) + atexit.register(shutil.rmtree, tmp, True) + binary = tmp / 'omarchy-powerd' + cc = os.environ.get('CC', 'cc') + pkg = subprocess.run(['pkg-config', '--cflags', '--libs', 'libsystemd'], + capture_output=True, text=True) + extra = ['-DHAVE_SD_BUS', *shlex.split(pkg.stdout)] if pkg.returncode == 0 else [] + subprocess.run( + [cc, '-O2', '-Wall', '-Wextra', '-Werror', '-std=c99', str(SOURCE), + *extra, '-lpthread', '-lm', '-o', str(binary)], + check=True, + ) + return binary + + +def setUpModule(): + # powerd.c builds against Linux headers (linux/input.h, netlink); a Mac + # has none of them, so the binary is tested on Linux only. + if not sys.platform.startswith('linux'): + raise unittest.SkipTest('powerd.c needs Linux headers') + compiled_binary() def supply(root, name, **fields): @@ -32,6 +58,14 @@ def test_an_empty_battery_suspends_never_powers_off(self): class BatteryEmpty(unittest.TestCase): + def battery_empty(self, root): + res = subprocess.run( + [str(compiled_binary()), '--test'], + input=f'battery_empty {root}\n', + capture_output=True, text=True, check=True, timeout=5, + ) + return res.stdout.strip() == 'VAL 1' + def test_empty_only_at_the_action_level_and_discharging(self): for status, capacity, empty in (('Discharging', 0, True), ('Discharging', 2, True), ('Discharging', 3, False), ('Charging', 0, False), @@ -39,21 +73,68 @@ def test_empty_only_at_the_action_level_and_discharging(self): with self.subTest(status=status, capacity=capacity), tempfile.TemporaryDirectory() as root: supply(root, 'lightning', type='USB', online=1) supply(root, 'battery', type='Battery', status=status, capacity=capacity) - self.assertEqual(powerd.battery_empty(Path(root)), empty) + self.assertEqual(self.battery_empty(root), empty) def test_no_battery_is_never_empty(self): with tempfile.TemporaryDirectory() as root: supply(root, 'lightning', type='USB', online=1) - self.assertFalse(powerd.battery_empty(Path(root))) + self.assertFalse(self.battery_empty(root)) + + +class CMachine: + def __init__(self): + self._proc = subprocess.Popen( + [str(compiled_binary()), '--test'], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + ) + self.state = 'ON' + self.lock_ok = self.settle_due = self.inflight = self.playing = False + self.no_suspend = self.hold_release = self.empty = False + self.aborts = 0 + + def _sync_set(self): + self._proc.stdin.write( + f'm_set {self.state} {int(self.lock_ok)} {int(self.settle_due)} ' + f'{int(self.inflight)} {int(self.playing)} {int(self.no_suspend)} ' + f'{int(self.hold_release)} {self.aborts} {int(self.empty)}\n' + ) + self._proc.stdin.flush() + assert self._proc.stdout.readline().strip() == 'OK' + + def handle(self, event): + self._sync_set() + self._proc.stdin.write(f'm_handle {event}\n') + self._proc.stdin.flush() + reply = self._proc.stdout.readline().strip() + left, right = reply.split('|', 1) + parts = left.split() + self.state = parts[1] + self.lock_ok = parts[2] == '1' + self.settle_due = parts[3] == '1' + self.inflight = parts[4] == '1' + self.playing = parts[5] == '1' + self.no_suspend = parts[6] == '1' + self.hold_release = parts[7] == '1' + self.aborts = int(parts[8]) + self.empty = parts[9] == '1' + return right.split() + + def close(self): + if self._proc.stdin and not self._proc.stdin.closed: + self._proc.stdin.close() + if self._proc.stdout and not self._proc.stdout.closed: + self._proc.stdout.close() + self._proc.wait(timeout=5) class Machine(unittest.TestCase): def asleep(self): - machine = powerd.Machine() + machine = CMachine() + self.addCleanup(machine.close) machine.handle('power') # dark and locking machine.handle('lock-ok') machine.handle('settle') # asleep - self.assertEqual(machine.state, powerd.SUSPENDING) + self.assertEqual(machine.state, 'SUSPENDING') return machine def test_an_empty_battery_keeps_power_and_home_from_lighting(self): @@ -62,10 +143,10 @@ def test_an_empty_battery_keeps_power_and_home_from_lighting(self): machine = self.asleep() machine.empty = True self.assertEqual(machine.handle(key), []) - self.assertEqual(machine.state, powerd.SUSPENDING) + self.assertEqual(machine.state, 'SUSPENDING') # The sleep the press ended settles again, dark. self.assertNotIn('light', machine.handle('sleep-ended')) - self.assertEqual(machine.state, powerd.SETTLING) + self.assertEqual(machine.state, 'SETTLING') self.assertEqual(machine.handle(key), []) def test_a_charger_still_wakes_it(self): diff --git a/tests/test_package.py b/tests/test_package.py index e2e6ee04..1bd886be 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -376,6 +376,7 @@ def test_changed_files_links_modes_and_a_missing_install_step_fail(self): def test_the_compiled_helpers_are_of_the_roots_architecture(self): self.assertEqual(set(audit.HELPERS), {'usr/libexec/omarchy-wtype', + 'usr/libexec/omarchy-powerd', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state'}) from release.architecture import check_elf check_elf(elf('aarch64'), 'aarch64') diff --git a/tests/test_powerd.py b/tests/test_powerd.py index cafc9d6c..33e6acc4 100644 --- a/tests/test_powerd.py +++ b/tests/test_powerd.py @@ -1,29 +1,146 @@ -"""omarchy-powerd: the state machine (docs/power-and-lock.md) and its parsing.""" -import struct -import importlib.machinery -import importlib.util +"""omarchy-powerd: the state machine (docs/power-and-lock.md), parsing, and real C99 daemon loop.""" +import atexit +import functools import json -from pathlib import Path import os -import pwd +from pathlib import Path +import shlex +import shutil import socket +import struct import subprocess +import sys import tempfile -import threading import time import unittest -from unittest import mock -from unittest.mock import patch import xml.etree.ElementTree as ET PROJECT = Path(__file__).resolve().parents[1] -PATH = PROJECT / 'system/overlay/usr/libexec/omarchy-powerd' -loader = importlib.machinery.SourceFileLoader('omarchy_powerd', str(PATH)) -spec = importlib.util.spec_from_loader(loader.name, loader) -powerd = importlib.util.module_from_spec(spec) -loader.exec_module(powerd) -Machine, EVENTS = powerd.Machine, powerd.EVENTS -ON, SETTLING, DARK, SUSPENDING = powerd.ON, powerd.SETTLING, powerd.DARK, powerd.SUSPENDING +SOURCE = PROJECT / 'desktop/configuration/powerd.c' + +ON, GRACE, SETTLING, DARK, SUSPENDING = 'ON', 'GRACE', 'SETTLING', 'DARK', 'SUSPENDING' +STATES = (ON, GRACE, SETTLING, DARK, SUSPENDING) +EVENTS = ('power', 'home', 'wake', 'idle', 'settle', 'lock-ok', 'lock-failed', 'playing', 'not-playing', + 'suspend-refused', 'suspend-unavailable', 'suspend-blocked', 'suspend-busy', 'sleep-signal', 'sleep-ended', + 'sleep-aborted', 'timeout', 'grace-ended', 'lock') +ABORTS_BEFORE_DARK = 3 +IDLE_GRACE_SECONDS = 8.0 +SETTLE_SECONDS = 10.0 +INPUT_EVENT = struct.Struct('llHHi') + + +@functools.lru_cache(maxsize=1) +def libsystemd_flags(): + """The compiler flags for libsystemd (sd-bus), or None where it is missing. + + The package always builds powerd with sd-bus (the recipe's makedepends); + a test machine without libsystemd's headers builds it without, and the + D-Bus tests skip. CI sets OMARCHY_TEST_REQUIRE_SD_BUS so that never + happens there unnoticed.""" + try: + pkg = subprocess.run(['pkg-config', '--cflags', '--libs', 'libsystemd'], + capture_output=True, text=True) + except FileNotFoundError: + pkg = None + if pkg is None or pkg.returncode != 0: + if os.environ.get('OMARCHY_TEST_REQUIRE_SD_BUS'): + raise AssertionError('libsystemd headers are missing (pkg-config libsystemd)') + return None + return shlex.split(pkg.stdout) + + +@functools.lru_cache(maxsize=1) +def compiled_binary(): + tmp = Path(tempfile.mkdtemp(prefix='omarchy-powerd-test-')) + atexit.register(shutil.rmtree, tmp, True) + binary = tmp / 'omarchy-powerd' + cc = os.environ.get('CC', 'cc') + flags = libsystemd_flags() + extra = ['-DHAVE_SD_BUS', *flags] if flags is not None else [] + subprocess.run( + [cc, '-O2', '-Wall', '-Wextra', '-Werror', '-std=c99', str(SOURCE), + *extra, '-lpthread', '-lm', '-o', str(binary)], + check=True, + ) + return binary + + +def setUpModule(): + # powerd.c builds against Linux headers (linux/input.h, netlink); a Mac + # has none of them, so the binary is tested on Linux only. + if not sys.platform.startswith('linux'): + raise unittest.SkipTest('powerd.c needs Linux headers') + compiled_binary() + + +class Harness: + """Persistent `--test` subprocess for fast unit tests against the C99 binary.""" + + def __init__(self): + self._proc = subprocess.Popen( + [str(compiled_binary()), '--test'], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + ) + + def ask(self, cmd): + self._proc.stdin.write(cmd + '\n') + self._proc.stdin.flush() + reply = self._proc.stdout.readline() + if not reply: + raise AssertionError('omarchy-powerd --test exited unexpectedly') + return reply.rstrip('\n') + + def close(self): + if self._proc.stdin and not self._proc.stdin.closed: + self._proc.stdin.close() + if self._proc.stdout and not self._proc.stdout.closed: + self._proc.stdout.close() + self._proc.wait(timeout=5) + + +_SHARED_HARNESS = None + + +def shared_harness(): + global _SHARED_HARNESS + if _SHARED_HARNESS is None: + _SHARED_HARNESS = Harness() + atexit.register(_SHARED_HARNESS.close) + return _SHARED_HARNESS + + +class Machine: + def __init__(self): + self.state = ON + self.lock_ok = False + self.settle_due = False + self.inflight = False + self.playing = False + self.no_suspend = False + self.hold_release = False + self.aborts = 0 + self.empty = False + + def handle(self, event): + h = shared_harness() + assert h.ask( + f'm_set {self.state} {int(self.lock_ok)} {int(self.settle_due)} ' + f'{int(self.inflight)} {int(self.playing)} {int(self.no_suspend)} ' + f'{int(self.hold_release)} {self.aborts} {int(self.empty)}' + ) == 'OK' + reply = h.ask(f'm_handle {event}') + left, right = reply.split('|', 1) + parts = left.split() + self.state = parts[1] + self.lock_ok = parts[2] == '1' + self.settle_due = parts[3] == '1' + self.inflight = parts[4] == '1' + self.playing = parts[5] == '1' + self.no_suspend = parts[6] == '1' + self.hold_release = parts[7] == '1' + self.aborts = int(parts[8]) + self.empty = parts[9] == '1' + return right.split() def run(machine, *events): @@ -40,22 +157,31 @@ def asleep(): class SupplyEvents(unittest.TestCase): + def parse_supply_uevent(self, message): + encoded = message.decode('latin1').replace('\0', '|') + reply = shared_harness().ask('uevent ' + encoded) + if reply == 'NONE': + return None + _, name, on = reply.split() + return name, on == '1' + def test_a_supplys_online_state_is_read_from_its_uevent(self): message = b'change@/devices/x/power_supply/lightning\0ACTION=change\0SUBSYSTEM=power_supply\0' \ b'POWER_SUPPLY_NAME=lightning\0POWER_SUPPLY_ONLINE=1\0' - self.assertEqual(powerd.parse_supply_uevent(message), ('lightning', True)) - self.assertEqual(powerd.parse_supply_uevent(message.replace(b'ONLINE=1', b'ONLINE=0')), ('lightning', False)) + self.assertEqual(self.parse_supply_uevent(message), ('lightning', True)) + self.assertEqual(self.parse_supply_uevent(message.replace(b'ONLINE=1', b'ONLINE=0')), ('lightning', False)) def test_other_uevents_are_ignored(self): - self.assertIsNone(powerd.parse_supply_uevent(b'change@/x\0SUBSYSTEM=input\0POWER_SUPPLY_ONLINE=1\0')) - self.assertIsNone(powerd.parse_supply_uevent(b'change@/x\0SUBSYSTEM=power_supply\0POWER_SUPPLY_NAME=battery\0')) + self.assertIsNone(self.parse_supply_uevent(b'change@/x\0SUBSYSTEM=input\0POWER_SUPPLY_ONLINE=1\0')) + self.assertIsNone(self.parse_supply_uevent(b'change@/x\0SUBSYSTEM=power_supply\0POWER_SUPPLY_NAME=battery\0')) def test_only_being_plugged_in_counts(self): - known = {} - self.assertTrue(powerd.plugged_in(known, 'lightning', True)) - self.assertFalse(powerd.plugged_in(known, 'lightning', True)) - self.assertFalse(powerd.plugged_in(known, 'lightning', False)) - self.assertTrue(powerd.plugged_in(known, 'lightning', True)) + h = shared_harness() + h.ask('s_reset') + self.assertEqual(h.ask('s_plug lightning 1'), 'VAL 1') + self.assertEqual(h.ask('s_plug lightning 1'), 'VAL 0') + self.assertEqual(h.ask('s_plug lightning 0'), 'VAL 0') + self.assertEqual(h.ask('s_plug lightning 1'), 'VAL 1') class Scenarios(unittest.TestCase): @@ -84,7 +210,6 @@ def test_a_press_after_the_panel_lit_is_a_command_even_while_the_sleep_finishes( machine.handle('power') self.assertEqual(machine.handle('power'), ['dark', 'lock', 'arm-settle']) run(machine, 'lock-ok') - # No second suspend on top of the one still finishing; it follows. self.assertEqual(machine.handle('settle'), []) self.assertEqual(machine.state, SETTLING) self.assertEqual(machine.handle('sleep-ended'), ['take-inhibitor', 'suspend']) @@ -150,31 +275,26 @@ def test_a_board_that_cannot_sleep_stays_dark_until_pressed_without_asking_again self.assertEqual(run(machine, 'settle', 'playing', 'not-playing'), []) self.assertEqual(machine.state, DARK) self.assertIn('light', machine.handle('power')) - # The next lock asks again: it costs one question, not a freeze. self.assertEqual(run(machine, 'power', 'lock-ok', 'settle'), ['suspend']) def test_a_board_whose_suspend_keeps_aborting_backs_off_dark_and_locked(self): machine = asleep() - for _ in range(powerd.ABORTS_BEFORE_DARK - 1): + for _ in range(ABORTS_BEFORE_DARK - 1): self.assertEqual(machine.handle('sleep-aborted'), ['take-inhibitor', 'arm-settle']) self.assertEqual(machine.handle('settle'), ['suspend']) - # The third: dark and locked, asked for again only after the backoff. self.assertEqual(machine.handle('sleep-aborted'), ['take-inhibitor', 'arm-backoff']) self.assertEqual((machine.state, machine.inflight), (SETTLING, False)) - # The backoff's end asks once more; another abort backs off again at once. self.assertEqual(machine.handle('settle'), ['suspend']) self.assertEqual(machine.handle('sleep-aborted'), ['take-inhibitor', 'arm-backoff']) - # Playback ending meanwhile does not shorten it. run(machine, 'playing') self.assertEqual(machine.handle('not-playing'), ['arm-backoff']) - # A press lights as usual and starts the count again. self.assertIn('light', machine.handle('home')) self.assertEqual(machine.aborts, 0) self.assertEqual(run(machine, 'power', 'lock-ok', 'settle'), ['suspend']) def test_a_sleep_that_happened_ends_the_backoff(self): machine = asleep() - for _ in range(powerd.ABORTS_BEFORE_DARK): + for _ in range(ABORTS_BEFORE_DARK): run(machine, 'sleep-aborted', 'settle') self.assertEqual(machine.handle('sleep-ended'), ['take-inhibitor', 'arm-settle']) self.assertEqual(machine.aborts, 0) @@ -193,9 +313,8 @@ def test_a_suspend_that_did_not_happen_is_tried_again(self): def test_the_lock_screens_blank_timeout_leads_to_sleep(self): machine = Machine() - run(machine, 'power', 'lock-ok', 'power', 'sleep-ended') # back on the lit lock screen + run(machine, 'power', 'lock-ok', 'power', 'sleep-ended') self.assertEqual(machine.handle('idle'), ['dark', 'arm-grace']) - # An already locked screen stays locked during the grace interval. run(machine, 'grace-ended', 'lock-ok') self.assertEqual(machine.handle('settle'), ['suspend']) @@ -214,12 +333,12 @@ class IdleGrace(unittest.TestCase): def test_idle_waits_eight_seconds_before_requesting_lock(self): machine = Machine() self.assertEqual(machine.handle('idle'), ['dark', 'arm-grace']) - self.assertEqual(machine.state, powerd.GRACE) + self.assertEqual(machine.state, GRACE) self.assertEqual(machine.handle('settle'), []) self.assertEqual(machine.handle('playing'), []) self.assertEqual(machine.handle('grace-ended'), ['dark', 'lock', 'arm-settle']) self.assertEqual(machine.state, SETTLING) - self.assertEqual(powerd.IDLE_GRACE_SECONDS, 8.0) + self.assertIn('DEFAULT_IDLE_GRACE_SECONDS 8.0', SOURCE.read_text()) def test_quick_wake_never_requests_lock_or_suspend(self): for event in ('power', 'home', 'wake'): @@ -248,7 +367,6 @@ def test_menu_lock_locks_at_once_also_during_grace(self): machine.handle('idle') self.assertEqual(machine.handle('lock'), ['cancel-grace', 'dark', 'lock', 'arm-settle']) self.assertEqual(machine.state, SETTLING) - # anywhere else it changes nothing: already dark and locked, or asleep self.assertEqual(machine.handle('lock'), []) @@ -288,21 +406,18 @@ def test_invariants(self): context = (event, vars(before), vars(after)) states.add(after.state) if kind == 'state': - self.assertIn(after.state, powerd.STATES, context) - # The panel and the state cannot disagree: dark exactly when not ON. + self.assertIn(after.state, STATES, context) self.assertEqual(dark, after.state != ON, context) if after.state == SUSPENDING: self.assertTrue(after.inflight, context) - # Dark and running with no timer only for playback or a board that cannot suspend. if after.state == DARK: self.assertTrue(after.playing or after.no_suspend, context) elif kind == 'suspend': - # Sleep is only ever asked for dark and locked. self.assertTrue(dark, context) self.assertTrue(after.lock_ok, context) self.assertEqual(after.state, SUSPENDING, context) self.assertIn(before.state, (SETTLING,), context) - self.assertEqual(states, set(powerd.STATES)) + self.assertEqual(states, set(STATES)) def test_power_and_home_always_light_a_dark_screen(self): for kind, event, before, after, dark in self.walk(): @@ -315,100 +430,68 @@ def test_home_never_darkens(self): self.assertEqual(after.state, ON, vars(before)) -class Inhibitor(unittest.TestCase): - def test_an_inhibitor_logind_refused_is_taken_again_and_a_released_one_is_not(self): - daemon = powerd.Daemon() - dead = type('Dead', (), {'poll': lambda self: 1})() - alive = type('Alive', (), {'poll': lambda self: None, 'terminate': lambda self: None, - 'wait': lambda self: 0})() - with patch.object(powerd.subprocess, 'Popen', side_effect=[dead, alive]) as started: - daemon.take_inhibitor() - daemon.keep_inhibitor() - self.assertEqual(started.call_count, 2) - daemon.keep_inhibitor() - self.assertEqual(started.call_count, 2) - daemon.release_inhibitor() - daemon.keep_inhibitor() - self.assertEqual(started.call_count, 2) - - def test_a_logind_that_started_again_gets_asked_only_if_we_hold_one(self): - daemon = powerd.Daemon() - alive = type('Alive', (), {'poll': lambda self: None, 'terminate': lambda self: None, - 'wait': lambda self: 0}) - with patch.object(powerd.subprocess, 'Popen', side_effect=lambda *_: alive()) as started: - daemon.renew_inhibitor() - self.assertEqual(started.call_count, 0) - daemon.take_inhibitor() - first = daemon.inhibitor - daemon.renew_inhibitor() - self.assertEqual(started.call_count, 2) - self.assertIsNot(daemon.inhibitor, first) - self.assertTrue(daemon.want_inhibitor) - - -class Parsing(unittest.TestCase): - def test_key_edges_only_power_and_home_presses_and_releases(self): - event = powerd.INPUT_EVENT.pack - data = (event(10, 500000, 1, 116, 1) + event(10, 600000, 1, 116, 0) + event(11, 0, 1, 172, 1) + - event(11, 0, 1, 115, 1) + event(12, 0, 0, 0, 0) + event(13, 0, 1, 116, 2)) - self.assertEqual(powerd.key_edges(data), [('power', True, 10.5), ('power', False, 10.6), ('home', True, 11.0)]) - self.assertEqual(powerd.INPUT_EVENT.size, 2 * struct.calcsize('l') + 8) - - class SmartCover(unittest.TestCase): - def test_cover_edges_only_the_cover_switch(self): - event = powerd.INPUT_EVENT.pack - data = (event(5, 0, 5, 0x10, 1) + event(5, 0, 0, 0, 0) + event(6, 500000, 5, 0x10, 0) + - event(7, 0, 5, 0x00, 1) + event(8, 0, 1, 116, 1)) - self.assertEqual(powerd.cover_edges(data), [(True, 5.0), (False, 6.5)]) - def test_a_device_reports_the_cover_from_its_switch_bitmap(self): - self.assertTrue(powerd.reports_cover('10000\n')) - self.assertTrue(powerd.reports_cover('0 10001\n')) - self.assertFalse(powerd.reports_cover('1\n')) - self.assertFalse(powerd.reports_cover('0\n')) - self.assertFalse(powerd.reports_cover('')) + h = shared_harness() + self.assertEqual(h.ask('reports_cover 10000'), 'VAL 1') + self.assertEqual(h.ask('reports_cover 0 10001'), 'VAL 1') + self.assertEqual(h.ask('reports_cover 1'), 'VAL 0') + self.assertEqual(h.ask('reports_cover 0'), 'VAL 0') + self.assertEqual(h.ask('reports_cover'), 'VAL 0') def test_power_and_home_come_from_any_device_that_has_them(self): - # The iPad's buttons (gpio-keys: Power), the simulator's QEMU keyboard - # (every key), and devices without either: a touchscreen, a mouse. - self.assertTrue(powerd.reports_keys('10000000000000 0\n')) - self.assertTrue(powerd.reports_keys('ffffffffff ffffffffffffffff ffffffffffffffff fffffffffffffffe\n')) - self.assertTrue(powerd.reports_keys('100000000000 0 0\n')) # KEY_HOMEPAGE alone (bit 172) - self.assertFalse(powerd.reports_keys('30400 1f0000 0 0 0 0\n')) - self.assertFalse(powerd.reports_keys('1f0000 0 0 0 0\n')) - self.assertFalse(powerd.reports_keys('')) + h = shared_harness() + self.assertEqual(h.ask('reports_keys 10000000000000 0'), 'VAL 1') + self.assertEqual(h.ask('reports_keys ffffffffff ffffffffffffffff ffffffffffffffff fffffffffffffffe'), 'VAL 1') + self.assertEqual(h.ask('reports_keys 100000000000 0 0'), 'VAL 1') + self.assertEqual(h.ask('reports_keys 30400 1f0000 0 0 0 0'), 'VAL 0') + self.assertEqual(h.ask('reports_keys 1f0000 0 0 0 0'), 'VAL 0') + self.assertEqual(h.ask('reports_keys'), 'VAL 0') def test_closing_locks_once_and_opening_wakes_once_across_both_sensors(self): - cover = powerd.Cover() - self.assertEqual(cover.change('a', True), 'lock') - self.assertIsNone(cover.change('b', True)) - self.assertIsNone(cover.change('a', False)) - self.assertEqual(cover.change('b', False), 'wake') - self.assertIsNone(cover.change('b', False)) + h = shared_harness() + h.ask('c_reset') + self.assertEqual(h.ask('c_change 1 1'), 'VAL lock') + self.assertEqual(h.ask('c_change 2 1'), 'VAL none') + self.assertEqual(h.ask('c_change 1 0'), 'VAL none') + self.assertEqual(h.ask('c_change 2 0'), 'VAL wake') + self.assertEqual(h.ask('c_change 2 0'), 'VAL none') def test_a_lost_sensor_does_not_keep_the_cover_closed(self): - cover = powerd.Cover() - cover.change('a', True) - cover.forget('a') - self.assertEqual(cover.change('b', True), 'lock') + h = shared_harness() + h.ask('c_reset') + h.ask('c_change 1 1') + h.ask('c_forget 1') + self.assertEqual(h.ask('c_change 2 1'), 'VAL lock') def test_closing_darkens_and_locks_and_opening_lights(self): - machine = powerd.Machine() + machine = Machine() self.assertEqual(machine.handle('lock'), ['dark', 'lock', 'arm-settle']) self.assertEqual(machine.handle('wake'), ['cancel-settle', 'light', 'woke']) - self.assertEqual(machine.state, powerd.ON) + self.assertEqual(machine.state, ON) class Buttons(unittest.TestCase): + def edge(self, name, down, when, lit=True): + reply = shared_harness().ask(f'b_edge {name} {int(down)} {when} {int(lit)}') + _, res, in_combo, woke = reply.split() + self.home_in_combo = in_combo == '1' + self.home_woke = woke == '1' + return None if res == 'none' else res + def events(self, edges, lit=True): - buttons = powerd.Buttons() - return [e for e in (buttons.edge(name, down, when, lit) for name, down, when in edges) if e] + shared_harness().ask('b_reset') + out = [] + for name, down, when in edges: + ev = self.edge(name, down, when, lit) + if ev: + out.append(ev) + return out def test_a_short_press_on_a_lit_screen_darkens_on_release(self): - buttons = powerd.Buttons() - self.assertIsNone(buttons.edge('power', True, 1.0, True)) - self.assertEqual(buttons.edge('power', False, 1.2, True), 'power') + shared_harness().ask('b_reset') + self.assertIsNone(self.edge('power', True, 1.0, True)) + self.assertEqual(self.edge('power', False, 1.2, True), 'power') def test_power_with_home_held_does_nothing_for_dfu_and_restart(self): for edges in ([('power', True, 1.0), ('home', True, 1.1), ('home', False, 11), ('power', False, 11)], @@ -424,12 +507,12 @@ def test_a_short_home_and_power_press_takes_one_screenshot_on_release(self): self.assertEqual(self.events(edges), ['home', 'screenshot']) def test_a_screenshot_press_does_not_count_as_a_home_press(self): - buttons = powerd.Buttons() + shared_harness().ask('b_reset') for name, down, when in (('power', True, 1.0), ('home', True, 1.1), ('home', False, 1.3), ('power', False, 1.4)): - buttons.edge(name, down, when, True) - self.assertTrue(buttons.home_in_combo) - buttons.edge('home', True, 5.0, True) - self.assertFalse(buttons.home_in_combo) + self.edge(name, down, when, True) + self.assertTrue(self.home_in_combo) + self.edge('home', True, 5.0, True) + self.assertFalse(self.home_in_combo) def test_a_short_volume_down_and_power_press_takes_one_screenshot(self): for edges in ([('power', True, 1.0), ('volume-down', True, 1.1), ('power', False, 1.3), ('volume-down', False, 1.4)], @@ -447,44 +530,28 @@ def test_volume_down_alone_is_no_event(self): self.assertEqual(self.events(edges), ['power']) def test_volume_down_and_power_is_no_home_combination(self): - buttons = powerd.Buttons() + shared_harness().ask('b_reset') for name, down, when in (('power', True, 1.0), ('volume-down', True, 1.1), ('volume-down', False, 1.3), ('power', False, 1.4)): - buttons.edge(name, down, when, True) - self.assertFalse(buttons.home_in_combo) + self.edge(name, down, when, True) + self.assertFalse(self.home_in_combo) self.assertEqual(self.events([('home', True, 3.0), ('home', False, 3.1)]), ['home', 'home-up']) def test_the_volume_keys_device_is_read(self): width = struct.calcsize('L') * 8 words = [0] * 4 - words[-1 - powerd.KEY_VOLUMEDOWN // width] |= 1 << powerd.KEY_VOLUMEDOWN % width - self.assertTrue(powerd.reports_keys(' '.join('%x' % w for w in words))) - self.assertEqual(powerd.key_edges(powerd.INPUT_EVENT.pack(5, 0, powerd.EV_KEY, powerd.KEY_VOLUMEDOWN, 1)), - [('volume-down', True, 5.0)]) - - def test_user_commands_look_groups_up_in_the_child(self): - # os.getgrouplist would hold the interpreter lock through nss-systemd, - # which stalls until systemd has finished a sleep. - user = pwd.struct_passwd(('tablet', 'x', 1000, 1000, '', '/home/tablet', '/bin/bash')) - with mock.patch.object(powerd, 'command') as command, \ - mock.patch.object(powerd.os, 'getgrouplist', side_effect=AssertionError('NSS in powerd')): - powerd.as_user(user, 'omarchy-shell', 'lock', 'woke') - argv, options = command.call_args - self.assertEqual(argv[:5], ('setpriv', '--reuid=1000', '--regid=1000', '--init-groups', '--')) - self.assertEqual(argv[5:], ('omarchy-shell', 'lock', 'woke')) - self.assertNotIn('extra_groups', options) - self.assertEqual(options['env']['HOME'], '/home/tablet') + words[-1 - 114 // width] |= 1 << (114 % width) + self.assertEqual(shared_harness().ask('reports_keys ' + ' '.join('%x' % w for w in words)), 'VAL 1') def test_a_home_press_that_wakes_the_screen_opens_nothing(self): - buttons = powerd.Buttons() - self.assertEqual(buttons.edge('home', True, 1.0, False), 'home') - self.assertIsNone(buttons.edge('home', False, 1.1, True)) - self.assertTrue(buttons.home_woke) - buttons.edge('home', True, 5.0, True) - self.assertFalse(buttons.home_woke) + shared_harness().ask('b_reset') + self.assertEqual(self.edge('home', True, 1.0, False), 'home') + self.assertIsNone(self.edge('home', False, 1.1, True)) + self.assertTrue(self.home_woke) + self.edge('home', True, 5.0, True) + self.assertFalse(self.home_woke) def test_home_let_go_after_a_press_alone_is_the_home_action(self): self.assertEqual(self.events([('home', True, 1.0), ('home', False, 1.1)]), ['home', 'home-up']) - # A release whose press was not seen (powerd started meanwhile) is not one. self.assertEqual(self.events([('home', False, 1.1)]), []) def test_power_alone_still_darkens_after_a_screenshot(self): @@ -498,31 +565,15 @@ def test_a_long_hold_does_nothing(self): def test_a_dark_screen_wakes_on_the_press(self): self.assertEqual(self.events([('power', True, 1.0), ('power', False, 1.1)], lit=False), ['power']) - def test_sleep_signal(self): - signal = {'type': 'signal', 'member': 'PrepareForSleep', 'payload': {'type': 'b', 'data': [True]}} - self.assertIs(powerd.parse_sleep_signal(json.dumps(signal)), True) - signal['payload']['data'] = [False] - self.assertIs(powerd.parse_sleep_signal(json.dumps(signal)), False) - self.assertIsNone(powerd.parse_sleep_signal('{"member":"Other"}')) - self.assertIsNone(powerd.parse_sleep_signal('Monitoring bus message stream.')) - - def test_logind_taking_its_name_is_seen(self): - def owner(name, new): - return json.dumps({'member': 'NameOwnerChanged', 'payload': {'data': [name, '', new]}}) - self.assertTrue(powerd.parse_logind_started(owner('org.freedesktop.login1', ':1.9'))) - self.assertFalse(powerd.parse_logind_started(owner('org.freedesktop.login1', ''))) - self.assertFalse(powerd.parse_logind_started(owner('org.other', ':1.9'))) - self.assertFalse(powerd.parse_logind_started('{"member":"NameOwnerChanged","payload":{"data":[]}}')) - self.assertFalse(powerd.parse_logind_started('Monitoring bus message stream.')) - def test_only_a_running_playback_stream_counts(self): + h = shared_harness() def node(media, state): return {'info': {'state': state, 'props': {'media.class': media}}} - self.assertTrue(powerd.streams_running(json.dumps([node('Stream/Output/Audio', 'running')]))) + self.assertEqual(h.ask('streams ' + json.dumps([node('Stream/Output/Audio', 'running')])), 'VAL 1') for nodes in ([node('Stream/Output/Audio', 'idle')], [node('Stream/Input/Audio', 'running')], [node('Audio/Sink', 'running')], [{'type': 'PipeWire:Interface:Core'}], []): - self.assertFalse(powerd.streams_running(json.dumps(nodes))) - self.assertFalse(powerd.streams_running('not json')) + self.assertEqual(h.ask('streams ' + json.dumps(nodes)), 'VAL 0') + self.assertEqual(h.ask('streams not json'), 'VAL 0') class Integration(unittest.TestCase): @@ -550,7 +601,7 @@ def test_every_way_to_dark_uses_the_same_client_and_the_decided_times(self): self.assertIn(f'{client} idle', lock) self.assertIn(f'{client} idle', idle) self.assertIn('"1" ? 30000 : 5000', lock) - self.assertEqual(powerd.SETTLE_SECONDS, 10.0) + self.assertIn('DEFAULT_SETTLE_SECONDS 10.0', SOURCE.read_text()) def test_a_new_installs_first_lock_stays_lit_ten_minutes_until_its_first_unlock(self): lock = (PROJECT / 'desktop/shell/shell/plugins/lock/Service.qml').read_text() @@ -587,261 +638,96 @@ class Brightness(unittest.TestCase): def setUp(self): work = tempfile.TemporaryDirectory() self.addCleanup(work.cleanup) - work = Path(work.name) - self.panel = work / 'backlight/panel' + self.work = Path(work.name) + self.panel = self.work / 'backlight/panel' self.panel.mkdir(parents=True) (self.panel / 'brightness').write_text('20\n') (self.panel / 'max_brightness').write_text('2000\n') - self.remembered = work / 'state/brightness' - for target, value in (('BACKLIGHTS', work / 'backlight'), ('BRIGHTNESS', self.remembered), - ('FADE_SECONDS', 0), ('log', lambda *_: None)): - patcher = patch.object(powerd, target, value) - patcher.start() - self.addCleanup(patcher.stop) - self.daemon = powerd.Daemon() + self.remembered = self.work / 'state/brightness' + self.sock = self.work / 'ctl' + self.init_bl(0.0) + + def init_bl(self, fade): + shared_harness().ask(f'bl_init {self.work / "backlight"} {self.remembered} {self.sock} {fade}') def level(self): return int((self.panel / 'brightness').read_text()) def test_the_first_boot_without_a_remembered_level_is_full_bright(self): - self.daemon.restore_brightness() + shared_harness().ask('bl_restore') self.assertEqual(self.level(), 2000) def test_a_boot_restores_the_level_of_the_last_dark_not_the_dark_itself(self): (self.panel / 'brightness').write_text('1200\n') - self.daemon.do_dark(None) + shared_harness().ask('bl_dark 10.0') self.assertEqual(self.level(), 0) self.assertEqual(self.remembered.read_text(), '1200\n') - powerd.Daemon().restore_brightness() + self.init_bl(0.0) + shared_harness().ask('bl_restore') self.assertEqual(self.level(), 1200) def test_a_remembered_level_too_dim_to_see_is_raised(self): self.remembered.parent.mkdir() self.remembered.write_text('3\n') - self.daemon.restore_brightness() + shared_harness().ask('bl_restore') self.assertEqual(self.level(), 100) def test_fade_is_eased_interruptible_and_keeps_requested_brightness(self): (self.panel / 'brightness').write_text('1200\n') - with patch.object(powerd, 'FADE_SECONDS', .24), patch.object(powerd.time, 'monotonic', return_value=10): - self.daemon.do_dark(None) + self.init_bl(0.24) + shared_harness().ask('bl_dark 10.0') self.assertEqual(self.level(), 1200) - with patch.object(powerd, 'FADE_SECONDS', .24), patch.object(powerd.time, 'monotonic', return_value=10.12): - self.daemon.tick_fade() - self.assertAlmostEqual(self.level(), 600, delta=1) - self.daemon.key_time = 10.12 - self.daemon.do_light(SETTLING) - with patch.object(powerd, 'FADE_SECONDS', .24), patch.object(powerd.time, 'monotonic', return_value=10.36): - self.daemon.tick_fade() + shared_harness().ask('bl_tick 10.12') + self.assertAlmostEqual(self.level(), 600, delta=1) + shared_harness().ask('bl_light 10.12') + reply = shared_harness().ask('bl_tick 10.36') self.assertEqual(self.level(), 1200) - self.assertEqual(self.daemon.saved, 1200) + self.assertEqual(reply, 'VAL 0 1200') def test_suspend_finishes_a_dark_transition_before_freezing(self): - with patch.object(powerd, 'FADE_SECONDS', .24): - self.daemon.do_dark(None) - self.daemon.finish_dark_fade() + self.init_bl(0.24) + shared_harness().ask('bl_dark 10.0') + self.assertEqual(shared_harness().ask('bl_finish_dark'), 'VAL 0') self.assertEqual(self.level(), 0) - self.assertIsNone(self.daemon.fade) - - def test_a_fade_writes_once_a_frame_however_often_the_loop_turns(self): - # Each backlight write is a kernel uevent that wakes the loop again at once. - writes = [] - real_write = Path.write_text - - def write_text(path, data, *args, **kwargs): - writes.append(data) - return real_write(path, data, *args, **kwargs) - (self.panel / 'brightness').write_text('1200\n') - with patch.object(powerd, 'FADE_SECONDS', .24), patch.object(Path, 'write_text', write_text): - with patch.object(powerd.time, 'monotonic', return_value=10): - self.daemon.do_dark(None) - self.daemon.tick_fade() - first = len(writes) - for i in range(1000): # a busy loop within one frame - with patch.object(powerd.time, 'monotonic', return_value=10 + i * 1e-5): - self.daemon.tick_fade() - self.assertEqual(len(writes), first) - with patch.object(powerd.time, 'monotonic', return_value=10 + powerd.FRAME_SECONDS + 1e-6): - self.assertEqual(self.daemon.next_frame(), 0) - self.daemon.tick_fade() - self.assertEqual(len(writes), first + 1) - with patch.object(powerd.time, 'monotonic', return_value=10.3): - self.daemon.tick_fade() # the last frame is written whenever it is due - self.assertEqual(self.level(), 0) - self.assertIsNone(self.daemon.fade) def test_shutdown_keeps_a_changed_level_but_never_a_dark_panel(self): (self.panel / 'brightness').write_text('700\n') - with self.assertRaises(SystemExit): - self.daemon.stop_brightness() + shared_harness().ask('bl_stop') self.assertEqual(self.remembered.read_text(), '700\n') (self.panel / 'brightness').write_text('0\n') - with self.assertRaises(SystemExit): - self.daemon.stop_brightness() + shared_harness().ask('bl_stop') self.assertEqual(self.remembered.read_text(), '700\n') def test_a_restart_while_dimmed_leaves_the_users_level_for_the_next_daemon(self): - # An update restarts the daemon; the next one knows nothing of the dim. - (self.panel / 'brightness').write_text('1600\n') - self.daemon.dim_saved, self.daemon.dim_level = 1600, 1000 (self.panel / 'brightness').write_text('1000\n') - with self.assertRaises(SystemExit): - self.daemon.stop_brightness() + shared_harness().ask('bl_set_dim 1600 1000') + shared_harness().ask('bl_stop') self.assertEqual(self.level(), 1600) self.assertEqual(self.remembered.read_text(), '1600\n') def test_a_restart_in_the_dark_or_mid_fade_comes_back_lit_at_the_users_level(self): - socket_path = self.remembered.parent.parent / 'ctl' - socket_path.write_text('') # the socket outlives a restart, not a boot - for fade in (0, .24): + self.sock.write_text('') + for fade in (0.0, 0.24): with self.subTest(fade=fade): (self.panel / 'brightness').write_text('1200\n') - daemon = powerd.Daemon() - with patch.object(powerd, 'FADE_SECONDS', fade): - daemon.do_dark(None) - daemon.tick_fade() - with self.assertRaises(SystemExit): - daemon.stop_brightness() + self.init_bl(fade) + shared_harness().ask('bl_dark 10.0') + shared_harness().ask('bl_tick 10.05') + shared_harness().ask('bl_stop') self.assertEqual(self.level(), 0) - with patch.object(powerd, 'SOCKET', str(socket_path)): - powerd.Daemon().start_lit() + self.init_bl(0.0) + shared_harness().ask('bl_start_lit') self.assertEqual(self.level(), 1200) -class SleepAccounting(unittest.TestCase): - """How long a suspend in flight has been awake, and what that may conclude.""" - - def setUp(self): - work = tempfile.TemporaryDirectory() - self.addCleanup(work.cleanup) - self.stats = Path(work.name) - for name, value in (('success', 3), ('fail', 0)): - (self.stats / name).write_text(f'{value}\n') - self.logs = [] - for target, value in (('STATS', self.stats), ('log', self.logs.append)): - patcher = patch.object(powerd, target, value) - patcher.start() - self.addCleanup(patcher.stop) - self.daemon = powerd.Daemon() - self.fed = [] - - def feed(event): # what the machine does with them: the suspend is no longer in flight - self.fed.append(event) - self.daemon.machine.inflight = False - self.daemon.feed = feed - self.daemon.machine.inflight = True - self.daemon.begin_sleep_record() - self.daemon.watching_unit = True # no unit watcher thread here - self.daemon.last_turn = 1000.0 - - def turns(self, count, step, start=None): - now = self.daemon.last_turn if start is None else start - for _ in range(count): - now += step - self.daemon.count_awake(now) - return now - - def test_a_busy_loop_is_not_time_awake(self): - self.turns(20000, 0.0005) # 20000 turns in 10 s - self.assertAlmostEqual(self.daemon.awake, 10, delta=0.01) - self.assertEqual(self.fed, []) - - def test_a_freeze_or_a_clock_that_runs_in_sleep_is_not_time_awake(self): - self.turns(1, 3600.0) # frozen, or asleep on a kernel whose clock runs on - self.turns(1, -5.0) # and never negative - self.assertLessEqual(self.daemon.awake, powerd.AWAKE_STEP_MAX) - self.assertEqual(self.fed, []) - - def test_a_suspend_not_begun_in_30_s_awake_did_not_happen(self): - self.turns(int(29.9 / powerd.TICK_SECONDS), powerd.TICK_SECONDS) - self.assertEqual(self.fed, []) - self.turns(10, powerd.TICK_SECONDS) - self.assertEqual(self.fed, ['timeout']) - self.assertTrue(any('suspend did not happen' in line for line in self.logs)) - - def test_a_sleep_that_began_ends_only_by_its_end(self): - self.turns(200, powerd.TICK_SECONDS) - self.daemon.sleep_began('logind') - self.assertEqual(self.daemon.awake, 0) - self.turns(int(100 / powerd.TICK_SECONDS), powerd.TICK_SECONDS) # a wake press, a slow resume - self.assertEqual(self.fed, []) - (self.stats / 'success').write_text('4\n') - self.daemon.sleep_finished('logind') - self.assertEqual(self.fed, ['sleep-ended']) - self.assertTrue(any(line.startswith('sleep-ended result=slept ') and 'end=logind' in line - for line in self.logs), self.logs) - - def test_an_end_never_seen_is_concluded_from_the_counters_at_last(self): - self.daemon.sleep_began('kernel') - (self.stats / 'fail').write_text('1\n') - self.turns(int((powerd.SLEEP_END_AWAKE_SECONDS + 1) / powerd.TICK_SECONDS), powerd.TICK_SECONDS) - self.assertEqual(self.fed, ['sleep-aborted']) - self.assertTrue(any(line.startswith('sleep-ended result=aborted ') and 'end=none' in line - for line in self.logs), self.logs) - - def test_every_line_of_a_read_from_the_monitor_is_seen(self): - read, write = os.pipe() - self.addCleanup(os.close, read) - self.addCleanup(os.close, write) - self.daemon.monitor = type('Monitor', (), {'stdout': open(read, 'rb', buffering=0, closefd=False)}) - seen = [] - self.daemon.monitor_line = seen.append - prepare = json.dumps({'member': 'PrepareForSleep', 'payload': {'data': [False]}}) - os.write(write, ('{"member": "NameOwnerChanged"}\n' + prepare + '\n{"memb').encode()) - self.daemon.read_monitor() - self.assertEqual(seen, ['{"member": "NameOwnerChanged"}', prepare]) - os.write(write, b'er": "x"}\n') - self.daemon.read_monitor() - self.assertEqual(seen[-1], '{"member": "x"}') - - -class SuspendRequest(unittest.TestCase): - def test_only_a_board_that_cannot_sleep_is_told_from_a_refusal_for_now(self): - for answer, event in (('s "na"', 'suspend-unavailable'), ('s "no"', 'suspend-unavailable'), - ('s "challenge"', 'suspend-refused'), ('', 'suspend-refused')): - daemon, posted = powerd.Daemon(), [] - daemon.post = posted.append - reply = subprocess.CompletedProcess([], 0, answer + '\n', '') - with patch.object(powerd, 'command', return_value=reply), patch.object(powerd, 'log'): - daemon.request_suspend() - self.assertEqual(posted, [event], answer) - - -class LogindSleep(unittest.TestCase): - """logind refuses a delay inhibitor while its sleep runs ("already running").""" +class EventLoopFixture(unittest.TestCase): + """The real compiled C99 event loop with fake sysfs, pipes, and control socket.""" def setUp(self): - self.daemon = powerd.Daemon() - self.started = [] - alive = type('Alive', (), {'poll': lambda self: None, 'terminate': lambda self: None, - 'wait': lambda self: 0}) - patcher = patch.object(powerd.subprocess, 'Popen', side_effect=lambda *_: self.started.append(1) or alive()) - patcher.start() - self.addCleanup(patcher.stop) - - def test_the_inhibitor_waits_for_loginds_end_of_the_sleep(self): - daemon = self.daemon - daemon.logind_asleep = True - daemon.take_inhibitor() - daemon.keep_inhibitor() - self.assertEqual(self.started, []) - daemon.logind_asleep = False # PrepareForSleep(false) - daemon.keep_inhibitor() - self.assertEqual(len(self.started), 1) - - def test_without_loginds_end_it_is_asked_a_while_after_systemd_suspend_ended(self): - daemon = self.daemon - daemon.logind_asleep = True - daemon.take_inhibitor() - daemon.logind_busy_until = time.monotonic() - 1 # set by sleep_finished('unit'), now past - daemon.keep_inhibitor() - self.assertEqual(len(self.started), 1) - - -class EventLoop(unittest.TestCase): - """The real loop with a fake sysfs, keys through a pipe and no logind.""" + self._prepare() + self._start_daemon() - def setUp(self): + def _prepare(self): work = tempfile.TemporaryDirectory() self.addCleanup(work.cleanup) self.work = Path(work.name) @@ -853,76 +739,116 @@ def setUp(self): self.stats.mkdir() self.set_stats(3, 0) (self.work / 'wakeup_count').write_text('7\n') - self.requests = [] - self.unit_state = 'activating' self.remembered = self.work / 'state/brightness' self.remembered.parent.mkdir() self.remembered.write_text('1563\n') - for target, value in (('SETTLE_SECONDS', 0.1), ('FADE_SECONDS', 0), ('IDLE_GRACE_SECONDS', 0.1), - ('STATS', self.stats), ('BACKLIGHTS', self.work / 'backlight'), - ('BRIGHTNESS', self.remembered), - ('WAKEUP_COUNT', self.work / 'wakeup_count'), ('SOCKET', str(self.work / 'ctl')), - ('session_user', lambda: None), ('command', self.fake_command), ('log', lambda *_: None)): - patcher = patch.object(powerd, target, value) - patcher.start() - self.addCleanup(patcher.stop) - self.daemon = powerd.Daemon() + self.socket_path = self.work / 'ctl' + self.req_log = self.work / 'requests.log' + self.unit_state_file = self.work / 'unit_state' + self.unit_state_file.write_text('activating\n') + self.spawn_log = self.work / 'spawn.log' + + bin_dir = self.work / 'bin' + bin_dir.mkdir() + (bin_dir / 'busctl').write_text( + '#!/bin/sh\n' + f'echo "busctl $*" >> "{self.req_log}"\n' + 'case "$*" in *CanSuspend*) echo \'s "yes"\';; *) echo \'s ""\';; esac\n' + ) + (bin_dir / 'busctl').chmod(0o755) + (bin_dir / 'systemctl').write_text( + '#!/bin/sh\n' + f'echo "systemctl $*" >> "{self.req_log}"\n' + f'case "$*" in *ActiveState*) cat "{self.unit_state_file}";; esac\n' + ) + (bin_dir / 'systemctl').chmod(0o755) + self.key_read, self.key_write = os.pipe() - monitor_read, self.monitor_write = os.pipe() - self.daemon.keys[self.key_read] = 'fake' - self.daemon.take_inhibitor = self.daemon.release_inhibitor = lambda: None - self.daemon.scan_keys = lambda: None - monitor = open(monitor_read) - def start_monitor(): - self.daemon.monitor = type('Monitor', (), {'stdout': monitor}) - self.daemon.start_monitor = start_monitor - real_open = self.daemon.open_socket - def open_socket(): - with patch.object(powerd.os, 'chown'), patch.object(powerd.grp, 'getgrnam') as group: - group.return_value.gr_gid = 0 - return real_open() - self.daemon.open_socket = open_socket - loop = threading.Thread(target=self.daemon.run, daemon=True) - def stop_loop(): - self.daemon.stopping = True - os.write(self.daemon.wake_write, b'.') - loop.join(3) - self.assertFalse(loop.is_alive()) - self.stop_loop = stop_loop - def stop(): - stop_loop() - monitor.close() - os.close(self.monitor_write) - self.addCleanup(stop) - loop.start() - self.wait(lambda: Path(powerd.SOCKET).exists()) - - def fake_command(self, *argv, **_): - self.requests.append(argv) - out = 's "yes"\n' if 'CanSuspend' in argv else 's ""\n' - if 'ActiveState' in argv: - out = self.unit_state + '\n' - return subprocess.CompletedProcess(argv, 0, out, '') + self.monitor_read, self.monitor_write = os.pipe() + self.addCleanup(os.close, self.key_write) + self.addCleanup(os.close, self.monitor_write) + self.bin_dir = bin_dir + + def _start_daemon(self, extra_env=None): + env = { + **os.environ, + 'PATH': f'{self.bin_dir}:{os.environ.get("PATH", "/usr/bin:/bin")}', + 'OMARCHY_POWERD_SOCKET': str(self.socket_path), + 'OMARCHY_POWERD_STATS': str(self.stats), + 'OMARCHY_POWERD_WAKEUP_COUNT': str(self.work / 'wakeup_count'), + 'OMARCHY_POWERD_BACKLIGHTS': str(self.work / 'backlight'), + 'OMARCHY_POWERD_BRIGHTNESS': str(self.remembered), + 'OMARCHY_POWERD_SETTLE_SECONDS': '0.1', + 'OMARCHY_POWERD_FADE_SECONDS': '0', + 'OMARCHY_POWERD_IDLE_GRACE_SECONDS': '0.1', + 'OMARCHY_POWERD_NO_DBUS': '1', + 'OMARCHY_POWERD_NO_CHOWN': '1', + 'OMARCHY_POWERD_NO_SCAN': '1', + 'OMARCHY_POWERD_NO_SESSION': '1', + 'OMARCHY_POWERD_KEY_FD': str(self.key_read), + 'OMARCHY_POWERD_MONITOR_FD': str(self.monitor_read), + **(extra_env or {}), + } + env = {key: value for key, value in env.items() if value is not None} + self.proc = subprocess.Popen( + [str(compiled_binary())], + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + pass_fds=(self.key_read, self.monitor_read), + ) + self.addCleanup(self._stop_daemon) + self.wait(lambda: self.socket_path.exists()) + + def _stop_daemon(self): + if self.proc.poll() is None: + self.proc.terminate() + try: + self.proc.wait(timeout=3) + except subprocess.TimeoutExpired: + self.proc.kill() + self.proc.wait() + for s in (self.proc.stdout, self.proc.stderr): + if s and not s.closed: + s.close() + for fd in (self.key_read, self.monitor_read): + try: + os.close(fd) + except OSError: + pass def set_stats(self, success, fail): - for name, value in (('fail', fail), ('success', success)): # atomic, like sysfs + for name, value in (('fail', fail), ('success', success)): (self.stats / 'new').write_text(f'{value}\n') os.replace(self.stats / 'new', self.stats / name) + def requests(self): + return self.req_log.read_text().splitlines() if self.req_log.exists() else [] + + def state_tuple(self): + parts = self.ask('test-state').split() + return { + 'state': parts[0], + 'inflight': parts[1] == '1', + 'sleep_begun': parts[2] == '1', + 'logind_asleep': parts[3] == '1', + 'home_in_combo': parts[4] == '1', + 'lit_at': float(parts[5]), + } + def press(self, code=116, when=None): - """A tap: the key goes down and comes up 50 ms later.""" when = time.monotonic() if when is None else when up = when + 0.05 - os.write(self.key_write, powerd.INPUT_EVENT.pack(int(when), int(when % 1 * 1e6), 1, code, 1) + - powerd.INPUT_EVENT.pack(int(up), int(up % 1 * 1e6), 1, code, 0)) + os.write(self.key_write, INPUT_EVENT.pack(int(when), int(when % 1 * 1e6), 1, code, 1) + + INPUT_EVENT.pack(int(up), int(up % 1 * 1e6), 1, code, 0)) def wait(self, condition, seconds=3): deadline = time.monotonic() + seconds while time.monotonic() < deadline: if condition(): return - time.sleep(0.005) - self.fail(f'not reached; state {self.daemon.machine.state}, requests {self.requests}') + time.sleep(0.01) + self.fail(f'not reached; requests={self.requests()}') def brightness(self): return (self.panel / 'brightness').read_text().strip() @@ -930,44 +856,30 @@ def brightness(self): def ask(self, request): with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: connection.settimeout(2) - connection.connect(powerd.SOCKET) + connection.connect(str(self.socket_path)) connection.sendall(request.encode() + b'\n') - return connection.recv(64).decode().strip() - - def test_home_alone_starts_the_home_action_and_a_screenshot_chord_does_not(self): - # The action comes from the button: no labwc binding or keyboard - # state in between. Half of Home + Power starts nothing. - user = pwd.struct_passwd(('tablet', 'x', 1000, 1000, '', '/home/tablet', '/bin/bash')) - spawned = [] - with patch.object(powerd, 'session_user', lambda: user), \ - patch.object(powerd, 'spawn_as_user', lambda *argv, **options: spawned.append((argv, options))): - when = time.monotonic() - event = powerd.INPUT_EVENT.pack - os.write(self.key_write, b''.join(event(int(when+i/10), int((when+i/10)%1*1e6), 1, code, down) - for i, (code, down) in enumerate(((116, 1), (172, 1), (172, 0), (116, 0))))) - self.wait(lambda: self.daemon.buttons.home_in_combo) - self.assertEqual(spawned, []) - self.press(172) - self.wait(lambda: spawned) - self.assertEqual(spawned[0][0][1:], ('omarchy-home-button',)) - self.assertEqual(self.ask('status'), 'ON') + return connection.recv(128).decode().strip() + +class EventLoop(EventLoopFixture): def test_idle_dim_halves_the_range_and_any_input_restores_the_level(self): self.assertEqual(self.ask('dim'), 'ok') self.assertEqual(self.brightness(), '1500') self.assertEqual(self.ask('als-state'), 'dark') self.assertEqual(self.ask('brightness panel 600 1500'), 'held') - self.ask('undim'); self.assertEqual(self.brightness(), '1563') - # A level changed while dimmed is still restored: a touch must never leave the panel dim. + self.ask('undim') + self.assertEqual(self.brightness(), '1563') self.ask('dim') (self.panel / 'brightness').write_text('700\n') - self.ask('undim'); self.assertEqual(self.brightness(), '1563') + self.ask('undim') + self.assertEqual(self.brightness(), '1563') def test_idle_dim_never_brightens_a_panel_already_at_half_or_below(self): (self.panel / 'brightness').write_text('900\n') self.assertEqual(self.ask('dim'), 'ok') self.assertEqual(self.brightness(), '900') - self.ask('undim'); self.assertEqual(self.brightness(), '900') + self.ask('undim') + self.assertEqual(self.brightness(), '900') def test_the_idle_dim_comes_ten_seconds_before_the_lock(self): idle = (PROJECT / 'desktop/shell/shell/plugins/services/idle/Service.qml').read_text() @@ -982,162 +894,364 @@ def test_automatic_brightness_obeys_power_state_and_manual_changes(self): 'brightness other 1900 1800', 'brightness panel ² 1800'): self.assertEqual(self.ask(request), 'held') self.assertEqual(self.brightness(), '1800') - self.press(); self.wait(lambda: self.brightness() == '0') + self.press() + self.wait(lambda: self.brightness() == '0') self.assertEqual(self.ask('brightness panel 1800 0'), 'held') self.assertEqual(self.brightness(), '0') - def test_press_sleep_wake(self): - machine = self.daemon.machine self.assertEqual(self.ask('input'), 'lit') self.press() self.wait(lambda: self.brightness() == '0') self.assertEqual(self.ask('input'), 'dark') - self.wait(lambda: ('systemctl', 'suspend') in self.requests) - self.assertEqual(machine.state, SUSPENDING) - # Asleep, then the wake key is the first thing the thawed daemon sees. + self.wait(lambda: 'systemctl suspend' in self.requests()) + self.assertEqual(self.state_tuple()['state'], SUSPENDING) self.press() self.wait(lambda: self.brightness() == '1563') - self.assertEqual((machine.state, machine.inflight), (ON, True)) - # Pressed before it lit, delivered after: that wake took care of it. - self.press(when=self.daemon.lit_at - 0.5) + st = self.state_tuple() + self.assertEqual((st['state'], st['inflight']), (ON, True)) + self.press(when=st['lit_at'] - 0.5) self.set_stats(4, 0) - self.unit_state = 'inactive' - self.wait(lambda: not machine.inflight) - self.assertEqual((machine.state, self.brightness()), (ON, '1563')) - # The next press is a new command. + self.unit_state_file.write_text('inactive\n') + self.wait(lambda: not self.state_tuple()['inflight']) + self.assertEqual((self.state_tuple()['state'], self.brightness()), (ON, '1563')) self.press() self.wait(lambda: self.brightness() == '0') def test_a_wake_without_a_button_stays_dark(self): self.press() - self.wait(lambda: ('systemctl', 'suspend') in self.requests) + self.wait(lambda: 'systemctl suspend' in self.requests()) self.set_stats(4, 0) - self.unit_state = 'inactive' - self.wait(lambda: not self.daemon.machine.inflight) + self.unit_state_file.write_text('inactive\n') + self.wait(lambda: not self.state_tuple()['inflight']) self.assertEqual(self.brightness(), '0') - self.assertIn(self.daemon.machine.state, (SETTLING, SUSPENDING)) + self.assertIn(self.state_tuple()['state'], (SETTLING, SUSPENDING)) def test_a_failed_kernel_attempt_is_not_the_end_of_the_sleep(self): - machine = self.daemon.machine self.press() - self.wait(lambda: ('systemctl', 'suspend') in self.requests) + self.wait(lambda: 'systemctl suspend' in self.requests()) count = self.work / 'wakeup_count' before = count.stat().st_mtime_ns - time.sleep(0.01) - self.set_stats(3, 1) # systemd-sleep goes on to try again - self.wait(lambda: count.stat().st_mtime_ns > before) # armed again + time.sleep(0.02) + self.set_stats(3, 1) + self.wait(lambda: count.stat().st_mtime_ns > before) time.sleep(0.2) - self.assertEqual((machine.state, machine.inflight), (SUSPENDING, True)) - self.press() # the real wake + st = self.state_tuple() + self.assertEqual((st['state'], st['inflight']), (SUSPENDING, True)) + self.press() self.wait(lambda: self.brightness() == '1563') - self.assertEqual((machine.state, machine.inflight), (ON, True)) + st = self.state_tuple() + self.assertEqual((st['state'], st['inflight']), (ON, True)) self.set_stats(4, 1) - self.unit_state = 'inactive' - self.wait(lambda: not machine.inflight) + self.unit_state_file.write_text('inactive\n') + self.wait(lambda: not self.state_tuple()['inflight']) def test_a_press_after_it_lit_darkens_while_the_sleep_finishes(self): self.press() - self.wait(lambda: ('systemctl', 'suspend') in self.requests) + self.wait(lambda: 'systemctl suspend' in self.requests()) self.press() self.wait(lambda: self.brightness() == '1563') - self.press(when=time.monotonic() + 0.001) + self.press(when=time.monotonic() + 0.01) self.wait(lambda: self.brightness() == '0') - self.assertTrue(self.daemon.machine.inflight) + self.assertTrue(self.state_tuple()['inflight']) def test_a_suspend_from_elsewhere_arms_the_wakeup_count_and_a_press_lights(self): count = self.work / 'wakeup_count' count.write_text('9\n') before = count.stat().st_mtime_ns - time.sleep(0.01) + time.sleep(0.02) os.write(self.monitor_write, (json.dumps({'member': 'PrepareForSleep', 'payload': {'data': [True]}}) + '\n').encode()) self.wait(lambda: self.brightness() == '0') self.assertGreater(count.stat().st_mtime_ns, before) self.press() self.wait(lambda: self.brightness() == '1563') - self.assertEqual(self.daemon.machine.state, ON) + self.assertEqual(self.state_tuple()['state'], ON) def test_idle_through_the_socket_and_a_press_during_the_settle_time(self): self.assertEqual(self.ask('idle'), 'ok') self.wait(lambda: self.brightness() == '0') self.press() self.wait(lambda: self.brightness() == '1563') - time.sleep(0.25) # past the settle time: cancelled - self.assertNotIn(('systemctl', 'suspend'), self.requests) - self.assertEqual(self.daemon.machine.state, ON) - - def test_the_wake_fade_while_the_sleep_finishes_neither_spins_nor_ends_it(self): - # The kernel sends a uevent for every backlight write (backlight_generate_event) to the - # socket this loop watches: counted in loop turns, the 30 s ran out within the wake's fade. - logs, turns = [], [] - ours, kernel = socket.socketpair(socket.AF_UNIX, socket.SOCK_DGRAM) - self.addCleanup(kernel.close) - self.addCleanup(ours.close) - self.addCleanup(self.stop_loop) # runs first: the loop must not watch a closed socket - ours.setblocking(False) - kernel.setblocking(False) - brightness = self.panel / 'brightness' - real_write = Path.write_text - - def write_text(path, data, *args, **kwargs): - result = real_write(path, data, *args, **kwargs) - if path == brightness: - try: - kernel.send(b'change@/devices/backlight/panel\0ACTION=change\0SUBSYSTEM=backlight\0SOURCE=sysfs\0') - except BlockingIOError: - pass - return result - real_watch = self.daemon.watch_kernel - - def watch_kernel(): # once a turn of the loop - turns.append(1) - real_watch() - with patch.object(Path, 'write_text', write_text), patch.object(powerd, 'FADE_SECONDS', 0.24), \ - patch.object(powerd, 'log', logs.append): - self.daemon.uevents = ours - self.daemon.watch_kernel = watch_kernel - self.press() - self.wait(lambda: ('systemctl', 'suspend') in self.requests) - self.set_stats(4, 0) # it slept and resumed; systemd-suspend still runs - before = len(turns) - self.press() # the wake - self.wait(lambda: self.brightness() == '1563') - time.sleep(0.1) - self.assertLess(len(turns) - before, 200) - self.unit_state = 'inactive' - self.wait(lambda: not self.daemon.machine.inflight) - self.assertTrue(any(line.startswith('sleep-ended result=slept ') for line in logs), logs) - self.assertFalse(any('did not happen' in line for line in logs), logs) + time.sleep(0.25) + self.assertNotIn('systemctl suspend', self.requests()) + self.assertEqual(self.state_tuple()['state'], ON) def test_a_sleep_logind_announced_ends_with_loginds_end_also_after_a_wake_press(self): - logs = [] - def prepare_for_sleep(sleeping): os.write(self.monitor_write, (json.dumps({'member': 'PrepareForSleep', 'payload': {'data': [sleeping]}}) + '\n').encode()) - with patch.object(powerd, 'log', logs.append): - self.unit_state = 'inactive' # systemd-suspend has not started yet: that is not its end - self.press() - self.wait(lambda: ('systemctl', 'suspend') in self.requests) - prepare_for_sleep(True) - self.wait(lambda: self.daemon.sleep_begun and self.daemon.logind_asleep) - time.sleep(0.3) - self.assertTrue(self.daemon.machine.inflight) - self.unit_state = 'activating' - self.set_stats(4, 0) - self.press() # the wake: lit at once, the sleep still finishing - self.wait(lambda: self.brightness() == '1563') - self.assertEqual((self.daemon.machine.state, self.daemon.machine.inflight), (ON, True)) - prepare_for_sleep(False) - self.wait(lambda: not self.daemon.machine.inflight) - self.assertFalse(self.daemon.logind_asleep) - self.assertTrue(any(line.startswith('sleep-ended result=slept ') and 'end=logind' in line - for line in logs), logs) - self.assertFalse(any('did not happen' in line for line in logs), logs) + self.unit_state_file.write_text('inactive\n') + self.press() + self.wait(lambda: 'systemctl suspend' in self.requests()) + prepare_for_sleep(True) + self.wait(lambda: self.state_tuple()['sleep_begun'] and self.state_tuple()['logind_asleep']) + time.sleep(0.3) + self.assertTrue(self.state_tuple()['inflight']) + self.unit_state_file.write_text('activating\n') + self.set_stats(4, 0) + self.press() + self.wait(lambda: self.brightness() == '1563') + st = self.state_tuple() + self.assertEqual((st['state'], st['inflight']), (ON, True)) + prepare_for_sleep(False) + self.wait(lambda: not self.state_tuple()['inflight']) + self.assertFalse(self.state_tuple()['logind_asleep']) + + +FAKE_LOGIND = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static FILE *out; +static int held[64]; +static int nheld; + +static int inhibit(sd_bus_message *m, void *userdata, sd_bus_error *error) +{ + (void)userdata; (void)error; + const char *what, *who, *why, *mode; + int r = sd_bus_message_read(m, "ssss", &what, &who, &why, &mode); + if (r < 0) + return r; + int p[2]; + if (pipe2(p, O_CLOEXEC) < 0) + return -errno; + if (nheld < 64) + held[nheld++] = p[1]; + else + close(p[1]); + fprintf(out, "Inhibit %s %s %s\n", what, who, mode); + r = sd_bus_reply_method_return(m, "h", p[0]); + close(p[0]); + return r; +} + +static int can_suspend(sd_bus_message *m, void *userdata, sd_bus_error *error) +{ + (void)userdata; (void)error; + fprintf(out, "CanSuspend\n"); + return sd_bus_reply_method_return(m, "s", "yes"); +} + +static int block_inhibited(sd_bus *bus, const char *path, const char *interface, const char *property, + sd_bus_message *reply, void *userdata, sd_bus_error *error) +{ + (void)bus; (void)path; (void)interface; (void)property; (void)userdata; (void)error; + fprintf(out, "BlockInhibited\n"); + return sd_bus_message_append(reply, "s", ""); +} + +static const sd_bus_vtable manager[] = { + SD_BUS_VTABLE_START(0), + SD_BUS_METHOD("Inhibit", "ssss", "h", inhibit, SD_BUS_VTABLE_UNPRIVILEGED), + SD_BUS_METHOD("CanSuspend", "", "s", can_suspend, SD_BUS_VTABLE_UNPRIVILEGED), + SD_BUS_PROPERTY("BlockInhibited", "s", block_inhibited, 0, 0), + SD_BUS_SIGNAL("PrepareForSleep", "b", 0), + SD_BUS_VTABLE_END +}; + +/* Inhibitors whose other end the client still holds open. */ +static int count_held(void) +{ + int n = 0; + for (int i = 0; i < nheld; i++) { + struct pollfd p = { .fd = held[i], .events = 0 }; + if (poll(&p, 1, 0) == 0) + n++; + } + return n; +} + +int main(int argc, char **argv) +{ + if (argc != 2) + return 2; + out = fopen(argv[1], "a"); + if (!out) + return 1; + setvbuf(out, NULL, _IOLBF, 0); + sd_bus *bus = NULL; + sd_bus_slot *slot = NULL; + if (sd_bus_open_system(&bus) < 0 || + sd_bus_add_object_vtable(bus, &slot, "/org/freedesktop/login1", + "org.freedesktop.login1.Manager", manager, NULL) < 0 || + sd_bus_request_name(bus, "org.freedesktop.login1", 0) < 0) + return 1; + fprintf(out, "ready\n"); + char line[64]; + size_t len = 0; + for (;;) { + while (sd_bus_process(bus, NULL) > 0) + ; + struct pollfd p[2] = { + { .fd = sd_bus_get_fd(bus), .events = POLLIN }, + { .fd = 0, .events = POLLIN }, + }; + poll(p, 2, 50); + if (!(p[1].revents & (POLLIN | POLLHUP))) + continue; + char c; + ssize_t n = read(0, &c, 1); + if (n <= 0) + return 0; + if (c != '\n') { + if (len < sizeof(line) - 1) + line[len++] = c; + continue; + } + line[len] = '\0'; + len = 0; + if (strcmp(line, "sleep 1") == 0 || strcmp(line, "sleep 0") == 0) + sd_bus_emit_signal(bus, "/org/freedesktop/login1", "org.freedesktop.login1.Manager", + "PrepareForSleep", "b", line[6] == '1'); + else if (strcmp(line, "held") == 0) + fprintf(out, "held %d\n", count_held()); + sd_bus_flush(bus); + } +} +""" + +BUS_CONFIG = """ + + unix:path={path} + EXTERNAL + + + + + + + +""" + + +@functools.lru_cache(maxsize=1) +def fake_logind_binary(): + tmp = Path(tempfile.mkdtemp(prefix='omarchy-powerd-logind-')) + atexit.register(shutil.rmtree, tmp, True) + source = tmp / 'fake-logind.c' + source.write_text(FAKE_LOGIND) + binary = tmp / 'fake-logind' + subprocess.run([os.environ.get('CC', 'cc'), '-O2', '-Wall', '-Wextra', '-Werror', '-std=c99', + str(source), *libsystemd_flags(), '-o', str(binary)], check=True) + return binary + + +class LogindOverDbus(EventLoopFixture): + """The daemon against logind on a private system bus, through sd-bus as on a tablet. + + The other loop tests feed logind's signals through a pipe and answer its + calls with a busctl stub; these cover the sd-bus code itself: the delay + inhibitor, the sleep signal and the questions asked before a suspend. + """ + def setUp(self): + if libsystemd_flags() is None: + self.skipTest('libsystemd headers missing: powerd is built without sd-bus') + daemon = shutil.which('dbus-daemon') + if daemon is None: + if os.environ.get('OMARCHY_TEST_REQUIRE_SD_BUS'): + self.fail('dbus-daemon is missing') + self.skipTest('dbus-daemon missing') + self._prepare() + config = self.work / 'bus.conf' + config.write_text(BUS_CONFIG.format(path=self.work / 'system_bus_socket')) + self.bus = subprocess.Popen([daemon, f'--config-file={config}', '--nofork', '--print-address'], + stdout=subprocess.PIPE, text=True) + self.addCleanup(self._stop, self.bus) + self.address = self.bus.stdout.readline().strip() + self.assertTrue(self.address, 'dbus-daemon printed no address') + self.logind_log = self.work / 'logind.log' + self.logind = self._start_logind() + self._start_daemon({'OMARCHY_POWERD_NO_DBUS': None, 'DBUS_SYSTEM_BUS_ADDRESS': self.address}) + + def _start_logind(self): + before = self.logind_lines().count('ready') + proc = subprocess.Popen([str(fake_logind_binary()), str(self.logind_log)], stdin=subprocess.PIPE, + env={**os.environ, 'DBUS_SYSTEM_BUS_ADDRESS': self.address}, text=True) + self.addCleanup(self._stop, proc) + self.wait(lambda: self.logind_lines().count('ready') > before) + return proc + + @staticmethod + def _stop(proc): + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=3) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + for stream in (proc.stdin, proc.stdout): + if stream and not stream.closed: + stream.close() + + def logind_lines(self): + return self.logind_log.read_text().splitlines() if self.logind_log.exists() else [] + + def tell_logind(self, command): + self.logind.stdin.write(command + '\n') + self.logind.stdin.flush() + + def inhibitors_held(self): + count = len([line for line in self.logind_lines() if line.startswith('held ')]) + self.tell_logind('held') + self.wait(lambda: len([line for line in self.logind_lines() if line.startswith('held ')]) > count) + return int([line for line in self.logind_lines() if line.startswith('held ')][-1].split()[1]) + + def wait_held(self, count, seconds=5): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if self.inhibitors_held() == count: + return + time.sleep(0.05) + self.fail(f'{count} inhibitors not reached; logind={self.logind_lines()}') -if __name__ == '__main__': - unittest.main() + def test_the_daemon_holds_a_delay_inhibitor_for_sleep(self): + self.wait(lambda: 'Inhibit sleep omarchy-powerd delay' in self.logind_lines()) + self.wait_held(1) + + def test_a_suspend_from_elsewhere_darkens_first_then_lets_the_sleep_through(self): + self.wait_held(1) + self.tell_logind('sleep 1') + self.wait(lambda: self.brightness() == '0') + self.wait_held(0) + self.wait(lambda: self.state_tuple()['logind_asleep']) + self.tell_logind('sleep 0') + self.wait(lambda: not self.state_tuple()['logind_asleep']) + self.press() + self.wait(lambda: self.brightness() == '1563') + self.assertEqual(self.state_tuple()['state'], ON) + self.wait_held(1) + + def test_its_own_suspend_asks_logind_over_the_bus_and_ends_with_loginds_signal(self): + self.wait_held(1) + self.unit_state_file.write_text('inactive\n') + self.press() + self.wait(lambda: 'systemctl suspend' in self.requests()) + self.assertIn('CanSuspend', self.logind_lines()) + self.assertFalse([r for r in self.requests() if r.startswith('busctl')], self.requests()) + self.tell_logind('sleep 1') + self.wait(lambda: self.state_tuple()['sleep_begun'] and self.state_tuple()['logind_asleep']) + self.set_stats(4, 0) + self.tell_logind('sleep 0') + self.wait(lambda: not self.state_tuple()['inflight']) + self.assertFalse(self.state_tuple()['logind_asleep']) + + def test_a_restarted_logind_gets_the_inhibitor_again(self): + self.wait_held(1) + self._stop(self.logind) + taken = self.logind_lines().count('Inhibit sleep omarchy-powerd delay') + self.logind = self._start_logind() + self.wait(lambda: self.logind_lines().count('Inhibit sleep omarchy-powerd delay') > taken) + self.wait_held(1) class LockedUsb(unittest.TestCase): @@ -1147,13 +1261,16 @@ def test_new_usb_devices_are_off_while_locked_and_on_after_unlock(self): for host in ('usb1', 'usb2'): (root / host).mkdir() (root / host / 'authorized_default').write_text('1') - with patch.object(powerd, 'USB_DEVICES', root): - powerd.usb_new_devices(False) - self.assertEqual({(root / h / 'authorized_default').read_text() for h in ('usb1', 'usb2')}, {'0'}) - powerd.usb_new_devices(True) - self.assertEqual({(root / h / 'authorized_default').read_text() for h in ('usb1', 'usb2')}, {'1'}) + shared_harness().ask(f'usb 0 {root}') + self.assertEqual({(root / h / 'authorized_default').read_text() for h in ('usb1', 'usb2')}, {'0'}) + shared_harness().ask(f'usb 1 {root}') + self.assertEqual({(root / h / 'authorized_default').read_text() for h in ('usb1', 'usb2')}, {'1'}) def test_the_lock_screen_reports_the_unlock(self): service = (PROJECT / 'desktop/shell/shell/plugins/lock/Service.qml').read_text() self.assertIn('"/usr/libexec/omarchy-powerctl", "unlocked"', service) - self.assertIn("request == 'unlocked'", PATH.read_text()) + self.assertIn('strcmp(req, "unlocked") == 0', SOURCE.read_text()) + + +if __name__ == '__main__': + unittest.main()