diff --git a/CHANGELOG.md b/CHANGELOG.md index 3de2cb1c..0f54d173 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,10 @@ release is checked here and released on by hand. - Lock, idle and brightness commands answer faster: the power control command is a small C program instead of Python (tcballard). +- The on-screen keyboard shows and hides without a start-up delay, and + about 11 MiB more memory is free: its controller is a small C program + instead of Python (tcballard). + - Upstream's commands show their texts instead of raw keys like `webapp.intro`, in every language upstream has, and Install > Browser gets past its browser policy step (jannyg). diff --git a/Makefile b/Makefile index 571024f8..b4d1688a 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,8 @@ # make install DESTDIR= OMARCHY= DBUS_NEXT= # # The compiles are the on-screen keyboard (wvkbd with this repository's -# patches), the startup cursor helper (wtype), the mute-switch and power-control helpers and the power daemon +# patches) and its controller, the startup cursor helper (wtype), the +# mute-switch and power-control helpers and the power daemon # (omarchy-powerd, against libsystemd's sd-bus: the recipe's makedepends); # desktop/install-tree puts every file in place. @@ -15,7 +16,7 @@ CC ?= cc CFLAGS ?= -O2 PKG_CONFIG ?= pkg-config -all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd $(BUILD)/omarchy-mute-switch $(BUILD)/omarchy-powerctl +all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd $(BUILD)/omarchy-mute-switch $(BUILD)/omarchy-powerctl $(BUILD)/omarchy-keyboard $(BUILD)/omarchy-powerd: desktop/configuration/powerd.c mkdir -p $(BUILD) @@ -30,6 +31,10 @@ $(BUILD)/omarchy-powerctl: desktop/configuration/powerctl.c mkdir -p $(BUILD) $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -std=c99 desktop/configuration/powerctl.c $(LDFLAGS) -o $@ +$(BUILD)/omarchy-keyboard: desktop/configuration/keyboard.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 $< $(LDFLAGS) -o $@ + $(BUILD)/wvkbd-mobintl: @test -d "$(WVKBD)" || { echo 'Set WVKBD to the wvkbd v0.20 source' >&2; exit 1; } @grep -q preferred_buffer_scale /usr/include/wayland-client-protocol.h || \ diff --git a/desktop/configuration/keyboard.c b/desktop/configuration/keyboard.c new file mode 100644 index 00000000..3770e5b2 --- /dev/null +++ b/desktop/configuration/keyboard.c @@ -0,0 +1,1383 @@ +/* Session controller for the theme-matched Wayland keyboard, and its policy. + * + * omarchy-keyboard show|hide|toggle what the person asks for (swipe up, bar button) + * omarchy-keyboard quiet the window opening next was not asked for by a tap + * omarchy-keyboard hold|release a shell surface (the control center) is over the app + * and has its keyboard: its field going off is no reason + * omarchy-keyboard listen the policy: reads the compositor's facts on stdin + * omarchy-keyboard restart|run (re)start the keyboard process itself + * + * When it opens or closes on its own is decided here and nowhere else. The + * compositor only reports facts, one line each on `listen`'s standard input + * (Labwc: , see its + * input/osk.h): text fields going on and off, apps asking for the keyboard, + * taps, keys typed on a physical keyboard, how many such keyboards there are. + */ + +#define _POSIX_C_SOURCE 200809L +#define _DEFAULT_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static char g_binary[PATH_MAX]; +static char g_pid_file[PATH_MAX]; +static char g_state_file[PATH_MAX]; +static char g_log_file[PATH_MAX]; +static char g_policy_socket[PATH_MAX]; +static const char *g_argv0 = "omarchy-keyboard"; + +static void init_paths(void) +{ + const char *root = getenv("OMARCHY_PATH"); + if (!root) + root = "/usr/share/omarchy"; + const char *runtime = getenv("XDG_RUNTIME_DIR"); + if (!runtime) + runtime = "/tmp"; + + snprintf(g_binary, sizeof(g_binary), + "%s/trials/wvkbd-mobintl-v0.20-font18-special15-state", root); + snprintf(g_pid_file, sizeof(g_pid_file), "%s/omarchy-keyboard.pid", runtime); + snprintf(g_state_file, sizeof(g_state_file), "%s/omarchy-keyboard-visible", runtime); + snprintf(g_log_file, sizeof(g_log_file), "%s/omarchy-keyboard.log", runtime); + snprintf(g_policy_socket, sizeof(g_policy_socket), "%s/omarchy-keyboard.sock", runtime); +} + +static double monotonic_now(void *ctx) +{ + (void)ctx; + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) + return 0.0; + return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9; +} + +static void sleep_ms(int ms) +{ + struct timespec ts; + ts.tv_sec = ms / 1000; + ts.tv_nsec = (long)(ms % 1000) * 1000000L; + while (nanosleep(&ts, &ts) == -1 && errno == EINTR) + ; +} + +static char *trim_whitespace(char *s) +{ + while (*s && isspace((unsigned char)*s)) + s++; + size_t len = strlen(s); + while (len > 0 && isspace((unsigned char)s[len - 1])) + s[--len] = '\0'; + return s; +} + +static bool read_small_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_small_file(const char *path, const char *data) +{ + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) + return false; + size_t len = strlen(data); + size_t off = 0; + while (off < len) { + ssize_t n = write(fd, data + off, len - off); + if (n < 0) { + if (errno == EINTR) + continue; + close(fd); + return false; + } + off += (size_t)n; + } + return close(fd) == 0; +} + +static pid_t live_pid(void) +{ + char buf[64]; + if (!read_small_file(g_pid_file, buf, sizeof(buf))) + return 0; + char *s = trim_whitespace(buf); + if (*s == '\0') + return 0; + char *end = NULL; + errno = 0; + long val = strtol(s, &end, 10); + if (errno != 0 || end == s || *end != '\0' || val <= 0) + return 0; + + char proc_exe[64]; + char proc_resolved[PATH_MAX]; + char bin_resolved[PATH_MAX]; + snprintf(proc_exe, sizeof(proc_exe), "/proc/%ld/exe", val); + if (!realpath(proc_exe, proc_resolved)) + return 0; + if (!realpath(g_binary, bin_resolved)) + return 0; + if (strcmp(proc_resolved, bin_resolved) != 0) + return 0; + return (pid_t)val; +} + +static bool visible(void *ctx) +{ + (void)ctx; + char buf[32]; + if (!read_small_file(g_state_file, buf, sizeof(buf))) + return false; + return strcmp(trim_whitespace(buf), "1") == 0; +} + +static void launch(void) +{ + char self_path[PATH_MAX]; + const char *exe = realpath("/proc/self/exe", self_path); + if (!exe) + exe = g_argv0; + + int log_fd = open(g_log_file, O_WRONLY | O_CREAT | O_APPEND, 0644); + if (log_fd < 0) { + perror("open log_file"); + exit(1); + } + + pid_t first = fork(); + if (first < 0) { + close(log_fd); + perror("fork"); + exit(1); + } + if (first == 0) { + /* Double-fork so the daemon is reparented to init and never zombies. */ + pid_t second = fork(); + if (second < 0) + _exit(127); + if (second > 0) + _exit(0); + + setsid(); + int devnull = open("/dev/null", O_RDONLY); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + if (devnull > STDERR_FILENO) + close(devnull); + } + dup2(log_fd, STDOUT_FILENO); + dup2(log_fd, STDERR_FILENO); + if (log_fd > STDERR_FILENO) + close(log_fd); + + execl(exe, exe, "run", (char *)NULL); + _exit(127); + } + + close(log_fd); + int status = 0; + while (waitpid(first, &status, 0) < 0 && errno == EINTR) + ; +} + +static pid_t wait_for_start(void) +{ + char status_path[64]; + char buf[4096]; + + for (int i = 0; i < 40; i++) { + pid_t pid = live_pid(); + if (pid > 0) { + snprintf(status_path, sizeof(status_path), + "/proc/%ld/status", (long)pid); + if (read_small_file(status_path, buf, sizeof(buf))) { + char *p = buf; + while (*p) { + char *nl = strchr(p, '\n'); + if (nl) + *nl = '\0'; + if (strncmp(p, "SigBlk:", 7) == 0) { + char *val = trim_whitespace(p + 7); + char *end = NULL; + unsigned long long mask = strtoull(val, &end, 16); + if (end != val && + (mask & (1ULL << (SIGUSR2 - 1)))) + return pid; + break; + } + if (!nl) + break; + p = nl + 1; + } + } + } + sleep_ms(50); + } + fprintf(stderr, "Keyboard did not start; see %s\n", g_log_file); + exit(1); +} + +static void show_keyboard(void *ctx) +{ + (void)ctx; + pid_t pid = live_pid(); + if (!pid) { + launch(); + pid = wait_for_start(); + } + kill(pid, SIGUSR2); +} + +static void hide_keyboard(void *ctx) +{ + (void)ctx; + pid_t pid = live_pid(); + if (pid) + kill(pid, SIGUSR1); +} + +/* -------------------------------------------------------------------------- + * Auto-show / auto-hide policy + * -------------------------------------------------------------------------- */ + +#define POLICY_TAP_MS 350 +#define POLICY_TAP_PX 12 +#define POLICY_TOUCH_WINDOW 0.6 +#define POLICY_SHOW_WAIT 0.5 +#define POLICY_HIDE_DELAY 0.25 + +struct policy { + void (*show)(void *); + void (*hide)(void *); + bool (*visible)(void *); + double (*now)(void *); + void *ctx; + + int field; + double touched_until; + double tapped_until; + double asked_until; + bool has_hide_at; + double hide_at; + bool hide_asked; + bool pressing; + bool opened_here; + bool hardware; + bool held; + int keyboards; +}; + +static void policy_init(struct policy *p, + void (*show_fn)(void *), + void (*hide_fn)(void *), + bool (*visible_fn)(void *), + double (*now_fn)(void *), + void *ctx) +{ + memset(p, 0, sizeof(*p)); + p->show = show_fn; + p->hide = hide_fn; + p->visible = visible_fn; + p->now = now_fn; + p->ctx = ctx; +} + +static void policy_open(struct policy *p) +{ + p->touched_until = 0.0; + p->tapped_until = 0.0; + p->asked_until = 0.0; + p->has_hide_at = false; + p->hide_asked = false; + if (p->hardware) + return; + p->opened_here = true; + if (!p->visible(p->ctx)) + p->show(p->ctx); +} + +static void policy_close(struct policy *p) +{ + p->has_hide_at = false; + p->hide_asked = false; + if (p->opened_here) { + p->opened_here = false; + p->hide(p->ctx); + } +} + +static bool parse_nonneg_int(const char *s, int *out) +{ + if (!s || !*s) + return false; + for (const char *c = s; *c; c++) { + if (!isdigit((unsigned char)*c)) + 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 policy_fact(struct policy *p, const char *line) +{ + double now = p->now(p->ctx); + char copy[512]; + size_t n = strlen(line); + if (n >= sizeof(copy)) + return; + memcpy(copy, line, n + 1); + + char *words[4]; + int count = 0; + char *cur = copy; + while (*cur) { + while (*cur && isspace((unsigned char)*cur)) + cur++; + if (!*cur) + break; + if (count == 4) { + count++; + break; + } + words[count++] = cur; + while (*cur && !isspace((unsigned char)*cur)) + cur++; + if (*cur) + *cur++ = '\0'; + } + + int v1 = 0, v2 = 0; + if (count == 3 && strcmp(words[0], "field") == 0 && + strcmp(words[1], "on") == 0 && parse_nonneg_int(words[2], &v1)) { + p->field = v1; + p->has_hide_at = false; + if (now < p->asked_until || + (p->pressing && now < p->touched_until) || + (p->field < 2 && now < p->tapped_until)) + policy_open(p); + } else if (count == 2 && strcmp(words[0], "field") == 0 && + strcmp(words[1], "off") == 0) { + p->field = 0; + if (p->opened_here && !p->held) { + p->has_hide_at = true; + p->hide_at = now + POLICY_HIDE_DELAY; + } + } else if (count == 1 && strcmp(words[0], "show") == 0) { + if (now < p->touched_until) + policy_open(p); + } else if (count == 1 && strcmp(words[0], "hide") == 0) { + if (p->opened_here) { + p->has_hide_at = true; + p->hide_at = now + POLICY_HIDE_DELAY; + p->hide_asked = true; + } + } else if (count == 1 && strcmp(words[0], "press") == 0) { + p->touched_until = now + POLICY_TOUCH_WINDOW; + p->pressing = true; + } else if (count == 3 && strcmp(words[0], "release") == 0 && + parse_nonneg_int(words[1], &v1) && + parse_nonneg_int(words[2], &v2)) { + p->pressing = false; + if (v1 <= POLICY_TAP_MS && v2 <= POLICY_TAP_PX) { + p->touched_until = now + POLICY_TOUCH_WINDOW; + p->tapped_until = now + POLICY_TOUCH_WINDOW; + if (p->field > 0 && p->field < 2) + policy_open(p); + } else { + p->touched_until = 0.0; + p->tapped_until = 0.0; + } + } else if (count == 1 && strcmp(words[0], "key") == 0) { + if (p->keyboards > 0) { + p->hardware = true; + p->touched_until = 0.0; + p->tapped_until = 0.0; + p->asked_until = 0.0; + p->opened_here = false; + if (p->visible(p->ctx)) + p->hide(p->ctx); + } + } else if (count == 2 && strcmp(words[0], "keyboards") == 0 && + parse_nonneg_int(words[1], &v1)) { + p->keyboards = v1; + if (p->keyboards == 0) + p->hardware = false; + } +} + +static void policy_person(struct policy *p, const char *action) +{ + if (strcmp(action, "hold") == 0) { + p->held = true; + p->has_hide_at = false; + p->hide_asked = false; + return; + } + if (strcmp(action, "release") == 0) { + p->held = false; + if (p->opened_here && !p->field) { + p->has_hide_at = true; + p->hide_at = p->now(p->ctx) + POLICY_HIDE_DELAY; + } + return; + } + if (strcmp(action, "quiet") == 0) { + p->touched_until = 0.0; + p->tapped_until = 0.0; + p->asked_until = 0.0; + return; + } + p->opened_here = false; + p->has_hide_at = false; + if (strcmp(action, "show") == 0) + p->hardware = false; +} + +static void policy_tick(struct policy *p) +{ + if (p->has_hide_at && p->now(p->ctx) >= p->hide_at) { + if (p->hide_asked || !p->field) + policy_close(p); + p->has_hide_at = false; + p->hide_asked = false; + } +} + +/* -------------------------------------------------------------------------- + * Policy IPC & compositor listener + * -------------------------------------------------------------------------- */ + +static void tell_policy(const char *action) +{ + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + if (strlen(g_policy_socket) >= sizeof(addr.sun_path)) + return; + memcpy(addr.sun_path, g_policy_socket, strlen(g_policy_socket) + 1); + + int fd = socket(AF_UNIX, SOCK_DGRAM, 0); + if (fd < 0) + return; + (void)sendto(fd, action, strlen(action), 0, + (struct sockaddr *)&addr, sizeof(addr)); + close(fd); +} + +static void listen_loop(void) +{ + struct policy pol; + policy_init(&pol, show_keyboard, hide_keyboard, visible, monotonic_now, NULL); + + unlink(g_policy_socket); + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + if (strlen(g_policy_socket) >= sizeof(addr.sun_path)) { + fprintf(stderr, "omarchy-keyboard: socket path too long\n"); + exit(1); + } + memcpy(addr.sun_path, g_policy_socket, strlen(g_policy_socket) + 1); + + int sock = socket(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); + if (sock < 0) { + perror("socket"); + exit(1); + } + if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + perror("bind"); + close(sock); + exit(1); + } + + int flags = fcntl(STDIN_FILENO, F_GETFL, 0); + if (flags >= 0) + fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); + + char pending[8192]; + size_t pending_len = 0; + bool discard_line = false; + + for (;;) { + int timeout_ms = -1; + if (pol.has_hide_at) { + double rem = pol.hide_at - pol.now(pol.ctx); + if (rem <= 0.0) + timeout_ms = 0; + else + timeout_ms = (int)(rem * 1000.0) + 1; + } + + struct pollfd fds[2]; + fds[0].fd = STDIN_FILENO; + fds[0].events = POLLIN; + fds[0].revents = 0; + fds[1].fd = sock; + fds[1].events = POLLIN; + fds[1].revents = 0; + + int ready = poll(fds, 2, timeout_ms); + if (ready < 0) { + if (errno == EINTR) + continue; + break; + } + + if (fds[1].revents & POLLIN) { + for (;;) { + char msg[65]; + ssize_t n = recv(sock, msg, sizeof(msg) - 1, 0); + if (n <= 0) + break; + msg[n] = '\0'; + policy_person(&pol, trim_whitespace(msg)); + } + } + + if (fds[0].revents & (POLLIN | POLLHUP | POLLERR)) { + for (;;) { + char chunk[4096]; + ssize_t n = read(STDIN_FILENO, chunk, sizeof(chunk)); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) + break; + if (errno == EINTR) + continue; + close(sock); + return; + } + if (n == 0) { + close(sock); + return; + } + + for (ssize_t i = 0; i < n; i++) { + char c = chunk[i]; + if (c == '\n') { + if (!discard_line) { + pending[pending_len] = '\0'; + policy_fact(&pol, pending); + } + pending_len = 0; + discard_line = false; + } else if (!discard_line) { + if (pending_len + 1 < sizeof(pending)) + pending[pending_len++] = c; + else + discard_line = true; + } + } + } + } + + policy_tick(&pol); + } + + close(sock); +} + +/* -------------------------------------------------------------------------- + * Minimal JSON parser for `wlr-randr --json` phone detection + * -------------------------------------------------------------------------- */ + +struct json_cursor { + const char *p; + const char *end; +}; + +static void json_skip_ws(struct json_cursor *c) +{ + while (c->p < c->end && + (*c->p == ' ' || *c->p == '\t' || *c->p == '\r' || *c->p == '\n')) + c->p++; +} + +static bool json_parse_string(struct json_cursor *c, char *out, size_t cap) +{ + json_skip_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; + char esc = *c->p++; + if (esc == 'u') { + if (c->end - c->p < 4) + return false; + c->p += 4; + ch = '?'; + } else { + ch = esc; + } + } + 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 json_parse_number(struct json_cursor *c, double *out) +{ + json_skip_ws(c); + if (c->p >= c->end) + return false; + const char *start = c->p; + if (*c->p == '-') + c->p++; + if (c->p >= c->end || !isdigit((unsigned char)*c->p)) + return false; + while (c->p < c->end && isdigit((unsigned char)*c->p)) + c->p++; + if (c->p < c->end && *c->p == '.') { + c->p++; + if (c->p >= c->end || !isdigit((unsigned char)*c->p)) + return false; + while (c->p < c->end && isdigit((unsigned char)*c->p)) + c->p++; + } + if (c->p < c->end && (*c->p == 'e' || *c->p == 'E')) { + c->p++; + if (c->p < c->end && (*c->p == '+' || *c->p == '-')) + c->p++; + if (c->p >= c->end || !isdigit((unsigned char)*c->p)) + return false; + while (c->p < c->end && isdigit((unsigned char)*c->p)) + c->p++; + } + if (out) { + char tmp[64]; + size_t len = (size_t)(c->p - start); + if (len >= sizeof(tmp)) + return false; + memcpy(tmp, start, len); + tmp[len] = '\0'; + *out = strtod(tmp, NULL); + } + return true; +} + +static bool json_skip_value(struct json_cursor *c, int depth); + +static bool json_skip_array(struct json_cursor *c, int depth) +{ + if (depth > 32 || c->p >= c->end || *c->p != '[') + return false; + c->p++; + json_skip_ws(c); + if (c->p < c->end && *c->p == ']') { + c->p++; + return true; + } + for (;;) { + if (!json_skip_value(c, depth + 1)) + return false; + json_skip_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 json_skip_object(struct json_cursor *c, int depth) +{ + if (depth > 32 || c->p >= c->end || *c->p != '{') + return false; + c->p++; + json_skip_ws(c); + if (c->p < c->end && *c->p == '}') { + c->p++; + return true; + } + for (;;) { + if (!json_parse_string(c, NULL, 0)) + return false; + json_skip_ws(c); + if (c->p >= c->end || *c->p != ':') + return false; + c->p++; + if (!json_skip_value(c, depth + 1)) + return false; + json_skip_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 json_skip_value(struct json_cursor *c, int depth) +{ + json_skip_ws(c); + if (c->p >= c->end) + return false; + if (*c->p == '"') + return json_parse_string(c, NULL, 0); + if (*c->p == '{') + return json_skip_object(c, depth); + if (*c->p == '[') + return json_skip_array(c, depth); + if (*c->p == '-' || isdigit((unsigned char)*c->p)) + return json_parse_number(c, NULL); + if (c->end - c->p >= 4 && memcmp(c->p, "true", 4) == 0) { + c->p += 4; + return true; + } + if (c->end - c->p >= 5 && memcmp(c->p, "false", 5) == 0) { + c->p += 5; + return true; + } + if (c->end - c->p >= 4 && memcmp(c->p, "null", 4) == 0) { + c->p += 4; + return true; + } + return false; +} + +static bool json_parse_bool(struct json_cursor *c, bool *out) +{ + json_skip_ws(c); + if (c->end - c->p >= 4 && memcmp(c->p, "true", 4) == 0) { + c->p += 4; + *out = true; + return true; + } + if (c->end - c->p >= 5 && memcmp(c->p, "false", 5) == 0) { + c->p += 5; + *out = false; + return true; + } + return false; +} + +static bool parse_modes_array(struct json_cursor *c, bool *found_current, + double *cur_w, double *cur_h) +{ + json_skip_ws(c); + if (c->p >= c->end || *c->p != '[') + return false; + c->p++; + json_skip_ws(c); + if (c->p < c->end && *c->p == ']') { + c->p++; + return true; + } + for (;;) { + json_skip_ws(c); + if (c->p >= c->end || *c->p != '{') + return false; + c->p++; + bool is_current = false; + bool has_w = false, has_h = false; + double w = 0.0, h = 0.0; + + json_skip_ws(c); + if (c->p < c->end && *c->p == '}') { + c->p++; + } else { + for (;;) { + char key[32]; + if (!json_parse_string(c, key, sizeof(key))) + return false; + json_skip_ws(c); + if (c->p >= c->end || *c->p != ':') + return false; + c->p++; + json_skip_ws(c); + if (strcmp(key, "current") == 0) { + if (!json_parse_bool(c, &is_current)) { + if (!json_skip_value(c, 2)) + return false; + } + } else if (strcmp(key, "width") == 0) { + if (json_parse_number(c, &w)) + has_w = true; + else if (!json_skip_value(c, 2)) + return false; + } else if (strcmp(key, "height") == 0) { + if (json_parse_number(c, &h)) + has_h = true; + else if (!json_skip_value(c, 2)) + return false; + } else { + if (!json_skip_value(c, 2)) + return false; + } + json_skip_ws(c); + if (c->p >= c->end) + return false; + if (*c->p == '}') { + c->p++; + break; + } + if (*c->p != ',') + return false; + c->p++; + } + } + + if (is_current && has_w && has_h && !*found_current) { + *found_current = true; + *cur_w = w; + *cur_h = h; + } + + json_skip_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 is_phone_json(const char *data, size_t len) +{ + struct json_cursor c = { data, data + len }; + json_skip_ws(&c); + if (c.p >= c.end || *c.p != '[') + return false; + c.p++; + json_skip_ws(&c); + if (c.p < c.end && *c.p == ']') + return false; + + for (;;) { + json_skip_ws(&c); + if (c.p >= c.end || *c.p != '{') + return false; + c.p++; + + bool enabled = false; + bool has_scale = false; + double scale = 1.0; + bool found_current = false; + double cur_w = 0.0, cur_h = 0.0; + + json_skip_ws(&c); + if (c.p < c.end && *c.p == '}') { + c.p++; + } else { + for (;;) { + char key[32]; + if (!json_parse_string(&c, key, sizeof(key))) + return false; + json_skip_ws(&c); + if (c.p >= c.end || *c.p != ':') + return false; + c.p++; + json_skip_ws(&c); + if (strcmp(key, "enabled") == 0) { + if (!json_parse_bool(&c, &enabled)) { + if (!json_skip_value(&c, 1)) + return false; + } + } else if (strcmp(key, "scale") == 0) { + if (json_parse_number(&c, &scale)) + has_scale = true; + else if (!json_skip_value(&c, 1)) + return false; + } else if (strcmp(key, "modes") == 0) { + if (!parse_modes_array(&c, &found_current, + &cur_w, &cur_h)) + return false; + } else { + if (!json_skip_value(&c, 1)) + return false; + } + json_skip_ws(&c); + if (c.p >= c.end) + return false; + if (*c.p == '}') { + c.p++; + break; + } + if (*c.p != ',') + return false; + c.p++; + } + } + + double effective_scale = (has_scale && scale != 0.0) ? scale : 1.0; + if (enabled && found_current && effective_scale > 0.0) { + double short_side = cur_w < cur_h ? cur_w : cur_h; + return (short_side / effective_scale) < 480.0; + } + + json_skip_ws(&c); + if (c.p >= c.end) + return false; + if (*c.p == ']') + return false; + if (*c.p != ',') + return false; + c.p++; + } +} + +static bool phone(void) +{ + int pipefd[2]; + if (pipe(pipefd) < 0) + return false; + + pid_t pid = fork(); + if (pid < 0) { + close(pipefd[0]); + close(pipefd[1]); + return false; + } + if (pid == 0) { + close(pipefd[0]); + dup2(pipefd[1], STDOUT_FILENO); + close(pipefd[1]); + int devnull = open("/dev/null", O_WRONLY); + if (devnull >= 0) { + dup2(devnull, STDERR_FILENO); + if (devnull > STDERR_FILENO) + close(devnull); + } + execlp("wlr-randr", "wlr-randr", "--json", (char *)NULL); + _exit(127); + } + + close(pipefd[1]); + int flags = fcntl(pipefd[0], F_GETFL, 0); + if (flags >= 0) + fcntl(pipefd[0], F_SETFL, flags | O_NONBLOCK); + + size_t cap = 16384; + size_t len = 0; + char *buf = malloc(cap); + if (!buf) { + close(pipefd[0]); + kill(pid, SIGKILL); + waitpid(pid, NULL, 0); + return false; + } + + double deadline = monotonic_now(NULL) + 5.0; + bool timed_out = false; + for (;;) { + double rem = deadline - monotonic_now(NULL); + 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; + } + for (;;) { + if (len + 4096 > cap) { + if (cap >= 1024 * 1024) { + timed_out = true; + break; + } + cap *= 2; + char *nb = realloc(buf, cap); + if (!nb) { + timed_out = true; + break; + } + buf = nb; + } + ssize_t n = read(pipefd[0], buf + len, cap - len); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) + break; + if (errno == EINTR) + continue; + goto done; + } + if (n == 0) + goto done; + len += (size_t)n; + } + if (timed_out) + break; + } + +done: + close(pipefd[0]); + if (timed_out) + kill(pid, SIGKILL); + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) + ; + + bool result = false; + if (!timed_out) + result = is_phone_json(buf, len); + free(buf); + return result; +} + +/* -------------------------------------------------------------------------- + * Theme colors.toml parser and keyboard exec + * -------------------------------------------------------------------------- */ + +struct theme_colors { + char background[8]; + char lighter_background[8]; + char selection[8]; + char accent[8]; + char foreground[8]; + char bright_foreground[8]; +}; + +static bool parse_hex_color(const char *val, char out[8]) +{ + if (strlen(val) != 7 || val[0] != '#') + return false; + memcpy(out, val + 1, 7); + return true; +} + +static bool load_colors(const char *path, struct theme_colors *c) +{ + memset(c, 0, sizeof(*c)); + FILE *f = fopen(path, "r"); + if (!f) { + perror(path); + return false; + } + char line[512]; + while (fgets(line, sizeof(line), f)) { + char *s = trim_whitespace(line); + if (*s == '\0' || *s == '#' || *s == '[') + continue; + char *eq = strchr(s, '='); + if (!eq) + continue; + *eq = '\0'; + char *key = trim_whitespace(s); + char *val = trim_whitespace(eq + 1); + if (*val != '"' && *val != '\'') + continue; + char quote = *val++; + char *end = strchr(val, quote); + if (!end) + continue; + *end = '\0'; + + if (strcmp(key, "background") == 0) + parse_hex_color(val, c->background); + else if (strcmp(key, "lighter_background") == 0) + parse_hex_color(val, c->lighter_background); + else if (strcmp(key, "selection") == 0) + parse_hex_color(val, c->selection); + else if (strcmp(key, "accent") == 0) + parse_hex_color(val, c->accent); + else if (strcmp(key, "foreground") == 0) + parse_hex_color(val, c->foreground); + else if (strcmp(key, "bright_foreground") == 0) + parse_hex_color(val, c->bright_foreground); + } + fclose(f); + + const char *missing = NULL; + if (!c->background[0]) + missing = "background"; + else if (!c->lighter_background[0]) + missing = "lighter_background"; + else if (!c->selection[0]) + missing = "selection"; + else if (!c->accent[0]) + missing = "accent"; + else if (!c->foreground[0]) + missing = "foreground"; + if (missing) { + fprintf(stderr, "Invalid Omarchy colour: %s\n", missing); + return false; + } + if (!c->bright_foreground[0]) + memcpy(c->bright_foreground, c->foreground, sizeof(c->bright_foreground)); + return true; +} + +static void run_keyboard(void) +{ + pid_t pid = live_pid(); + if (pid && pid != getpid()) { + fprintf(stderr, "Keyboard already running\n"); + exit(1); + } + + const char *home = getenv("HOME"); + if (!home || !*home) { + fprintf(stderr, "HOME is not set\n"); + exit(1); + } + char colors_path[PATH_MAX]; + snprintf(colors_path, sizeof(colors_path), + "%s/.local/state/omarchy/current/theme/colors.toml", home); + + struct theme_colors colors; + if (!load_colors(colors_path, &colors)) + exit(1); + + char *args[26]; + int argc = 0; + args[argc++] = g_binary; + args[argc++] = "--hidden"; + args[argc++] = "--no-popup"; + args[argc++] = "-H"; + args[argc++] = "270"; + args[argc++] = "-L"; + args[argc++] = "220"; + args[argc++] = "--bg"; + args[argc++] = colors.background; + args[argc++] = "--fg"; + args[argc++] = colors.lighter_background; + args[argc++] = "--fg-sp"; + args[argc++] = colors.selection; + args[argc++] = "--press"; + args[argc++] = colors.accent; + args[argc++] = "--press-sp"; + args[argc++] = colors.accent; + args[argc++] = "--text"; + args[argc++] = colors.foreground; + args[argc++] = "--text-sp"; + args[argc++] = colors.bright_foreground; + + /* Upright on a phone: ten keys across under a short row of terminal keys, + * and 123 and #+= for the rest (desktop/keyboard/friendly-layout.py). */ + if (phone()) { + args[argc++] = "-l"; + args[argc++] = "phone,phonenum,phonesym"; + } + args[argc] = NULL; + + if (!write_small_file(g_state_file, "0\n")) { + perror("write state_file"); + exit(1); + } + char pid_buf[32]; + snprintf(pid_buf, sizeof(pid_buf), "%ld\n", (long)getpid()); + if (!write_small_file(g_pid_file, pid_buf)) { + perror("write pid_file"); + exit(1); + } + setenv("WVKBD_STATE_FILE", g_state_file, 1); + + execv(g_binary, args); + perror(g_binary); + exit(127); +} + +/* -------------------------------------------------------------------------- + * Test harnesses (--test-policy, --test-phone) + * -------------------------------------------------------------------------- */ + +struct test_ctx { + double clock; + bool shown; +}; + +static void test_show(void *ctx) +{ + struct test_ctx *tc = ctx; + tc->shown = true; + printf("CALL show\n"); +} + +static void test_hide(void *ctx) +{ + struct test_ctx *tc = ctx; + tc->shown = false; + printf("CALL hide\n"); +} + +static bool test_visible(void *ctx) +{ + struct test_ctx *tc = ctx; + return tc->shown; +} + +static double test_now(void *ctx) +{ + struct test_ctx *tc = ctx; + return tc->clock; +} + +static int run_test_policy(void) +{ + struct test_ctx tc = { .clock = 100.0, .shown = false }; + struct policy pol; + policy_init(&pol, test_show, test_hide, test_visible, test_now, &tc); + + char line[1024]; + while (fgets(line, sizeof(line), stdin)) { + size_t len = strlen(line); + while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) + line[--len] = '\0'; + + if (strncmp(line, "clock ", 6) == 0) { + tc.clock = strtod(line + 6, NULL); + } else if (strncmp(line, "visible ", 8) == 0) { + tc.shown = atoi(line + 8) != 0; + } else if (strncmp(line, "fact ", 5) == 0) { + policy_fact(&pol, line + 5); + } else if (strcmp(line, "fact") == 0) { + policy_fact(&pol, ""); + } else if (strncmp(line, "person ", 7) == 0) { + policy_person(&pol, line + 7); + } else if (strcmp(line, "tick") == 0) { + policy_tick(&pol); + } else if (strcmp(line, "state") == 0) { + printf("STATE hardware=%d opened_here=%d\n", + pol.hardware ? 1 : 0, pol.opened_here ? 1 : 0); + } + printf("OK\n"); + fflush(stdout); + } + return 0; +} + +static int run_test_phone(void) +{ + size_t cap = 16384, len = 0; + char *buf = malloc(cap); + if (!buf) + return 1; + for (;;) { + if (len + 4096 > cap) { + cap *= 2; + char *nb = realloc(buf, cap); + if (!nb) { + free(buf); + return 1; + } + buf = nb; + } + size_t n = fread(buf + len, 1, cap - len, stdin); + len += n; + if (n == 0) + break; + } + bool result = is_phone_json(buf, len); + free(buf); + return result ? 0 : 1; +} + +int main(int argc, char **argv) +{ + if (argc > 0 && argv[0]) + g_argv0 = argv[0]; + init_paths(); + + const char *mode = argc > 1 ? argv[1] : "run"; + if (strcmp(mode, "--test-policy") == 0) + return run_test_policy(); + if (strcmp(mode, "--test-phone") == 0) + return run_test_phone(); + + if (strcmp(mode, "toggle") == 0) + mode = visible(NULL) ? "hide" : "show"; + + if (strcmp(mode, "show") == 0) { + show_keyboard(NULL); + tell_policy("show"); + } else if (strcmp(mode, "hide") == 0) { + hide_keyboard(NULL); + tell_policy("hide"); + } else if (strcmp(mode, "quiet") == 0 || + strcmp(mode, "hold") == 0 || + strcmp(mode, "release") == 0) { + tell_policy(mode); + } else if (strcmp(mode, "listen") == 0) { + listen_loop(); + } else if (strcmp(mode, "restart") == 0) { + pid_t pid = live_pid(); + if (pid) { + kill(pid, SIGTERM); + for (int i = 0; i < 40; i++) { + if (!live_pid()) + break; + sleep_ms(50); + } + if (live_pid()) { + fprintf(stderr, "Prior keyboard did not stop\n"); + return 1; + } + } + launch(); + } else if (strcmp(mode, "run") == 0) { + run_keyboard(); + } else { + fprintf(stderr, + "Usage: omarchy-keyboard [show|hide|toggle|quiet|hold|release|listen|restart|run]\n"); + return 1; + } + + return 0; +} diff --git a/desktop/install-tree b/desktop/install-tree index 74acb345..c51b1ca5 100755 --- a/desktop/install-tree +++ b/desktop/install-tree @@ -19,7 +19,7 @@ here=$(cd "$(dirname "$0")" && pwd) project=$(dirname "$here") shell=$here/shell config=$here/configuration omarchy=$root/usr/share/omarchy -for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/omarchy-powerctl" "$build/omarchy-mute-switch" "$build/omarchy-powerd" "$upstream/themes" "$upstream/bin" \ +for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/omarchy-keyboard" "$build/omarchy-powerctl" "$build/omarchy-mute-switch" "$build/omarchy-powerd" "$upstream/themes" "$upstream/bin" \ "$upstream/themes/jade-horse/colors.toml" "$upstream/icons/papercraft" "$upstream/applications/foot.desktop" "$upstream/default/hypr/toggles/bar-glassy.lua" \ "$upstream/default/i18n/en/cli.json" "$upstream/install/helpers/as-root.sh" "$upstream/install/helpers/browser-policy.sh" \ "$upstream/default/chromium/policies/omarchy.json" "$upstream/default/firefox/policies.json" "$upstream/config/chromium-flags.conf" \ @@ -107,9 +107,10 @@ for set in "$omarchy"/icons/*/; do if [[ -f $set/btop.svg.tpl && ! -e $set/omactivity.svg.tpl ]]; then ln -s btop.svg.tpl "$set/omactivity.svg.tpl"; fi done -# The keyboard, the startup cursor helper, the power daemon, and the -# power-control and hardware mute-switch helpers. +# The keyboard, its controller, the startup cursor helper, the power daemon, +# and the power-control and hardware mute-switch helpers. put "$build/wvkbd-mobintl" "$omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state" 755 +put "$build/omarchy-keyboard" "$omarchy/bin/omarchy-keyboard" 755 put "$build/wtype" "$root/usr/libexec/omarchy-wtype" 755 put "$build/wtype.LICENSE" "$root/usr/share/licenses/omarchy-wtype/LICENSE" put "$build/omarchy-powerd" "$root/usr/libexec/omarchy-powerd" 755 diff --git a/desktop/shell/bin/omarchy-keyboard b/desktop/shell/bin/omarchy-keyboard deleted file mode 100644 index 67ea0b1c..00000000 --- a/desktop/shell/bin/omarchy-keyboard +++ /dev/null @@ -1,340 +0,0 @@ -#!/usr/bin/env python3 -"""Session controller for the theme-matched Wayland keyboard, and its policy. - - omarchy-keyboard show|hide|toggle what the person asks for (swipe up, bar button) - omarchy-keyboard quiet the window opening next was not asked for by a tap - omarchy-keyboard hold|release a shell surface (the control center) is over the app - and has its keyboard: its field going off is no reason - omarchy-keyboard listen the policy: reads the compositor's facts on stdin - omarchy-keyboard restart|run (re)start the keyboard process itself - -When it opens or closes on its own is decided here and nowhere else. The -compositor only reports facts, one line each on `listen`'s standard input -(Labwc: , see its -input/osk.h): text fields going on and off, apps asking for the keyboard, -taps, keys typed on a physical keyboard, how many such keyboards there are. -""" -import os -from pathlib import Path -import selectors -import signal -import socket -import subprocess -import sys -import time - -root = Path(os.environ.get("OMARCHY_PATH", "/usr/share/omarchy")) -runtime = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) -binary = root / "trials/wvkbd-mobintl-v0.20-font18-special15-state" -pid_file = runtime / "omarchy-keyboard.pid" -state_file = runtime / "omarchy-keyboard-visible" -log_file = runtime / "omarchy-keyboard.log" -policy_socket = runtime / "omarchy-keyboard.sock" - - -def live_pid(): - try: - pid = int(pid_file.read_text().strip()) - return pid if Path(f"/proc/{pid}/exe").resolve() == binary.resolve() else None - except (OSError, ValueError): - return None - - -def visible(): - try: - return state_file.read_text().strip() == "1" - except OSError: - return False - - -def launch(): - with log_file.open("ab") as log: - subprocess.Popen([str(Path(__file__).resolve()), "run"], stdin=subprocess.DEVNULL, - stdout=log, stderr=log, start_new_session=True) - - -def wait_for_start(): - for _ in range(40): - if pid := live_pid(): - try: - status = Path(f"/proc/{pid}/status").read_text() - mask = int(next(line.split()[1] for line in status.splitlines() - if line.startswith("SigBlk:")), 16) - if mask & (1 << (signal.SIGUSR2 - 1)): - return pid - except (OSError, StopIteration, ValueError): - pass - time.sleep(0.05) - raise SystemExit("Keyboard did not start; see " + str(log_file)) - - -def show(): - if not (pid := live_pid()): - launch() - pid = wait_for_start() - os.kill(pid, signal.SIGUSR2) - - -def hide(): - if pid := live_pid(): - os.kill(pid, signal.SIGUSR1) - - -class Policy: - """When the keyboard opens and closes on its own. - - It opens when the person taps a text field, never because a program moved - focus, and never for a press that becomes a drag or a long press (selecting - text). Apps on text-input version 2 ask for it themselves (`show`), and are - heard right after a touch only: Qt asks whenever a field gets focus, also - one an app focuses on start. A request that comes just before its field - reports itself (a tap that turns a label into a field) is kept a moment. - Version 1 apps cannot ask: for them a tap counts when a field is on at the - end of it, or comes on right after it (a tap that focused a field, a tap in - a terminal, which has text input whenever it is focused; a tap that moved - focus off a field turns it off before the tap ends). - - It closes when the app asks, and shortly after no field is on any more, if - it opened on its own. One the person put away stays away until the next - tap on a field. - - Typing on a physical keyboard closes it and stops taps from opening it, - until the person opens it (swipe up, bar button) or no physical keyboard is - left. Being connected alone changes nothing. - """ - - TAP_MS = 350 # longer is a long press - TAP_PX = 12 # further is a drag - TOUCH_WINDOW = 0.6 # a touch to an app's request, a tap to a field coming on - SHOW_WAIT = 0.5 # a request to its field coming on - HIDE_DELAY = 0.25 # focus moving from one field to the next - - def __init__(self, show, hide, visible, now=time.monotonic): - self._show, self._hide, self._visible, self.now = show, hide, visible, now - self.field = 0 # the focused field's text-input version, 0 when none - self.touched_until = 0.0 # a press, or the release of a tap, just happened - self.tapped_until = 0.0 # a tap just ended - self.asked_until = 0.0 # an app asked before its field came on - self.hide_at = None - self.hide_asked = False # the app asked to hide; held back like a field going off - self.pressing = False # a finger is down on the focused surface - self.opened_here = False - self.hardware = False # typing on a physical keyboard - self.held = False # the control center is over the app (hold … release) - self.keyboards = 0 - - def _open(self): - self.touched_until = self.tapped_until = self.asked_until = 0.0 - self.hide_at, self.hide_asked = None, False - if self.hardware: - return - self.opened_here = True - if not self._visible(): # a field taking focus and the app asking are one tap - self._show() - - def _close(self): - self.hide_at, self.hide_asked = None, False - if self.opened_here: - self.opened_here = False - self._hide() - - def fact(self, line): - now = self.now() - words = line.split() - if words[:2] == ["field", "on"] and len(words) == 3 and words[2].isdigit(): - self.field, self.hide_at = int(words[2]), None - # A field that takes focus while the finger is down was tapped, - # whatever version: Qt does not ask again for a keyboard it - # thinks is still up, after one that closed on its own. - if now < self.asked_until or (self.pressing and now < self.touched_until) \ - or (self.field < 2 and now < self.tapped_until): - self._open() - elif words == ["field", "off"]: - self.field = 0 - if self.opened_here and not self.held: - self.hide_at = now + self.HIDE_DELAY - elif words == ["show"]: - # Asked for right after a touch: Qt asks only for a text item it - # focused, and may enable its text input only at the next input - # event (a field tapped again after focus went elsewhere), so the - # request is enough. The keyboard types through key presses. - if now < self.touched_until: - self._open() - elif words == ["hide"]: - # Held back a moment: an app that asks to hide and show again at - # once (to be heard after the person put the keyboard away) must - # not make an open keyboard blink. - if self.opened_here: - self.hide_at, self.hide_asked = now + self.HIDE_DELAY, True - elif words == ["press"]: - self.touched_until = now + self.TOUCH_WINDOW - self.pressing = True - elif words[:1] == ["release"] and len(words) == 3 and words[1].isdigit() and words[2].isdigit(): - self.pressing = False - if int(words[1]) <= self.TAP_MS and int(words[2]) <= self.TAP_PX: - self.touched_until = self.tapped_until = now + self.TOUCH_WINDOW - if 0 < self.field < 2: - self._open() - else: - self.touched_until = self.tapped_until = 0.0 - elif words == ["key"]: - if self.keyboards > 0: - self.hardware = True - self.touched_until = self.tapped_until = self.asked_until = 0.0 - self.opened_here = False - if self._visible(): - self._hide() - elif words[:1] == ["keyboards"] and len(words) == 2 and words[1].isdigit(): - self.keyboards = int(words[1]) - if self.keyboards == 0: - self.hardware = False - - def person(self, action): - """The person opened or closed it (swipe up, bar button).""" - if action == "hold": - # The control center opens over the app and takes the keyboard: - # the app's field goes off, and the keyboard stays, under it. - self.held, self.hide_at, self.hide_asked = True, None, False - return - if action == "release": - # Closed again: the keyboard goes only if no field came back. - self.held = False - if self.opened_here and not self.field: - self.hide_at = self.now() + self.HIDE_DELAY - return - if action == "quiet": - # A launcher opening a window to read, not to type in (About's - # terminal): the tap that started it does not count for the field - # its window brings. A tap in the window still opens the keyboard. - self.touched_until = self.tapped_until = self.asked_until = 0.0 - return - self.opened_here = False - self.hide_at = None - if action == "show": - self.hardware = False - - def deadline(self): - return self.hide_at - - def tick(self): - if self.hide_at is not None and self.now() >= self.hide_at: - if self.hide_asked or not self.field: - self._close() - self.hide_at, self.hide_asked = None, False - - -def tell_policy(action): - """Lets a running policy know what the person did; nothing when none runs.""" - try: - with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as s: - s.sendto(action.encode(), str(policy_socket)) - except OSError: - pass - - -def listen(): - policy = Policy(show, hide, visible) - try: - policy_socket.unlink() - except FileNotFoundError: - pass - person = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) - person.bind(str(policy_socket)) - os.set_blocking(sys.stdin.fileno(), False) - events = selectors.DefaultSelector() - events.register(sys.stdin.buffer, selectors.EVENT_READ, "facts") - events.register(person, selectors.EVENT_READ, "person") - pending = b"" - while True: - deadline = policy.deadline() - timeout = None if deadline is None else max(0.0, deadline - policy.now()) - for key, _ in events.select(timeout): - if key.data == "person": - policy.person(person.recv(64).decode(errors="replace").strip()) - continue - chunk = os.read(sys.stdin.fileno(), 4096) - if not chunk: - return # the compositor went away - pending += chunk - while b"\n" in pending: - line, pending = pending.split(b"\n", 1) - try: - policy.fact(line.decode(errors="replace")) - except Exception as error: # a bad line must not end the session's keyboard - print("omarchy-keyboard: " + repr(error), file=sys.stderr) - policy.tick() - - -def phone(): - """A phone: the screen's short side under 480 logical pixels, the width - under which the shell lays itself out as on a phone too.""" - import json - try: - outputs = json.loads(subprocess.run(["wlr-randr", "--json"], capture_output=True, - text=True, timeout=5).stdout) - except (OSError, ValueError, subprocess.SubprocessError): - return False - for output in outputs: - mode = next((m for m in output.get("modes", []) if m.get("current")), None) - scale = output.get("scale") or 1 - if output.get("enabled") and mode and scale > 0: - return min(mode["width"], mode["height"]) / scale < 480 - return False - - -def run(): - import tomllib - if (pid := live_pid()) and pid != os.getpid(): - raise SystemExit("Keyboard already running") - colors = tomllib.loads((Path.home() / ".local/state/omarchy/current/theme/colors.toml").read_text()) - def color(key, fallback=None): - value = colors.get(key, colors.get(fallback, "")) - if not isinstance(value, str) or len(value) != 7 or not value.startswith("#"): - raise ValueError("Invalid Omarchy colour: " + key) - return value[1:] - args = [str(binary), "--hidden", "--no-popup", "-H", "270", "-L", "220", - "--bg", color("background"), "--fg", color("lighter_background"), - "--fg-sp", color("selection"), "--press", color("accent"), - "--press-sp", color("accent"), "--text", color("foreground"), - "--text-sp", color("bright_foreground", "foreground")] - # Upright on a phone: ten keys across under a short row of terminal keys, - # and 123 and #+= for the rest (desktop/keyboard/friendly-layout.py). - if phone(): - args += ["-l", "phone,phonenum,phonesym"] - state_file.write_text("0\n") - pid_file.write_text(str(os.getpid()) + "\n") - os.environ["WVKBD_STATE_FILE"] = str(state_file) - os.execv(str(binary), args) - - -def main(mode): - if mode == "toggle": - mode = "hide" if visible() else "show" - if mode == "show": - show() - tell_policy("show") - elif mode == "hide": - hide() - tell_policy("hide") - elif mode in ("quiet", "hold", "release"): - tell_policy(mode) - elif mode == "listen": - listen() - elif mode == "restart": - if pid := live_pid(): - os.kill(pid, signal.SIGTERM) - for _ in range(40): - if not live_pid(): - break - time.sleep(0.05) - if live_pid(): - raise SystemExit("Prior keyboard did not stop") - launch() - elif mode == "run": - run() - else: - raise SystemExit("Usage: omarchy-keyboard [show|hide|toggle|quiet|hold|release|listen|restart|run]") - - -if __name__ == "__main__": - main(sys.argv[1] if len(sys.argv) > 1 else "run") diff --git a/release/audit.py b/release/audit.py index cac6a617..9c963ef1 100644 --- a/release/audit.py +++ b/release/audit.py @@ -20,6 +20,7 @@ 'usr/libexec/omarchy-powerd': 'power, lock and sleep daemon', 'usr/libexec/omarchy-mute-switch': 'mute switch helper', 'usr/libexec/omarchy-powerctl': 'power control client', + 'usr/share/omarchy/bin/omarchy-keyboard': 'on-screen keyboard controller', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state': 'on-screen keyboard'} def private_firmware(orchard=None): diff --git a/tests/package_tree.py b/tests/package_tree.py index 07ef50a7..96b1b307 100644 --- a/tests/package_tree.py +++ b/tests/package_tree.py @@ -32,7 +32,7 @@ def inputs(base): """BUILD, OMARCHY and DBUS_NEXT for install-tree, under BASE.""" build, upstream, wheel = base / 'build', base / 'omarchy', base / 'wheel' build.mkdir() - for name in ('wvkbd-mobintl', 'wtype', 'omarchy-powerd', 'omarchy-mute-switch', 'omarchy-powerctl'): + for name in ('wvkbd-mobintl', 'wtype', 'omarchy-powerd', 'omarchy-mute-switch', 'omarchy-powerctl', 'omarchy-keyboard'): (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_keyboard_policy.py b/tests/test_keyboard_policy.py index f8a6fbaa..05330d44 100644 --- a/tests/test_keyboard_policy.py +++ b/tests/test_keyboard_policy.py @@ -1,21 +1,40 @@ -from importlib.machinery import SourceFileLoader -from importlib.util import module_from_spec, spec_from_loader +import atexit +import functools +import json +import os from pathlib import Path +import shutil +import subprocess +import sys +import tempfile import unittest PROJECT = Path(__file__).resolve().parents[1] -SCRIPT = PROJECT / 'desktop/shell/bin/omarchy-keyboard' +SOURCE = PROJECT / 'desktop/configuration/keyboard.c' TAP = 'release 80 2' DRAG = 'release 600 140' LONG_PRESS = 'release 900 3' -def load(): - loader = SourceFileLoader('omarchy_keyboard', str(SCRIPT)) - module = module_from_spec(spec_from_loader('omarchy_keyboard', loader)) - loader.exec_module(module) - return module +@functools.lru_cache(maxsize=1) +def compiled_binary(): + tmp = Path(tempfile.mkdtemp(prefix='omarchy-keyboard-test-')) + atexit.register(shutil.rmtree, tmp, True) + binary = tmp / 'omarchy-keyboard' + cc = os.environ.get('CC', 'cc') + subprocess.run( + [cc, '-O2', '-Wall', '-Wextra', '-Werror', '-std=c99', str(SOURCE), '-o', str(binary)], + check=True, + ) + return binary + + +def setUpModule(): + # keyboard.c uses Linux socket flags (SOCK_NONBLOCK, SOCK_CLOEXEC) that + # macOS lacks, so the binary is tested on Linux only. + if not sys.platform.startswith('linux'): + raise unittest.SkipTest('keyboard.c needs Linux headers') class Clock: @@ -26,6 +45,70 @@ def __call__(self): return self.t +class CPolicy: + def __init__(self, test): + self._test = test + self._proc = subprocess.Popen( + [str(compiled_binary()), '--test-policy'], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + text=True, + ) + + def _send(self, line): + self._proc.stdin.write(line + '\n') + self._proc.stdin.flush() + out = [] + while True: + reply = self._proc.stdout.readline() + if not reply: + raise AssertionError('omarchy-keyboard --test-policy exited unexpectedly') + reply = reply.rstrip('\n') + if reply == 'OK': + return out + if reply == 'CALL show': + self._test.shown = True + self._test.calls.append('show') + elif reply == 'CALL hide': + self._test.shown = False + self._test.calls.append('hide') + else: + out.append(reply) + + def _sync(self): + self._send(f'clock {self._test.clock.t:.9f}') + self._send(f'visible {1 if self._test.shown else 0}') + + def fact(self, line): + self._sync() + self._send('fact ' + line if line else 'fact') + + def person(self, action): + self._sync() + self._send('person ' + action) + + def tick(self): + self._sync() + self._send('tick') + + @property + def hardware(self): + lines = self._send('state') + for line in lines: + if line.startswith('STATE '): + for part in line.split()[1:]: + if part.startswith('hardware='): + return part.split('=', 1)[1] == '1' + raise AssertionError(f'Missing STATE line: {lines!r}') + + def close(self): + if self._proc.stdin: + self._proc.stdin.close() + if self._proc.stdout: + self._proc.stdout.close() + self._proc.wait(timeout=5) + + class KeyboardPolicyTests(unittest.TestCase): """When the on-screen keyboard opens and closes on its own (omarchy-keyboard listen).""" @@ -33,16 +116,10 @@ def setUp(self): self.clock = Clock() self.shown = False self.calls = [] + self.policy = CPolicy(self) - def show(): - self.shown = True - self.calls.append('show') - - def hide(): - self.shown = False - self.calls.append('hide') - - self.policy = load().Policy(show, hide, lambda: self.shown, now=self.clock) + def tearDown(self): + self.policy.close() def facts(self, *lines): for line in lines: @@ -271,15 +348,16 @@ class PhoneLayoutTests(unittest.TestCase): """A phone-width screen starts the keyboard with the phone layers.""" def phone(self, width, height, scale): - module = load() - import json - import subprocess output = [{'name': 'DSI-1', 'enabled': True, 'scale': scale, 'modes': [{'width': width, 'height': height, 'current': True}]}] - from unittest import mock - result = subprocess.CompletedProcess([], 0, stdout=json.dumps(output)) - with mock.patch.object(module.subprocess, 'run', return_value=result): - return module.phone() + result = subprocess.run( + [str(compiled_binary()), '--test-phone'], + input=json.dumps(output), + text=True, + capture_output=True, + timeout=5, + ) + return result.returncode == 0 def test_phone_width_screens_are_phones(self): self.assertTrue(self.phone(640, 1136, 2)) # iPod touch 6 @@ -292,7 +370,104 @@ def test_the_layers_exist_in_the_layout(self): layout = (PROJECT / 'desktop/keyboard/wvkbd-0.20-layout.patch').read_text() for name in ('phone', 'phonenum', 'phonesym'): self.assertIn('"latin", "%s"' % name, layout) - self.assertIn('"-l", "phone,phonenum,phonesym"', SCRIPT.read_text()) + source = SOURCE.read_text() + self.assertIn('"-l"', source) + self.assertIn('"phone,phonenum,phonesym"', source) + + +class ControllerIntegrationTests(unittest.TestCase): + """End-to-end checks for colors.toml parsing, wvkbd exec, and listen IPC.""" + + def test_run_parses_colors_and_execs_wvkbd(self): + with tempfile.TemporaryDirectory() as tmp: + tmp_path = Path(tmp) + home = tmp_path / 'home' + runtime = tmp_path / 'runtime' + omarchy = tmp_path / 'omarchy' + runtime.mkdir() + theme_dir = home / '.local/state/omarchy/current/theme' + theme_dir.mkdir(parents=True) + (theme_dir / 'colors.toml').write_text( + 'background = "#112233"\n' + 'lighter_background = "#223344"\n' + 'selection = "#334455"\n' + 'accent = "#445566"\n' + 'foreground = "#aabbcc"\n' + ) + fake_wvkbd = omarchy / 'trials/wvkbd-mobintl-v0.20-font18-special15-state' + fake_wvkbd.parent.mkdir(parents=True) + out_file = tmp_path / 'args.txt' + fake_wvkbd.write_text( + '#!/bin/sh\n' + f'printf "%s\\n" "$WVKBD_STATE_FILE" "$@" > "{out_file}"\n' + ) + fake_wvkbd.chmod(0o755) + env = { + 'PATH': os.environ.get('PATH', '/usr/bin:/bin'), + 'HOME': str(home), + 'XDG_RUNTIME_DIR': str(runtime), + 'OMARCHY_PATH': str(omarchy), + } + result = subprocess.run( + [str(compiled_binary()), 'run'], + env=env, + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + lines = out_file.read_text().splitlines() + self.assertEqual(lines[0], str(runtime / 'omarchy-keyboard-visible')) + args = lines[1:] + self.assertEqual(args[:6], ['--hidden', '--no-popup', '-H', '270', '-L', '220']) + pairs = dict(zip(args[6::2], args[7::2])) + self.assertEqual(pairs['--bg'], '112233') + self.assertEqual(pairs['--fg'], '223344') + self.assertEqual(pairs['--fg-sp'], '334455') + self.assertEqual(pairs['--press'], '445566') + self.assertEqual(pairs['--press-sp'], '445566') + self.assertEqual(pairs['--text'], 'aabbcc') + self.assertEqual(pairs['--text-sp'], 'aabbcc') # fallback to foreground + self.assertEqual((runtime / 'omarchy-keyboard-visible').read_text().strip(), '0') + self.assertTrue((runtime / 'omarchy-keyboard.pid').read_text().strip().isdigit()) + + def test_listen_handles_ipc_and_exits_on_stdin_eof(self): + import time + with tempfile.TemporaryDirectory() as tmp: + runtime = Path(tmp) + env = { + 'PATH': os.environ.get('PATH', '/usr/bin:/bin'), + 'XDG_RUNTIME_DIR': str(runtime), + 'OMARCHY_PATH': str(runtime), + } + proc = subprocess.Popen( + [str(compiled_binary()), 'listen'], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + ) + try: + sock_path = runtime / 'omarchy-keyboard.sock' + for _ in range(50): + if sock_path.exists(): + break + time.sleep(0.02) + self.assertTrue(sock_path.exists()) + for cmd in ('quiet', 'hold', 'release'): + res = subprocess.run([str(compiled_binary()), cmd], env=env, timeout=5) + self.assertEqual(res.returncode, 0) + proc.stdin.write(b'press\nrelease 80 2\n') + proc.stdin.flush() + proc.stdin.close() + self.assertEqual(proc.wait(timeout=5), 0) + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + for stream in (proc.stdin, proc.stdout, proc.stderr): + if stream and not stream.closed: + stream.close() if __name__ == '__main__': diff --git a/tests/test_keyboard_shortcuts.py b/tests/test_keyboard_shortcuts.py index 103102b5..09947898 100644 --- a/tests/test_keyboard_shortcuts.py +++ b/tests/test_keyboard_shortcuts.py @@ -67,7 +67,7 @@ def test_overview_triggers(self): changed = (PROJECT / 'desktop/shell/bin/omarchy-overview-changed').read_text() self.assertIn('omarchy.dock closeApps', changed) self.assertIn('omarchy-keyboard hide', changed) - self.assertIn('mode == "hide"', (PROJECT / 'desktop/shell/bin/omarchy-keyboard').read_text()) + self.assertIn('strcmp(mode, "hide") == 0', (PROJECT / 'desktop/configuration/keyboard.c').read_text()) home = (PROJECT / 'desktop/shell/bin/omarchy-home-button').read_text() self.assertIn('labwc --overview', home) # One press waits for a second before the drawer opens: two presses diff --git a/tests/test_package.py b/tests/test_package.py index b19baef3..f2efe75d 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -379,6 +379,7 @@ def test_the_compiled_helpers_are_of_the_roots_architecture(self): 'usr/libexec/omarchy-powerd', 'usr/libexec/omarchy-mute-switch', 'usr/libexec/omarchy-powerctl', + 'usr/share/omarchy/bin/omarchy-keyboard', 'usr/share/omarchy/trials/wvkbd-mobintl-v0.20-font18-special15-state'}) from release.architecture import check_elf check_elf(elf('aarch64'), 'aarch64')