diff --git a/Makefile b/Makefile index 9d655955..591ab21a 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ CC ?= cc CFLAGS ?= -O2 PKG_CONFIG ?= pkg-config -all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd $(BUILD)/omarchy-mute-switch $(BUILD)/omarchy-powerctl $(BUILD)/omarchy-keyboard $(BUILD)/arch-ipad-rotate-output $(BUILD)/arch-ipad-auto-brightness +all: $(BUILD)/wvkbd-mobintl $(BUILD)/wtype $(BUILD)/omarchy-powerd $(BUILD)/omarchy-mute-switch $(BUILD)/omarchy-powerctl $(BUILD)/omarchy-keyboard $(BUILD)/arch-ipad-rotate-output $(BUILD)/arch-ipad-auto-brightness $(BUILD)/omarchy-desktop-ready $(BUILD)/omarchy-rotation-lock $(BUILD)/omarchy-launcher-recent-files $(BUILD)/omarchy-render-labwc-theme $(BUILD)/omarchy-render-labwc-buttons $(BUILD)/omarchy-powerd: desktop/configuration/powerd.c mkdir -p $(BUILD) @@ -44,6 +44,26 @@ $(BUILD)/arch-ipad-auto-brightness: desktop/configuration/auto-brightness.c mkdir -p $(BUILD) $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 $< $(LDFLAGS) -lm -o $@ +$(BUILD)/omarchy-desktop-ready: desktop/configuration/desktop-ready.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 $< $(LDFLAGS) -o $@ + +$(BUILD)/omarchy-rotation-lock: desktop/configuration/rotation-lock.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 $< $(LDFLAGS) -o $@ + +$(BUILD)/omarchy-launcher-recent-files: desktop/configuration/launcher-recent-files.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 $< $(LDFLAGS) -o $@ + +$(BUILD)/omarchy-render-labwc-theme: desktop/configuration/render-labwc-theme.c + mkdir -p $(BUILD) + $(CC) $(CPPFLAGS) $(CFLAGS) -Wall -Wextra -Werror -std=c99 $< $(LDFLAGS) -o $@ + +$(BUILD)/omarchy-render-labwc-buttons: desktop/configuration/render-labwc-buttons.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/desktop-ready.c b/desktop/configuration/desktop-ready.c new file mode 100644 index 00000000..0a63d813 --- /dev/null +++ b/desktop/configuration/desktop-ready.c @@ -0,0 +1,120 @@ +/* + * omarchy-desktop-ready: record Wayland session readiness for the installer + * and desktop session. + * + * Without an argument, writes $XDG_RUNTIME_DIR/omarchy-desktop-ready.json. + * With "pin-screen", writes /run/omarchy-session/ready.json. + * + * Build: cc -O2 -Wall -Wextra -Werror -std=c99 desktop-ready.c -o omarchy-desktop-ready + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void die(const char *msg) +{ + fprintf(stderr, "%s\n", msg); + exit(1); +} + +static void write_json_str(FILE *fp, const char *s) +{ + fputc('"', fp); + for (; *s; s++) { + unsigned char c = (unsigned char)*s; + + if (c == '"' || c == '\\') { + fputc('\\', fp); + fputc(c, fp); + } else if (c < 0x20) { + fprintf(fp, "\\u%04x", c); + } else { + fputc(c, fp); + } + } + fputc('"', fp); +} + +int main(int argc, char **argv) +{ + struct passwd *pw; + bool pin_screen = false; + const char *xdg_runtime, *wayland_display, *target, *name; + char sock_path[PATH_MAX], tmp_path[PATH_MAX], final_path[PATH_MAX]; + char boot_id[128]; + struct stat st_sock, st_target; + FILE *fp; + size_t n; + int fd; + + pw = getpwuid(getuid()); + if (!pw || strcmp(pw->pw_name, "tablet") != 0) + die("Readiness comes from the tablet session"); + + if (argc == 2 && strcmp(argv[1], "pin-screen") == 0) + pin_screen = true; + else if (argc != 1) + die("Usage: omarchy-desktop-ready [pin-screen]"); + + xdg_runtime = getenv("XDG_RUNTIME_DIR"); + wayland_display = getenv("WAYLAND_DISPLAY"); + if (!xdg_runtime || !*xdg_runtime || !wayland_display || !*wayland_display) + die("No owned Wayland session"); + + target = pin_screen ? "/run/omarchy-session" : xdg_runtime; + if (snprintf(sock_path, sizeof(sock_path), "%s/%s", + xdg_runtime, wayland_display) >= (int)sizeof(sock_path)) + die("No owned Wayland session"); + + if (stat(sock_path, &st_sock) != 0 || !S_ISSOCK(st_sock.st_mode) || + stat(target, &st_target) != 0 || st_target.st_uid != getuid()) + die("No owned Wayland session"); + + fp = fopen("/proc/sys/kernel/random/boot_id", "r"); + if (!fp) + die("Failed to read boot_id"); + n = fread(boot_id, 1, sizeof(boot_id) - 1, fp); + fclose(fp); + boot_id[n] = '\0'; + while (n > 0 && (boot_id[n - 1] == '\n' || boot_id[n - 1] == '\r' || + boot_id[n - 1] == ' ' || boot_id[n - 1] == '\t')) + boot_id[--n] = '\0'; + + name = pin_screen ? "ready.json" : "omarchy-desktop-ready.json"; + if (snprintf(tmp_path, sizeof(tmp_path), "%s/%s.pending", + target, name) >= (int)sizeof(tmp_path) || + snprintf(final_path, sizeof(final_path), "%s/%s", + target, name) >= (int)sizeof(final_path)) + die("Path too long"); + + fd = open(tmp_path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) + die(strerror(errno)); + fp = fdopen(fd, "w"); + if (!fp) { + close(fd); + die(strerror(errno)); + } + + fputs("{\"boot_id\": ", fp); + write_json_str(fp, boot_id); + fprintf(fp, ", \"shell_pid\": %ld, \"wayland_socket\": ", (long)getppid()); + write_json_str(fp, sock_path); + fputs("}", fp); + + if (fflush(fp) != 0 || fchmod(fd, 0644) != 0 || fclose(fp) != 0) + die(strerror(errno)); + if (rename(tmp_path, final_path) != 0) + die(strerror(errno)); + + return 0; +} diff --git a/desktop/configuration/first-theme b/desktop/configuration/first-theme index f5ee99d7..559936b9 100644 --- a/desktop/configuration/first-theme +++ b/desktop/configuration/first-theme @@ -19,8 +19,8 @@ if [[ ! -s "$state/theme.name" ]]; then background=$(find "$state/theme/backgrounds" -maxdepth 1 -type f -name '*.webp' -printf '%f\n' | sort | head -n1) [[ -n "$background" ]] || exit 1 ln -s "$state/theme/backgrounds/$background" "$state/background" - python3 "$OMARCHY_PATH/render-labwc-theme.py" "$state/theme/colors.toml" "$state/theme/shell.toml" > "$HOME/.local/share/themes/Omarchy-Current/labwc/themerc" - python3 "$OMARCHY_PATH/render-labwc-buttons.py" "$state/theme/colors.toml" "$HOME/.local/share/themes/Omarchy-Current/labwc" + /usr/libexec/omarchy-render-labwc-theme "$state/theme/colors.toml" "$state/theme/shell.toml" > "$HOME/.local/share/themes/Omarchy-Current/labwc/themerc" + /usr/libexec/omarchy-render-labwc-buttons "$state/theme/colors.toml" "$HOME/.local/share/themes/Omarchy-Current/labwc" fi [[ -s "$state/theme/colors.toml" && -s "$state/theme/shell.toml" && -e "$state/background" ]] || exit 1 # Render the KDE palette for installations initialized before this template. diff --git a/desktop/configuration/launcher-recent-files.c b/desktop/configuration/launcher-recent-files.c new file mode 100644 index 00000000..b5a4cf16 --- /dev/null +++ b/desktop/configuration/launcher-recent-files.c @@ -0,0 +1,485 @@ +/* + * omarchy-launcher-recent-files: list recently used files from GTK's + * recently-used.xbel, newest first, with the default app from xdg-mime, as JSON. + * + * Usage: omarchy-launcher-recent-files [count] + * + * Build: cc -O2 -Wall -Wextra -Werror -std=c99 launcher-recent-files.c -o omarchy-launcher-recent-files + */ +#define _DEFAULT_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct recent_row { + char *path; + char *mime; + double timestamp; +}; + +struct mime_cache_entry { + char *mime; + char *app; +}; + +static char *xstrdup(const char *s) +{ + size_t n = strlen(s) + 1; + char *p = malloc(n); + + if (p) + memcpy(p, s, n); + return p; +} + +static char *read_file_all(const char *path) +{ + FILE *fp = fopen(path, "rb"); + char *buf; + long sz; + size_t n; + + if (!fp) + return NULL; + if (fseek(fp, 0, SEEK_END) != 0 || (sz = ftell(fp)) < 0 || fseek(fp, 0, SEEK_SET) != 0) { + fclose(fp); + return NULL; + } + if (sz > 16 * 1024 * 1024) { + fclose(fp); + return NULL; + } + buf = malloc((size_t)sz + 1); + if (!buf) { + fclose(fp); + return NULL; + } + n = fread(buf, 1, (size_t)sz, fp); + fclose(fp); + buf[n] = '\0'; + return buf; +} + +/* Parse ISO-8601 timestamp (e.g. 2026-12-06T15:00:00Z or with .frac / +HH:MM) */ +static double parse_iso8601(const char *s) +{ + int y, mon, d, h, m, sec; + struct tm tm; + const char *p; + double frac = 0.0; + int tz_off = 0; + time_t t; + + if (!s || !*s) + return 0.0; + if (sscanf(s, "%d-%d-%dT%d:%d:%d", &y, &mon, &d, &h, &m, &sec) != 6) + return 0.0; + memset(&tm, 0, sizeof(tm)); + tm.tm_year = y - 1900; + tm.tm_mon = mon - 1; + tm.tm_mday = d; + tm.tm_hour = h; + tm.tm_min = m; + tm.tm_sec = sec; + + p = strchr(s, 'T'); + if (!p) + return 0.0; + p++; + while (*p && *p != '.' && *p != 'Z' && *p != '+' && *p != '-') + p++; + if (*p == '.') { + double scale = 0.1; + + p++; + while (isdigit((unsigned char)*p)) { + frac += (*p - '0') * scale; + scale *= 0.1; + p++; + } + } + if (*p == '+' || *p == '-') { + int sign = (*p == '-') ? -1 : 1; + int tzh = 0, tzm = 0; + + if (sscanf(p + 1, "%2d:%2d", &tzh, &tzm) >= 1) + tz_off = sign * (tzh * 3600 + tzm * 60); + } + + t = timegm(&tm); + if (t == (time_t)-1) + return 0.0; + return (double)t - (double)tz_off + frac; +} + +static int hex_val(char c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return 10 + (c - 'a'); + if (c >= 'A' && c <= 'F') + return 10 + (c - 'A'); + return -1; +} + +/* Decode XML entities in-place */ +static void xml_unescape(char *s) +{ + char *r = s, *w = s; + + while (*r) { + if (*r == '&') { + if (strncmp(r, "&", 5) == 0) { + *w++ = '&'; + r += 5; + } else if (strncmp(r, "<", 4) == 0) { + *w++ = '<'; + r += 4; + } else if (strncmp(r, ">", 4) == 0) { + *w++ = '>'; + r += 4; + } else if (strncmp(r, """, 6) == 0) { + *w++ = '"'; + r += 6; + } else if (strncmp(r, "'", 6) == 0) { + *w++ = '\''; + r += 6; + } else if (r[1] == '#') { + char *semi = strchr(r, ';'); + + if (semi && semi - r < 12) { + unsigned long v = (r[2] == 'x' || r[2] == 'X') ? + strtoul(r + 3, NULL, 16) : strtoul(r + 2, NULL, 10); + if (v > 0 && v < 128) + *w++ = (char)v; + r = semi + 1; + } else { + *w++ = *r++; + } + } else { + *w++ = *r++; + } + } else { + *w++ = *r++; + } + } + *w = '\0'; +} + +/* Percent-decode URL path in-place */ +static void url_unquote(char *s) +{ + char *r = s, *w = s; + + while (*r) { + if (*r == '%' && r[1] && r[2]) { + int hi = hex_val(r[1]); + int lo = hex_val(r[2]); + + if (hi >= 0 && lo >= 0) { + *w++ = (char)((hi << 4) | lo); + r += 3; + continue; + } + } + *w++ = *r++; + } + *w = '\0'; +} + +/* Extract attribute value from an XML tag [tag_start, tag_end) */ +static bool get_xml_attr(const char *tag_start, const char *tag_end, + const char *attr, char *out, size_t out_sz) +{ + size_t alen = strlen(attr); + const char *p = tag_start; + + while (p < tag_end) { + while (p < tag_end && !isspace((unsigned char)*p)) + p++; + while (p < tag_end && isspace((unsigned char)*p)) + p++; + if (p + alen + 1 < tag_end && strncmp(p, attr, alen) == 0 && p[alen] == '=') { + const char *v = p + alen + 1; + char q = *v++; + const char *end; + size_t len; + + if (q != '"' && q != '\'') + continue; + end = memchr(v, q, (size_t)(tag_end - v)); + if (!end) + return false; + len = (size_t)(end - v); + if (len >= out_sz) + len = out_sz - 1; + memcpy(out, v, len); + out[len] = '\0'; + xml_unescape(out); + return true; + } + } + return false; +} + +static int cmp_rows_desc(const void *a, const void *b) +{ + const struct recent_row *ra = a; + const struct recent_row *rb = b; + + if (rb->timestamp > ra->timestamp) + return 1; + if (rb->timestamp < ra->timestamp) + return -1; + return 0; +} + +static const char *query_default_app(const char *mime, + struct mime_cache_entry **cache, + size_t *cache_len) +{ + int pfd[2]; + pid_t pid; + char buf[256]; + ssize_t n; + size_t i, total = 0; + struct mime_cache_entry *grown; + + if (!mime || !*mime) + return ""; + + for (i = 0; i < *cache_len; i++) { + if (strcmp((*cache)[i].mime, mime) == 0) + return (*cache)[i].app; + } + + buf[0] = '\0'; + if (pipe(pfd) == 0) { + pid = fork(); + if (pid == 0) { + close(pfd[0]); + dup2(pfd[1], STDOUT_FILENO); + close(pfd[1]); + execlp("xdg-mime", "xdg-mime", "query", "default", mime, (char *)NULL); + _exit(127); + } + close(pfd[1]); + if (pid > 0) { + while (total < sizeof(buf) - 1 && + (n = read(pfd[0], buf + total, sizeof(buf) - 1 - total)) > 0) + total += (size_t)n; + buf[total] = '\0'; + waitpid(pid, NULL, 0); + } + close(pfd[0]); + } + while (total > 0 && isspace((unsigned char)buf[total - 1])) + buf[--total] = '\0'; + + grown = realloc(*cache, (*cache_len + 1) * sizeof(*grown)); + if (!grown) + return ""; + *cache = grown; + (*cache)[*cache_len].mime = xstrdup(mime); + (*cache)[*cache_len].app = xstrdup(buf); + (*cache_len)++; + return (*cache)[*cache_len - 1].app; +} + +static void print_json_str(const char *s) +{ + putchar('"'); + for (; *s; s++) { + unsigned char c = (unsigned char)*s; + + if (c == '"' || c == '\\') { + putchar('\\'); + putchar(c); + } else if (c == '\n') { + fputs("\\n", stdout); + } else if (c == '\r') { + fputs("\\r", stdout); + } else if (c == '\t') { + fputs("\\t", stdout); + } else if (c < 0x20) { + printf("\\u%04x", c); + } else { + putchar(c); + } + } + putchar('"'); +} + +int main(int argc, char **argv) +{ + long count = (argc > 1) ? strtol(argv[1], NULL, 10) : 8; + const char *xdg_data = getenv("XDG_DATA_HOME"); + const char *home = getenv("HOME"); + char xbel_path[PATH_MAX]; + char *xml, *p; + struct recent_row *rows = NULL; + size_t n_rows = 0, cap_rows = 0, i, limit; + struct mime_cache_entry *cache = NULL; + size_t cache_len = 0; + + if (count < 0) + count = 0; + if (!home) + home = ""; + + if (xdg_data && *xdg_data) + snprintf(xbel_path, sizeof(xbel_path), "%s/recently-used.xbel", xdg_data); + else + snprintf(xbel_path, sizeof(xbel_path), "%s/.local/share/recently-used.xbel", home); + + xml = read_file_all(xbel_path); + if (!xml) { + puts("[]"); + return 0; + } + + p = xml; + while ((p = strstr(p, "'); + if (!tag_end) + break; + close_bm = strstr(tag_end, ""); + if (!close_bm) + close_bm = tag_end; + + if (get_xml_attr(p, tag_end, "href", href, sizeof(href)) && + strncmp(href, "file://", 7) == 0) { + path_start = href + 7; + /* Strip optional host before leading slash (file://localhost/...) */ + if (*path_start != '/') { + char *slash = strchr(path_start, '/'); + + path_start = slash ? slash : path_start; + } + url_unquote(path_start); + if (stat(path_start, &st) == 0 && S_ISREG(st.st_mode)) { + if (get_xml_attr(p, tag_end, "added", ts_buf, sizeof(ts_buf))) { + t = parse_iso8601(ts_buf); + if (t > best) + best = t; + } + if (get_xml_attr(p, tag_end, "modified", ts_buf, sizeof(ts_buf))) { + t = parse_iso8601(ts_buf); + if (t > best) + best = t; + } + if (get_xml_attr(p, tag_end, "visited", ts_buf, sizeof(ts_buf))) { + t = parse_iso8601(ts_buf); + if (t > best) + best = t; + } + + mime_buf[0] = '\0'; + mime_tag = strstr(tag_end, "mime-type"); + if (mime_tag && mime_tag < close_bm) { + mime_end = strchr(mime_tag, '>'); + if (mime_end && mime_end <= close_bm) + get_xml_attr(mime_tag, mime_end, "type", + mime_buf, sizeof(mime_buf)); + } + + if (n_rows == cap_rows) { + size_t ncap = cap_rows ? cap_rows * 2 : 32; + struct recent_row *nr = realloc(rows, ncap * sizeof(*nr)); + + if (!nr) + break; + rows = nr; + cap_rows = ncap; + } + rows[n_rows].path = xstrdup(path_start); + rows[n_rows].mime = xstrdup(mime_buf); + rows[n_rows].timestamp = best; + n_rows++; + } + } + p = (char *)(close_bm > tag_end ? close_bm + 11 : tag_end + 1); + } + + if (n_rows > 1) + qsort(rows, n_rows, sizeof(*rows), cmp_rows_desc); + + limit = ((size_t)count < n_rows) ? (size_t)count : n_rows; + putchar('['); + for (i = 0; i < limit; i++) { + const char *path = rows[i].path; + const char *slash = strrchr(path, '/'); + const char *base = slash ? slash + 1 : path; + char folder[PATH_MAX]; + size_t hlen = strlen(home); + const char *app; + + if (slash == path) { + strcpy(folder, "/"); + } else if (slash) { + size_t dlen = (size_t)(slash - path); + + if (dlen >= sizeof(folder)) + dlen = sizeof(folder) - 1; + memcpy(folder, path, dlen); + folder[dlen] = '\0'; + } else { + strcpy(folder, "."); + } + + if (hlen > 0 && strncmp(folder, home, hlen) == 0 && + (folder[hlen] == '\0' || folder[hlen] == '/')) { + char short_folder[PATH_MAX]; + + snprintf(short_folder, sizeof(short_folder), "~%s", folder + hlen); + strcpy(folder, short_folder); + } + + app = query_default_app(rows[i].mime, &cache, &cache_len); + if (i > 0) + fputs(", ", stdout); + fputs("{\"path\": ", stdout); + print_json_str(path); + fputs(", \"name\": ", stdout); + print_json_str(base); + fputs(", \"folder\": ", stdout); + print_json_str(folder); + printf(", \"time\": %.6g, \"app\": ", rows[i].timestamp); + print_json_str(app); + putchar('}'); + } + puts("]"); + + for (i = 0; i < n_rows; i++) { + free(rows[i].path); + free(rows[i].mime); + } + free(rows); + for (i = 0; i < cache_len; i++) { + free(cache[i].mime); + free(cache[i].app); + } + free(cache); + free(xml); + return 0; +} diff --git a/desktop/configuration/render-labwc-buttons.c b/desktop/configuration/render-labwc-buttons.c new file mode 100644 index 00000000..9efb06dd --- /dev/null +++ b/desktop/configuration/render-labwc-buttons.c @@ -0,0 +1,190 @@ +/* + * omarchy-render-labwc-buttons: render crisp, theme-coloured labwc SVG + * titlebar controls. + * + * Usage: omarchy-render-labwc-buttons + * + * Build: cc -O2 -Wall -Wextra -Werror -std=c99 render-labwc-buttons.c -o omarchy-render-labwc-buttons + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool is_ident_char(unsigned char c) +{ + return isalnum(c) || c == '_' || c == '-'; +} + +static bool is_hex6(const char *s, size_t len) +{ + size_t i; + + if (len != 7 || s[0] != '#') + return false; + for (i = 1; i < 7; i++) { + if (!isxdigit((unsigned char)s[i])) + return false; + } + return true; +} + +static int mkdir_p(const char *dir) +{ + char buf[PATH_MAX]; + size_t len = strlen(dir); + char *p; + + if (len == 0 || len >= sizeof(buf)) + return -1; + memcpy(buf, dir, len + 1); + for (p = buf + 1; *p; p++) { + if (*p == '/') { + *p = '\0'; + if (mkdir(buf, 0755) != 0 && errno != EEXIST) + return -1; + *p = '/'; + } + } + if (mkdir(buf, 0755) != 0 && errno != EEXIST) + return -1; + return 0; +} + +int main(int argc, char **argv) +{ + static const struct { + const char *name; + const char *shape; + } shapes[] = { + { "iconify", "" }, + { "max", "" }, + { "max_toggled", "" }, + { "close", "" }, + }; + char fg[8] = "", dark_fg[8] = ""; + char line[1024]; + FILE *fp; + const char *states[2] = { "active", "inactive" }; + const char *state_colors[2]; + size_t s, i; + + if (argc != 3) { + fprintf(stderr, "Usage: omarchy-render-labwc-buttons \n"); + return 1; + } + + fp = fopen(argv[1], "r"); + if (!fp) { + fprintf(stderr, "Cannot open %s: %s\n", argv[1], strerror(errno)); + return 1; + } + while (fgets(line, sizeof(line), fp)) { + char *p = line, *kstart, *kend, *vstart, *vend, *rest; + size_t klen, vlen; + + while (*p && isspace((unsigned char)*p)) + p++; + kstart = p; + while (*p && is_ident_char((unsigned char)*p)) + p++; + kend = p; + klen = (size_t)(kend - kstart); + while (*p && isspace((unsigned char)*p)) + p++; + if (*p != '=') + continue; + p++; + while (*p && isspace((unsigned char)*p)) + p++; + if (*p != '"') + continue; + vstart = p + 1; + vend = strchr(vstart, '"'); + if (!vend) + continue; + rest = vend + 1; + while (*rest && isspace((unsigned char)*rest)) + rest++; + if (*rest != '\0' && *rest != '#') + continue; + vlen = (size_t)(vend - vstart); + if (!is_hex6(vstart, vlen)) + continue; + + if (klen == 10 && strncmp(kstart, "foreground", 10) == 0) { + memcpy(fg, vstart, 7); + fg[7] = '\0'; + } else if (klen == 15 && strncmp(kstart, "dark_foreground", 15) == 0) { + memcpy(dark_fg, vstart, 7); + dark_fg[7] = '\0'; + } + } + fclose(fp); + + if (!fg[0] || !dark_fg[0]) { + fprintf(stderr, "Missing foreground or dark_foreground in %s\n", argv[1]); + return 1; + } + + if (mkdir_p(argv[2]) != 0) { + fprintf(stderr, "Cannot create %s: %s\n", argv[2], strerror(errno)); + return 1; + } + + state_colors[0] = fg; + state_colors[1] = dark_fg; + + for (s = 0; s < 2; s++) { + for (i = 0; i < sizeof(shapes) / sizeof(shapes[0]); i++) { + char final_path[PATH_MAX], tmp_path[PATH_MAX], hover_path[PATH_MAX]; + int fd; + FILE *out; + + if (snprintf(final_path, sizeof(final_path), "%s/%s-%s.svg", + argv[2], shapes[i].name, states[s]) >= (int)sizeof(final_path) || + snprintf(tmp_path, sizeof(tmp_path), "%s.next", + final_path) >= (int)sizeof(tmp_path) || + snprintf(hover_path, sizeof(hover_path), "%s/%s_hover-%s.svg", + argv[2], shapes[i].name, states[s]) >= (int)sizeof(hover_path)) { + fprintf(stderr, "Path too long\n"); + return 1; + } + + fd = open(tmp_path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) { + fprintf(stderr, "%s: %s\n", tmp_path, strerror(errno)); + return 1; + } + out = fdopen(fd, "w"); + if (!out) { + close(fd); + return 1; + } + fprintf(out, + "" + "" + "%s\n", + state_colors[s], shapes[i].shape); + if (fflush(out) != 0 || fchmod(fd, 0644) != 0 || fclose(out) != 0) { + fprintf(stderr, "%s: %s\n", tmp_path, strerror(errno)); + return 1; + } + if (rename(tmp_path, final_path) != 0) { + fprintf(stderr, "%s: %s\n", final_path, strerror(errno)); + return 1; + } + /* Labwc draws its hover background only without a dedicated hover icon. */ + unlink(hover_path); + } + } + return 0; +} diff --git a/desktop/configuration/render-labwc-theme.c b/desktop/configuration/render-labwc-theme.c new file mode 100644 index 00000000..5fdd4581 --- /dev/null +++ b/desktop/configuration/render-labwc-theme.c @@ -0,0 +1,319 @@ +/* + * omarchy-render-labwc-theme: map an Omarchy colors.toml and shell.toml palette + * to labwc's Openbox-style themerc on stdout. + * + * Usage: omarchy-render-labwc-theme + * + * Build: cc -O2 -Wall -Wextra -Werror -std=c99 render-labwc-theme.c -o omarchy-render-labwc-theme + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include + +#define MAX_KV 64 + +struct kv { + char key[64]; + char val[128]; +}; + +static bool is_ident_char(unsigned char c) +{ + return isalnum(c) || c == '_' || c == '-'; +} + +static bool is_hex_color(const char *s, size_t len) +{ + size_t i; + + if (len != 7 && len != 9) + return false; + if (s[0] != '#') + return false; + for (i = 1; i < len; i++) { + if (!isxdigit((unsigned char)s[i])) + return false; + } + return true; +} + +static int parse_toml_values(const char *path, const char *want_section, + struct kv *out, int max_kv) +{ + FILE *fp = fopen(path, "r"); + char line[1024]; + char current_section[128] = ""; + int count = 0; + + if (!fp) { + fprintf(stderr, "Cannot open %s\n", path); + return -1; + } + + while (fgets(line, sizeof(line), fp)) { + char *p = line; + char *end; + + while (*p && isspace((unsigned char)*p)) + p++; + end = p + strlen(p); + while (end > p && isspace((unsigned char)end[-1])) + end--; + *end = '\0'; + + if (*p == '\0' || *p == '#') + continue; + + /* Section header: [name] */ + if (*p == '[' && end > p + 2 && end[-1] == ']') { + size_t slen = (size_t)(end - p - 2); + + if (!memchr(p + 1, ']', slen) && slen < sizeof(current_section)) { + memcpy(current_section, p + 1, slen); + current_section[slen] = '\0'; + } + continue; + } + + if (want_section && strcmp(current_section, want_section) != 0) + continue; + + /* key = "value" [# comment] */ + { + char *kstart = p; + char *kend, *vstart, *vend, *rest; + size_t klen, vlen; + + while (*p && is_ident_char((unsigned char)*p)) + p++; + kend = p; + klen = (size_t)(kend - kstart); + if (klen == 0 || klen >= sizeof(out[0].key)) + continue; + while (*p && isspace((unsigned char)*p)) + p++; + if (*p != '=') + continue; + p++; + while (*p && isspace((unsigned char)*p)) + p++; + if (*p != '"') + continue; + vstart = p + 1; + vend = strchr(vstart, '"'); + if (!vend) + continue; + rest = vend + 1; + while (*rest && isspace((unsigned char)*rest)) + rest++; + if (*rest != '\0' && *rest != '#') + continue; + + vlen = (size_t)(vend - vstart); + if (vlen >= sizeof(out[0].val)) + continue; + + /* For colors.toml (want_section == NULL), require #RRGGBB or #RRGGBBAA */ + if (!want_section && !is_hex_color(vstart, vlen)) + continue; + + if (count < max_kv) { + memcpy(out[count].key, kstart, klen); + out[count].key[klen] = '\0'; + memcpy(out[count].val, vstart, vlen); + out[count].val[vlen] = '\0'; + count++; + } + } + } + + fclose(fp); + return count; +} + +static const char *kv_get(const struct kv *kvs, int count, const char *key) +{ + int i; + + for (i = count - 1; i >= 0; i--) { + if (strcmp(kvs[i].key, key) == 0) + return kvs[i].val; + } + return NULL; +} + +static bool extract_active_hex(const char *border, char out[8]) +{ + const char *p; + + for (p = border; *p; p++) { + if (*p == '#') { + int i; + + for (i = 1; i <= 6 && isxdigit((unsigned char)p[i]); i++) + ; + if (i == 7) { + out[0] = '#'; + memcpy(out + 1, p + 1, 6); + out[7] = '\0'; + return true; + } + } else if (strncmp(p, "rgba(", 5) == 0) { + int i; + + for (i = 0; i < 6 && isxdigit((unsigned char)p[5 + i]); i++) + ; + if (i == 6 && + (p[11] == ')' || + (isxdigit((unsigned char)p[11]) && + isxdigit((unsigned char)p[12]) && p[13] == ')'))) { + out[0] = '#'; + memcpy(out + 1, p + 5, 6); + out[7] = '\0'; + return true; + } + } + } + return false; +} + +static void parent_dir_name(const char *path, char *out, size_t out_sz) +{ + const char *slash = strrchr(path, '/'); + const char *p, *start; + size_t len; + + if (!slash || slash == path) { + snprintf(out, out_sz, "."); + return; + } + p = slash; + while (p > path && p[-1] == '/') + p--; + start = p; + while (start > path && start[-1] != '/') + start--; + len = (size_t)(p - start); + if (len == 0) { + snprintf(out, out_sz, "."); + return; + } + if (len >= out_sz) + len = out_sz - 1; + memcpy(out, start, len); + out[len] = '\0'; +} + +int main(int argc, char **argv) +{ + static const char *const required[] = { + "accent", "background", "dark_background", "dark_foreground", + "foreground", "lighter_background", "selection" + }; + struct kv colors[MAX_KV], hyprland[MAX_KV]; + int n_colors, n_hypr; + const char *border, *yellow; + char active[8], theme_name[128]; + size_t i; + + if (argc != 3) { + fprintf(stderr, "Usage: omarchy-render-labwc-theme \n"); + return 1; + } + + n_colors = parse_toml_values(argv[1], NULL, colors, MAX_KV); + if (n_colors < 0) + return 1; + n_hypr = parse_toml_values(argv[2], "hyprland", hyprland, MAX_KV); + if (n_hypr < 0) + return 1; + + for (i = 0; i < sizeof(required) / sizeof(required[0]); i++) { + if (!kv_get(colors, n_colors, required[i])) { + fprintf(stderr, "Missing palette key: %s\n", required[i]); + return 1; + } + } + + border = kv_get(hyprland, n_hypr, "active-border"); + if (!border) + border = kv_get(colors, n_colors, "accent"); + if (!extract_active_hex(border, active)) { + fprintf(stderr, "Unsupported active border: %s\n", border); + return 1; + } + + parent_dir_name(argv[1], theme_name, sizeof(theme_name)); + yellow = kv_get(colors, n_colors, "yellow"); + if (!yellow) + yellow = "#e0af68"; + + printf("# Generated from Omarchy %s colors.toml and shell.toml.\n" + "# Hyprland default/looknfeel.lua: 2px border, inactive #595959aa,\n" + "# rounding 0, shadow off, blur off. labwc keeps functional titlebar buttons.\n" + "border.width: 2\n" + "window.active.border.color: %s\n" + "window.inactive.border.color: #595959aa\n" + "window.active.title.bg: Solid\n" + "window.active.title.bg.color: %s\n" + "window.inactive.title.bg: Solid\n" + "window.inactive.title.bg.color: %s\n" + "window.active.label.text.color: %s\n" + "window.inactive.label.text.color: %s\n" + "window.label.text.justify: Left\n" + "window.titlebar.padding.width: 10\n" + "window.titlebar.padding.height: 2\n" + "window.button.width: 24\n" + "window.button.height: 26\n" + "window.button.spacing: 2\n" + "window.active.button.unpressed.image.color: %s\n" + "window.inactive.button.unpressed.image.color: %s\n" + "window.button.hover.bg.color: %s33\n" + "window.button.hover.bg.corner-radius: 0\n" + "menu.items.bg.color: %s\n" + "menu.items.text.color: %s\n" + "menu.items.active.bg.color: %s\n" + "menu.items.active.text.color: %s\n" + "menu.border.color: %s\n" + "menu.border.width: 2\n" + "osd.bg.color: %s\n" + "osd.label.text.color: %s\n" + "osd.border.color: %s\n" + "osd.border.width: 2\n" + "# Pixman uses an outline for snapping. Match Omarchy's focused border and\n" + "# background rather than labwc's unrelated default OSD preview colours.\n" + "snapping.overlay.edge.bg.enabled: no\n" + "snapping.overlay.region.bg.enabled: no\n" + "snapping.overlay.edge.border.enabled: yes\n" + "snapping.overlay.region.border.enabled: yes\n" + "snapping.overlay.edge.border.width: 2\n" + "snapping.overlay.region.border.width: 2\n" + "snapping.overlay.edge.border.color: %s,%s\n" + "snapping.overlay.region.border.color: %s,%s\n" + "overview.attention.color: %s\n\n", + theme_name, + active, + kv_get(colors, n_colors, "lighter_background"), + kv_get(colors, n_colors, "dark_background"), + kv_get(colors, n_colors, "foreground"), + kv_get(colors, n_colors, "dark_foreground"), + kv_get(colors, n_colors, "foreground"), + kv_get(colors, n_colors, "dark_foreground"), + active, + kv_get(colors, n_colors, "background"), + kv_get(colors, n_colors, "foreground"), + kv_get(colors, n_colors, "selection"), + kv_get(colors, n_colors, "foreground"), + active, + kv_get(colors, n_colors, "background"), + kv_get(colors, n_colors, "foreground"), + active, + active, kv_get(colors, n_colors, "background"), + active, kv_get(colors, n_colors, "background"), + yellow); + return 0; +} diff --git a/desktop/configuration/rotation-lock.c b/desktop/configuration/rotation-lock.c new file mode 100644 index 00000000..41f15a2c --- /dev/null +++ b/desktop/configuration/rotation-lock.c @@ -0,0 +1,92 @@ +/* + * omarchy-rotation-lock: persistent rotation lock shared by the Display panel + * and the rotation daemon. + * + * Usage: omarchy-rotation-lock [status|on|off] + * Prints {"locked": true} or {"locked": false}. + * + * Build: cc -O2 -Wall -Wextra -Werror -std=c99 rotation-lock.c -o omarchy-rotation-lock + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include +#include + +static int mkdir_p(const char *dir) +{ + char buf[PATH_MAX]; + size_t len; + char *p; + + len = strlen(dir); + if (len == 0 || len >= sizeof(buf)) + return -1; + memcpy(buf, dir, len + 1); + + for (p = buf + 1; *p; p++) { + if (*p == '/') { + *p = '\0'; + if (mkdir(buf, 0755) != 0 && errno != EEXIST) + return -1; + *p = '/'; + } + } + if (mkdir(buf, 0755) != 0 && errno != EEXIST) + return -1; + return 0; +} + +int main(int argc, char **argv) +{ + const char *xdg = getenv("XDG_CONFIG_HOME"); + const char *home = getenv("HOME"); + const char *mode = (argc > 1) ? argv[1] : "status"; + char dir[PATH_MAX], path[PATH_MAX]; + int n; + + if (xdg && *xdg) { + n = snprintf(dir, sizeof(dir), "%s/omarchy", xdg); + } else if (home && *home) { + n = snprintf(dir, sizeof(dir), "%s/.config/omarchy", home); + } else { + fprintf(stderr, "Neither XDG_CONFIG_HOME nor HOME is set\n"); + return 1; + } + if (n < 0 || (size_t)n >= sizeof(dir) || + snprintf(path, sizeof(path), "%s/rotation-lock", dir) >= (int)sizeof(path)) { + fprintf(stderr, "Path too long\n"); + return 1; + } + + if (strcmp(mode, "on") == 0) { + int fd; + + if (mkdir_p(dir) != 0) { + fprintf(stderr, "%s: %s\n", dir, strerror(errno)); + return 1; + } + fd = open(path, O_WRONLY | O_CREAT, 0644); + if (fd < 0) { + fprintf(stderr, "%s: %s\n", path, strerror(errno)); + return 1; + } + close(fd); + } else if (strcmp(mode, "off") == 0) { + if (unlink(path) != 0 && errno != ENOENT) { + fprintf(stderr, "%s: %s\n", path, strerror(errno)); + return 1; + } + } else if (strcmp(mode, "status") != 0) { + fprintf(stderr, "Usage: omarchy-rotation-lock [status|on|off]\n"); + return 1; + } + + printf("{\"locked\": %s}\n", access(path, F_OK) == 0 ? "true" : "false"); + return 0; +} diff --git a/desktop/install-tree b/desktop/install-tree index 339db879..e1453f0c 100755 --- a/desktop/install-tree +++ b/desktop/install-tree @@ -19,7 +19,7 @@ here=$(cd "$(dirname "$0")" && pwd) project=$(dirname "$here") shell=$here/shell config=$here/configuration omarchy=$root/usr/share/omarchy -for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/arch-ipad-auto-brightness" "$build/arch-ipad-rotate-output" "$build/omarchy-keyboard" "$build/omarchy-powerctl" "$build/omarchy-mute-switch" "$build/omarchy-powerd" "$upstream/themes" "$upstream/bin" \ +for input in "$build/wvkbd-mobintl" "$build/wtype" "$build/wtype.LICENSE" "$build/arch-ipad-auto-brightness" "$build/arch-ipad-rotate-output" "$build/omarchy-keyboard" "$build/omarchy-powerctl" "$build/omarchy-mute-switch" "$build/omarchy-powerd" "$build/omarchy-desktop-ready" "$build/omarchy-rotation-lock" "$build/omarchy-launcher-recent-files" "$build/omarchy-render-labwc-theme" "$build/omarchy-render-labwc-buttons" "$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" \ @@ -119,6 +119,11 @@ put "$build/omarchy-mute-switch" "$root/usr/libexec/omarchy-mute-switch" 755 put "$build/omarchy-powerctl" "$root/usr/libexec/omarchy-powerctl" 755 put "$build/arch-ipad-rotate-output" "$root/usr/libexec/arch-ipad-rotate-output" 755 put "$build/arch-ipad-auto-brightness" "$root/usr/libexec/arch-ipad-auto-brightness" 755 +put "$build/omarchy-desktop-ready" "$root/usr/libexec/omarchy-desktop-ready" 755 +put "$build/omarchy-rotation-lock" "$omarchy/bin/omarchy-rotation-lock" 755 +put "$build/omarchy-launcher-recent-files" "$omarchy/bin/omarchy-launcher-recent-files" 755 +put "$build/omarchy-render-labwc-theme" "$root/usr/libexec/omarchy-render-labwc-theme" 755 +put "$build/omarchy-render-labwc-buttons" "$root/usr/libexec/omarchy-render-labwc-buttons" 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/desktop/shell/bin/omarchy-launcher-recent-files b/desktop/shell/bin/omarchy-launcher-recent-files deleted file mode 100755 index c81f1761..00000000 --- a/desktop/shell/bin/omarchy-launcher-recent-files +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python3 - -# omarchy:summary=List recently used files, newest first, with the app that opens each, as JSON -# omarchy:args=[count] -# omarchy:hidden=true - -# The launcher's Recent files. GTK keeps the list in recently-used.xbel, the -# same file Folio's Recents reads. Files that are gone are left out, and each -# carries the desktop entry `xdg-mime` names as its default app. - -import json -import os -import subprocess -import sys -import xml.etree.ElementTree as ElementTree -from datetime import datetime -from urllib.parse import unquote, urlparse - -MIME_NS = "{http://www.freedesktop.org/standards/shared-mime-info}" - - -def stamp(value): - if not value: - return 0 - try: - return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() - except ValueError: - return 0 - - -def default_app(mime, cache): - if mime not in cache: - try: - answer = subprocess.run(["xdg-mime", "query", "default", mime], capture_output=True, - text=True, timeout=3).stdout.strip() - except (OSError, subprocess.SubprocessError): - answer = "" - cache[mime] = answer - return cache[mime] - - -def main(): - count = int(sys.argv[1]) if len(sys.argv) > 1 else 8 - data = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share") - try: - root = ElementTree.parse(os.path.join(data, "recently-used.xbel")).getroot() - except (OSError, ElementTree.ParseError): - print("[]") - return - - home = os.path.expanduser("~") - rows = [] - for bookmark in root.iter("bookmark"): - url = urlparse(bookmark.get("href", "")) - if url.scheme != "file": - continue - path = unquote(url.path) - if not os.path.isfile(path): - continue - mime = bookmark.find(".//" + MIME_NS + "mime-type") - when = max(stamp(bookmark.get(key)) for key in ("added", "modified", "visited")) - rows.append({"path": path, "time": when, "mime": mime.get("type", "") if mime is not None else ""}) - - rows.sort(key=lambda row: row["time"], reverse=True) - apps = {} - out = [] - for row in rows[:count]: - folder = os.path.dirname(row["path"]) - if folder == home or folder.startswith(home + os.sep): - folder = "~" + folder[len(home):] - out.append({ - "path": row["path"], - "name": os.path.basename(row["path"]), - "folder": folder, - "time": row["time"], - "app": default_app(row["mime"], apps) if row["mime"] else "", - }) - print(json.dumps(out)) - - -main() diff --git a/desktop/shell/bin/omarchy-rotation-lock b/desktop/shell/bin/omarchy-rotation-lock deleted file mode 100755 index ee7de7a3..00000000 --- a/desktop/shell/bin/omarchy-rotation-lock +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/python3 -"""Persistent rotation lock, shared by the Display panel and rotation daemon.""" -import json -import os -from pathlib import Path -import sys - -path = Path(os.environ.get('XDG_CONFIG_HOME', str(Path.home() / '.config'))) / 'omarchy/rotation-lock' -mode = sys.argv[1] if len(sys.argv) > 1 else 'status' -if mode == 'on': - path.parent.mkdir(parents=True, exist_ok=True) - path.touch() -elif mode == 'off': - path.unlink(missing_ok=True) -elif mode != 'status': - raise SystemExit('Usage: omarchy-rotation-lock [status|on|off]') -print(json.dumps({'locked': path.exists()})) diff --git a/desktop/shell/bin/omarchy-theme-set b/desktop/shell/bin/omarchy-theme-set index 209ba999..8c45b653 100644 --- a/desktop/shell/bin/omarchy-theme-set +++ b/desktop/shell/bin/omarchy-theme-set @@ -21,7 +21,7 @@ trap cleanup EXIT omarchy-theme-set-templates for file in colors.toml shell.toml foot.ini; do [[ -s $next/$file ]] || { echo "Missing rendered $file" >&2; exit 1; }; done -python3 "$root/render-labwc-theme.py" "$next/colors.toml" "$next/shell.toml" >"$rendered" +/usr/libexec/omarchy-render-labwc-theme "$next/colors.toml" "$next/shell.toml" >"$rendered" mapfile -t backgrounds < <(find -L "$next/backgrounds" -maxdepth 1 -type f ! -name '._*' \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.webp' \) -printf '%f\n' | sort) ((${#backgrounds[@]})) || { echo "No image backgrounds in $name" >&2; exit 1; } @@ -42,7 +42,7 @@ mv "$next" "$state/theme" printf '%s\n' "$name" >"$state/theme.name" ln -nsf "$state/theme/backgrounds/$selected" "$state/background" install -m644 "$rendered" "$labwc_theme/themerc" -python3 "$root/render-labwc-buttons.py" "$state/theme/colors.toml" "$labwc_theme" +/usr/libexec/omarchy-render-labwc-buttons "$state/theme/colors.toml" "$labwc_theme" colors_payload=$(base64 -w0 "$state/theme/colors.toml") shell_payload=$(base64 -w0 "$state/theme/shell.toml") diff --git a/desktop/shell/render-labwc-buttons.py b/desktop/shell/render-labwc-buttons.py deleted file mode 100644 index 070d0b09..00000000 --- a/desktop/shell/render-labwc-buttons.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python3 -"""Render crisp, theme-coloured labwc SVG titlebar controls.""" -from pathlib import Path -import os -import re -import sys - -if len(sys.argv) != 3: - sys.exit("Usage: render-labwc-buttons.py ") -colors = {} -for line in Path(sys.argv[1]).read_text().splitlines(): - match = re.fullmatch(r'\s*([\w-]+)\s*=\s*"(#[0-9a-fA-F]{6})"\s*(?:#.*)?', line) - if match: - colors[match.group(1)] = match.group(2) - -out = Path(sys.argv[2]) -out.mkdir(parents=True, exist_ok=True) -shapes = { - "iconify": '', - "max": '', - "max_toggled": '', - "close": '', -} -for state, color in (("active", colors["foreground"]), - ("inactive", colors["dark_foreground"])): - for name, shape in shapes.items(): - svg = (f'' - f'' - f'{shape}\n') - variant = f"{name}-{state}.svg" - tmp = out / (variant + ".next") - tmp.write_text(svg) - os.chmod(tmp, 0o644) - os.replace(tmp, out / variant) - # Labwc draws its hover background only without a dedicated hover icon. - (out / f"{name}_hover-{state}.svg").unlink(missing_ok=True) diff --git a/desktop/shell/render-labwc-theme.py b/desktop/shell/render-labwc-theme.py deleted file mode 100644 index b994fb1b..00000000 --- a/desktop/shell/render-labwc-theme.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python3 -"""Map the selected Omarchy palette to labwc's Openbox-style decorations. - -Omarchy's compositor draws border-only windows; labwc retains titlebar controls -for mouse use, but shares the palette, 2px border, square corners and no shadow. -""" -from __future__ import annotations - -from pathlib import Path -import re -import sys - - -def values(path: Path, section: str | None = None) -> dict[str, str]: - result: dict[str, str] = {} - current = None - for line in path.read_text().splitlines(): - header = re.fullmatch(r"\s*\[([^]]+)\]\s*", line) - if header: - current = header.group(1) - continue - if section is not None and current != section: - continue - match = re.fullmatch(r'\s*([\w-]+)\s*=\s*"(#[0-9a-fA-F]{6,8})"\s*(?:#.*)?', line) - if match: - result[match.group(1)] = match.group(2) - return result - - -base = Path(__file__).resolve().parent -if len(sys.argv) == 1: - colors_file, shell_file = base / "theme/colors.toml", base / "theme/shell.toml" -elif len(sys.argv) == 3: - colors_file, shell_file = Path(sys.argv[1]), Path(sys.argv[2]) -else: - sys.exit("Usage: render-labwc-theme.py [colors.toml shell.toml]") -colors = values(colors_file) -hyprland = values(shell_file, "hyprland") -required = {"background", "dark_background", "lighter_background", "foreground", "dark_foreground", "selection", "accent"} -if missing := required - colors.keys(): - sys.exit(f"Missing palette keys: {', '.join(sorted(missing))}") -# labwc takes a solid border; use the first stop of an Omarchy gradient. -border = hyprland.get("active-border", colors["accent"]) -first = re.search(r"#([0-9a-fA-F]{6})|rgba\(([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?\)", border) -if not first: - sys.exit(f"Unsupported active border: {border}") -active = "#" + (first.group(1) or first.group(2)) - -print(f"""# Generated from Omarchy {colors_file.parent.name} colors.toml and shell.toml. -# Hyprland default/looknfeel.lua: 2px border, inactive #595959aa, -# rounding 0, shadow off, blur off. labwc keeps functional titlebar buttons. -border.width: 2 -window.active.border.color: {active} -window.inactive.border.color: #595959aa -window.active.title.bg: Solid -window.active.title.bg.color: {colors['lighter_background']} -window.inactive.title.bg: Solid -window.inactive.title.bg.color: {colors['dark_background']} -window.active.label.text.color: {colors['foreground']} -window.inactive.label.text.color: {colors['dark_foreground']} -window.label.text.justify: Left -window.titlebar.padding.width: 10 -window.titlebar.padding.height: 2 -window.button.width: 24 -window.button.height: 26 -window.button.spacing: 2 -window.active.button.unpressed.image.color: {colors['foreground']} -window.inactive.button.unpressed.image.color: {colors['dark_foreground']} -window.button.hover.bg.color: {active}33 -window.button.hover.bg.corner-radius: 0 -menu.items.bg.color: {colors['background']} -menu.items.text.color: {colors['foreground']} -menu.items.active.bg.color: {colors['selection']} -menu.items.active.text.color: {colors['foreground']} -menu.border.color: {active} -menu.border.width: 2 -osd.bg.color: {colors['background']} -osd.label.text.color: {colors['foreground']} -osd.border.color: {active} -osd.border.width: 2 -# Pixman uses an outline for snapping. Match Omarchy's focused border and -# background rather than labwc's unrelated default OSD preview colours. -snapping.overlay.edge.bg.enabled: no -snapping.overlay.region.bg.enabled: no -snapping.overlay.edge.border.enabled: yes -snapping.overlay.region.border.enabled: yes -snapping.overlay.edge.border.width: 2 -snapping.overlay.region.border.width: 2 -snapping.overlay.edge.border.color: {active},{colors['background']} -snapping.overlay.region.border.color: {active},{colors['background']} -overview.attention.color: {colors.get('yellow', '#e0af68')} -""") diff --git a/system/overlay/usr/libexec/omarchy-desktop-ready b/system/overlay/usr/libexec/omarchy-desktop-ready deleted file mode 100755 index 9885ad3b..00000000 --- a/system/overlay/usr/libexec/omarchy-desktop-ready +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/python3 -"""Called by the tablet session's shell: record readiness. - -Without an argument, once the shell is up: the desktop's own record in the -session's runtime directory. With `pin-screen`, once the lock the session -starts with is on screen: /run/omarchy-session/ready.json, which the installer -waits for (the release manifest names it). -""" -import json -import os -from pathlib import Path -import pwd -import sys - -if pwd.getpwuid(os.getuid()).pw_name != 'tablet': - raise SystemExit('Readiness comes from the tablet session') -pin_screen = sys.argv[1:] == ['pin-screen'] -if sys.argv[1:] and not pin_screen: - raise SystemExit('Usage: omarchy-desktop-ready [pin-screen]') -target = Path('/run/omarchy-session') if pin_screen else Path(os.environ['XDG_RUNTIME_DIR']) -socket = Path(os.environ['XDG_RUNTIME_DIR']) / os.environ['WAYLAND_DISPLAY'] -if not socket.is_socket() or target.stat().st_uid != os.getuid(): - raise SystemExit('No owned Wayland session') -record = {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), - 'shell_pid': os.getppid(), 'wayland_socket': str(socket)} -name = 'ready.json' if pin_screen else 'omarchy-desktop-ready.json' -temporary = target / (name + '.pending') -temporary.write_text(json.dumps(record)) -temporary.chmod(0o644) -os.replace(temporary, target / name) diff --git a/tests/package_tree.py b/tests/package_tree.py index 4fae242e..cade8b06 100644 --- a/tests/package_tree.py +++ b/tests/package_tree.py @@ -32,7 +32,7 @@ def inputs(base): """BUILD, OMARCHY and DBUS_NEXT for install-tree, under BASE.""" build, upstream, wheel = base / 'build', base / 'omarchy', base / 'wheel' build.mkdir() - for name in ('wvkbd-mobintl', 'wtype', 'omarchy-powerd', 'omarchy-mute-switch', 'omarchy-powerctl', 'omarchy-keyboard', 'arch-ipad-rotate-output', 'arch-ipad-auto-brightness'): + for name in ('wvkbd-mobintl', 'wtype', 'omarchy-powerd', 'omarchy-mute-switch', 'omarchy-powerctl', 'omarchy-keyboard', 'arch-ipad-rotate-output', 'arch-ipad-auto-brightness', 'omarchy-desktop-ready', 'omarchy-rotation-lock', 'omarchy-launcher-recent-files', 'omarchy-render-labwc-theme', 'omarchy-render-labwc-buttons'): (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_c_runtime_helpers.py b/tests/test_c_runtime_helpers.py new file mode 100644 index 00000000..88bdd82e --- /dev/null +++ b/tests/test_c_runtime_helpers.py @@ -0,0 +1,148 @@ +"""Unit tests for the C runtime helpers replacing Python scripts.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +PROJECT = Path(__file__).resolve().parents[1] +CONFIG = PROJECT / "desktop/configuration" + + +class CRuntimeHelpersTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.bin_dir = Path(cls.tmp.name) / "bin" + cls.bin_dir.mkdir() + targets = { + "omarchy-desktop-ready": "desktop-ready.c", + "omarchy-rotation-lock": "rotation-lock.c", + "omarchy-launcher-recent-files": "launcher-recent-files.c", + "omarchy-render-labwc-theme": "render-labwc-theme.c", + "omarchy-render-labwc-buttons": "render-labwc-buttons.c", + } + cls.bins = {} + for name, src in targets.items(): + out = cls.bin_dir / name + res = subprocess.run( + ["cc", "-O2", "-Wall", "-Wextra", "-Werror", "-std=c99", + str(CONFIG / src), "-o", str(out)], + capture_output=True, text=True, + ) + if res.returncode != 0: + raise RuntimeError(f"Failed to compile {src}:\n{res.stderr}") + cls.bins[name] = str(out) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def test_rotation_lock_lifecycle(self): + with tempfile.TemporaryDirectory() as td: + env = {**os.environ, "XDG_CONFIG_HOME": td} + exe = self.bins["omarchy-rotation-lock"] + + r = subprocess.run([exe], env=env, capture_output=True, text=True, check=True) + self.assertEqual(json.loads(r.stdout), {"locked": False}) + + r = subprocess.run([exe, "on"], env=env, capture_output=True, text=True, check=True) + self.assertEqual(json.loads(r.stdout), {"locked": True}) + self.assertTrue((Path(td) / "omarchy/rotation-lock").exists()) + + r = subprocess.run([exe, "status"], env=env, capture_output=True, text=True, check=True) + self.assertEqual(json.loads(r.stdout), {"locked": True}) + + r = subprocess.run([exe, "off"], env=env, capture_output=True, text=True, check=True) + self.assertEqual(json.loads(r.stdout), {"locked": False}) + self.assertFalse((Path(td) / "omarchy/rotation-lock").exists()) + + r = subprocess.run([exe, "bogus"], env=env, capture_output=True, text=True) + self.assertNotEqual(r.returncode, 0) + + def test_launcher_recent_files(self): + with tempfile.TemporaryDirectory() as td: + tdp = Path(td) + home = tdp / "home" + docs = home / "Documents" + docs.mkdir(parents=True) + f1 = docs / "hello world.txt" + f2 = docs / "report¬es.pdf" + f1.write_text("hi") + f2.write_text("pdf") + + data = tdp / "share" + data.mkdir() + xbel = ( + '\n' + '\n' + f' \n' + ' \n' + ' \n' + f' \n' + ' \n' + ' \n' + ' \n' + '\n' + ) + (data / "recently-used.xbel").write_text(xbel) + + env = {**os.environ, "HOME": str(home), "XDG_DATA_HOME": str(data)} + r = subprocess.run([self.bins["omarchy-launcher-recent-files"], "5"], + env=env, capture_output=True, text=True, check=True) + rows = json.loads(r.stdout) + self.assertEqual(len(rows), 2) + self.assertEqual(rows[0]["name"], "report¬es.pdf") + self.assertEqual(rows[0]["folder"], "~/Documents") + self.assertEqual(rows[1]["name"], "hello world.txt") + self.assertGreater(rows[0]["time"], rows[1]["time"]) + + def test_render_labwc_theme_and_buttons(self): + with tempfile.TemporaryDirectory() as td: + tdp = Path(td) + tdir = tdp / "jade-horse" + tdir.mkdir() + colors = tdir / "colors.toml" + shell = tdir / "shell.toml" + colors.write_text( + 'background = "#112233"\n' + 'dark_background = "#0a111a"\n' + 'lighter_background = "#223344"\n' + 'foreground = "#ddeeff"\n' + 'dark_foreground = "#8899aa"\n' + 'selection = "#334455"\n' + 'accent = "#44aa88"\n' + 'yellow = "#e0af68"\n' + ) + shell.write_text('[hyprland]\nactive-border = "rgba(44aa88ff) rgba(112233ff) 45deg"\n') + + r = subprocess.run([self.bins["omarchy-render-labwc-theme"], str(colors), str(shell)], + capture_output=True, text=True, check=True) + self.assertIn("Generated from Omarchy jade-horse colors.toml and shell.toml.", r.stdout) + self.assertIn("window.active.border.color: #44aa88\n", r.stdout) + self.assertIn("window.button.hover.bg.color: #44aa8833\n", r.stdout) + self.assertIn("overview.attention.color: #e0af68\n", r.stdout) + + out_dir = tdp / "labwc" + out_dir.mkdir() + stale_hover = out_dir / "close_hover-active.svg" + stale_hover.write_text("stale") + subprocess.run([self.bins["omarchy-render-labwc-buttons"], str(colors), str(out_dir)], + capture_output=True, text=True, check=True) + self.assertFalse(stale_hover.exists()) + close_svg = (out_dir / "close-active.svg").read_text() + self.assertIn('stroke="#ddeeff"', close_svg) + self.assertIn('M9 9L15 15M15 9L9 15', close_svg) + self.assertEqual(len(list(out_dir.glob("*.svg"))), 8) + + def test_desktop_ready_rejects_non_tablet_user(self): + r = subprocess.run([self.bins["omarchy-desktop-ready"]], + capture_output=True, text=True) + # Running as developer user (not 'tablet') must refuse cleanly. + self.assertNotEqual(r.returncode, 0) + self.assertIn("tablet", r.stderr) + + +if __name__ == "__main__": + unittest.main()