From 158345c16871dee2540ec639a995918b11aeb4a4 Mon Sep 17 00:00:00 2001 From: Luxferre Date: Thu, 26 Nov 2026 12:37:25 +0200 Subject: [PATCH] feat: add XKB layout indicator, live X11 session replace, and ANODE WM/DE identity --- Makefile | 12 +- README.md | 6 +- docs/ARCHITECTURE.md | 6 +- scripts/anode-replace | 318 +++++++++++++++++++++++++++++ scripts/anode-session | 67 +++++- src/common/anode_xkb_parse.h | 198 ++++++++++++++++++ src/daemons/anode-statusd.c | 100 ++++++++- src/dwm/dwm.c | 171 ++++++++++++++-- tests/test_posix_make.py | 1 + tests/test_replace.py | 385 +++++++++++++++++++++++++++++++++++ tests/test_units.c | 46 +++++ tests/test_x11_xvfb.py | 41 +++- 12 files changed, 1303 insertions(+), 48 deletions(-) create mode 100755 scripts/anode-replace create mode 100644 src/common/anode_xkb_parse.h create mode 100755 tests/test_replace.py diff --git a/Makefile b/Makefile index 00c6757..ad0db13 100644 --- a/Makefile +++ b/Makefile @@ -155,7 +155,7 @@ build/apps/anode-vkbd: build/apps/anode-vkbd.o build/libgemui/libgemui.so build/ # --- Zero-poll Daemons & Privilege Helpers --- daemons: build/daemons/anode-statusd build/daemons/anode-touchd build/daemons/anode-powerd build/daemons/anode-power-ctl build/daemons/anode-dnsctl build/daemons/anode-tzctl build/daemons/anode-checkpw -build/daemons/anode-statusd.o: src/daemons/anode-statusd.c src/common/anode_plat.h src/common/anode_tz_valid.h build/flags.sh +build/daemons/anode-statusd.o: src/daemons/anode-statusd.c src/common/anode_plat.h src/common/anode_tz_valid.h src/common/anode_xkb_parse.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$STATUSD_CFLAGS -c src/daemons/anode-statusd.c -o build/daemons/anode-statusd.o build/daemons/anode-statusd: build/daemons/anode-statusd.o build/common/anode_plat.o build/flags.sh @@ -310,7 +310,7 @@ install: all cp -f build/daemons/anode-statusd build/daemons/anode-touchd build/daemons/anode-powerd \ build/daemons/anode-power-ctl build/daemons/anode-dnsctl build/daemons/anode-tzctl \ build/daemons/anode-checkpw "$(DESTDIR)$(PREFIX)/bin/" - cp -f scripts/anode-session scripts/anode-autostart scripts/anode-launcher scripts/anode-apply-theme \ + cp -f scripts/anode-session scripts/anode-replace scripts/anode-autostart scripts/anode-launcher scripts/anode-apply-theme \ scripts/anode-apply-scale scripts/anode-sync-gtk-theme scripts/anode-sync-dunst-theme \ "$(DESTDIR)$(PREFIX)/bin/" chmod 755 \ @@ -325,8 +325,8 @@ install: all "$(DESTDIR)$(PREFIX)/bin/anode-touchd" "$(DESTDIR)$(PREFIX)/bin/anode-powerd" \ "$(DESTDIR)$(PREFIX)/bin/anode-power-ctl" "$(DESTDIR)$(PREFIX)/bin/anode-dnsctl" \ "$(DESTDIR)$(PREFIX)/bin/anode-tzctl" "$(DESTDIR)$(PREFIX)/bin/anode-checkpw" \ - "$(DESTDIR)$(PREFIX)/bin/anode-session" "$(DESTDIR)$(PREFIX)/bin/anode-autostart" \ - "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ + "$(DESTDIR)$(PREFIX)/bin/anode-session" "$(DESTDIR)$(PREFIX)/bin/anode-replace" \ + "$(DESTDIR)$(PREFIX)/bin/anode-autostart" "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ "$(DESTDIR)$(PREFIX)/bin/anode-apply-theme" "$(DESTDIR)$(PREFIX)/bin/anode-apply-scale" \ "$(DESTDIR)$(PREFIX)/bin/anode-sync-gtk-theme" "$(DESTDIR)$(PREFIX)/bin/anode-sync-dunst-theme" cp -f build/libgemui/libgemui.so "$(DESTDIR)$(PREFIX)/lib/libgemui.so" @@ -384,6 +384,7 @@ uninstall: "$(DESTDIR)$(PREFIX)/bin/anode-tzctl" \ "$(DESTDIR)$(PREFIX)/bin/anode-checkpw" \ "$(DESTDIR)$(PREFIX)/bin/anode-session" \ + "$(DESTDIR)$(PREFIX)/bin/anode-replace" \ "$(DESTDIR)$(PREFIX)/bin/anode-autostart" \ "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ "$(DESTDIR)$(PREFIX)/bin/anode-apply-theme" \ @@ -404,7 +405,7 @@ clean: rm -rf build # --- Tests --- -build/tests/test_units: tests/test_units.c src/daemons/anode-touch-gesture.c src/common/anode_plat.c build/flags.sh +build/tests/test_units: tests/test_units.c src/daemons/anode-touch-gesture.c src/common/anode_plat.c src/common/anode_xkb_parse.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -Isrc/daemons -DANODE_PREFIX="\"$(PREFIX)\"" $$TOUCHD_CFLAGS -o build/tests/test_units tests/test_units.c src/daemons/anode-touch-gesture.c src/common/anode_plat.c -lm test: all build/tests/test_units @@ -413,5 +414,6 @@ test: all build/tests/test_units python3 tests/test_theme_scale.py python3 tests/test_autostart.py python3 tests/test_x11_xvfb.py + python3 tests/test_replace.py .PHONY: all dwm dmenu st libgemui apps vkbd daemons gtkttk gtkttk-auto install uninstall clean test diff --git a/README.md b/README.md index f5902ef..f21d617 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ ANODE is a lightweight, keyboard-first, cross-Unix X11 desktop environment for * ## Key features - **Patched window & core X11 stack**: - - **DWM (`6.5-anode`)**: Pango/HarfBuzz status & title bar (`Fira Code` + `DejaVuSansM Nerd Font`), first-class 32-bit ARGB XEmbed systray (`_NET_SYSTEM_TRAY_S`, `XEMBED_INFO` state, empty-tray unmap, `ReparentNotify` undocking, multi-monitor relocation), EWMH dock struts (`_NET_WM_WINDOW_TYPE_DOCK`, `_NET_WM_STRUT_PARTIAL`, `_NET_WORKAREA`), per-tag/grid layouts (`[]=`, `[M]`, `><>`, `###`), clickable bar regions, `Super_L` quick-tap support, `SIGHUP` live restart, and `SIGUSR1`/`XA_RESOURCE_MANAGER` live theme & DPI reload. + - **DWM (`6.5-anode`)**: Pango/HarfBuzz status & title bar (`Fira Code` + `DejaVuSansM Nerd Font`), first-class 32-bit ARGB XEmbed systray (`_NET_SYSTEM_TRAY_S`, `XEMBED_INFO` state, empty-tray unmap, `ReparentNotify` undocking, multi-monitor relocation), EWMH dock struts (`_NET_WM_WINDOW_TYPE_DOCK`, `_NET_WM_STRUT_PARTIAL`, `_NET_WORKAREA`), per-tag/grid layouts (`[]=`, `[M]`, `><>`, `###`), clickable bar regions, `Super_L` quick-tap support, `ANODE WM` EWMH identity, ICCCM `WM_S` `--replace` handoff, `SIGHUP` live restart, and `SIGUSR1`/`XA_RESOURCE_MANAGER` live theme & DPI reload. - **dmenu (`5.3-anode`)**: Pango/HarfBuzz rendering, fuzzy matching, touch/pointer navigation, XFixes/XI2 pointer auto-hiding, dynamic `.Xresources` & fractional scale sizing. - **st (`0.9.2-anode`)**: HarfBuzz programming ligatures (`Fira Code`), dirty-cell rendering cache, focus-gated cursor blink, `.Xresources` + `SIGUSR1` live reload, portable Linux/BSD PTY handling. - **Unified `.xth` theme & fractional DPI scaling engine**: @@ -22,7 +22,7 @@ ANODE is a lightweight, keyboard-first, cross-Unix X11 desktop environment for * - `anode-media-key`: Multimedia key dispatcher for volume, mic mute, brightness, MPRIS/MPD/mpv media playback, screenshots, airplane toggle, suspend, and virtual keyboard toggling. - `anode-vkbd`: Optional EWMH dock multi-layer touch virtual keyboard (`QWERTY`, `Shift`, `Sym`, `Nav`) injecting XTest keystrokes without stealing focus. - **Zero-poll event daemons**: - - `anode-statusd`: `poll()` + self-pipe + Linux `NETLINK_ROUTE` / BSD `PF_ROUTE` link watcher + minute-aligned timer. + - `anode-statusd`: `poll()` + self-pipe + XKB layout group/keymap events + Linux `NETLINK_ROUTE` / BSD `PF_ROUTE` link watcher + minute-aligned timer. - `anode-touchd`: XI2 multitouch edge-swipe gesture recognizer. - `anode-powerd`: Idle dim / lock / suspend policy daemon (`XScreenSaverQueryInfo` when available). - **gtkTtk 0.9 port**: @@ -46,7 +46,7 @@ make PREFIX=/opt/anode CC=clang WITH_GTKTTK=1 make DESTDIR=/tmp/stage PREFIX=/usr/local install ``` -Start ANODE from `.xinitrc` (`exec /usr/local/bin/anode-session`) or via a display manager selecting the installed `ANODE` XSession (`PREFIX/share/xsessions/anode.desktop`). Passing `--profile NAME` (or setting `ANODE_SESSION_PROFILE`) selects a session profile for autostart. +Start ANODE from `.xinitrc` (`exec /usr/local/bin/anode-session`) or via a display manager selecting the installed `ANODE` XSession (`PREFIX/share/xsessions/anode.desktop`). Passing `--profile NAME` (or setting `ANODE_SESSION_PROFILE`) selects a session profile for autostart. To live-replace an already running X11 window manager or session without logging out, run `anode-replace` (pass `--keep-panels` to retain third-party panels/daemons). ## Session autostart diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 086cec9..ed4e4aa 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -3,13 +3,13 @@ ## Component map - `Makefile` & `scripts/detect-env.sh`: Strict `.POSIX:` single build orchestration probing OS headers, `-lcrypt` vs ``, `-lrt`, `-lutil`, `XScrnSaver`, and optional `gtk+-2.0`/`tcl`/`tk` headers cleanly into `build/flags.sh`. -- `src/common/`: Cross-Unix platform layer (`anode_plat.c`, `anode_plat.h`), `.Xresources` / EDID fractional scale helpers (`anode_scale.h`), input validators (`anode_dns_valid.h`, `anode_tz_valid.h`), CLI output parsers (`anode_audio_parse.h`, `anode_wifi_list.h`, `anode_bt_list.h`), and power policy (`anode_power_policy.h`). -- `src/dwm/`, `src/dmenu/`, `src/st/`: Patched suckless X11 core using Pango/HarfBuzz (`Fira Code` ligatures), `.Xresources` + `SIGUSR1` live reload, and `anode_scale.h`. +- `src/common/`: Cross-Unix platform layer (`anode_plat.c`, `anode_plat.h`), `.Xresources` / EDID fractional scale helpers (`anode_scale.h`), input validators (`anode_dns_valid.h`, `anode_tz_valid.h`), XKB layout parser (`anode_xkb_parse.h`), CLI output parsers (`anode_audio_parse.h`, `anode_wifi_list.h`, `anode_bt_list.h`), and power policy (`anode_power_policy.h`). +- `src/dwm/`, `src/dmenu/`, `src/st/`: Patched suckless X11 core using Pango/HarfBuzz (`Fira Code` ligatures), `.Xresources` + `SIGUSR1` live reload, `anode_scale.h`, ICCCM `WM_S` `--replace` selection handoff, and `ANODE WM` EWMH identity. - `src/libgemui/`: Shared library `libgemui.so` + `gemui.pc` providing double-buffered Cairo + Pango rendering, workarea-clamped responsive window sizing, hit tracking, touch-mode sizing (`gemui_touch_row_px`), self-pipe `SIGUSR1` + root `XA_RESOURCE_MANAGER` live reload, and non-blocking `poll()` loops. - `src/apps/`: Desktop control panels and optional dock virtual keyboard (`anode-vkbd`) + multimedia dispatcher (`anode-media-key`). - `src/daemons/`: Zero-poll `poll()` + signal self-pipe daemons (`anode-statusd`, `anode-touchd`, `anode-powerd`) and narrowly-scoped privilege helpers (`anode-power-ctl`, `anode-dnsctl`, `anode-tzctl`, `anode-checkpw`). - `src/gtkTtk/`: Tk/Ttk native GTK-2 bridge (`libgtkTtk0.9.so` + `gtkTtk.tcl`) supporting full `[0.5, 4.0]` fractional scaling. -- `data/` & `scripts/`: 22 96-DPI `.xth` themes, strict POSIX `/bin/sh` synchronization scripts, and i3-style session autostart management (`anode-autostart` + `data/autostart` template). +- `data/` & `scripts/`: 22 96-DPI `.xth` themes, strict POSIX `/bin/sh` synchronization scripts, live session replacement (`anode-replace`), and i3-style session autostart management (`anode-autostart` + `data/autostart` template). ## Fractional DPI multi-toolkit contract diff --git a/scripts/anode-replace b/scripts/anode-replace new file mode 100755 index 0000000..1a61b31 --- /dev/null +++ b/scripts/anode-replace @@ -0,0 +1,318 @@ +#!/bin/sh +# Live-replace a running X11 session / window manager with ANODE (strict POSIX sh) +set -eu + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +: "${ANODE_PREFIX:=/usr/local}" +SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" + +PROFILE="${ANODE_SESSION_PROFILE:-}" +KEEP_PANELS=0 +FOREGROUND=0 +NO_AUTOSTART=0 +DRY_RUN=0 + +usage() { + cat <<'EOF' +Usage: anode-replace [OPTIONS] + +Live-replace the currently running X11 window manager / session with ANODE. + +Options: + --profile NAME Pass session autostart profile NAME to anode-session + --keep-panels Do not stop existing panel, notification, or xsettings daemons + --foreground Exec anode-session in the foreground instead of detaching + --no-autostart Skip anode-autostart start during replacement + --dry-run Print detected WM and planned actions without replacing + -h, --help Show this help +EOF +} + +while [ $# -gt 0 ]; do + case "$1" in + --profile) + [ $# -ge 2 ] || { printf 'anode-replace: --profile requires a name\n' >&2; exit 2; } + PROFILE="$2" + shift 2 + ;; + --profile=*) + PROFILE="${1#--profile=}" + shift + ;; + --keep-panels) + KEEP_PANELS=1 + shift + ;; + --foreground) + FOREGROUND=1 + shift + ;; + --no-autostart) + NO_AUTOSTART=1 + shift + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + printf 'anode-replace: unknown argument: %s\n' "$1" >&2 + exit 2 + ;; + esac +done + +if [ -z "${DISPLAY:-}" ]; then + printf 'anode-replace: error: DISPLAY is not set (run inside an active X11 session)\n' >&2 + exit 1 +fi + +case ":$PATH:" in + *":$SCRIPT_DIR:"*) ;; + *) PATH="$SCRIPT_DIR:$PATH" ;; +esac +case ":$PATH:" in + *":$ANODE_PREFIX/bin:"*) ;; + *) PATH="$ANODE_PREFIX/bin:$PATH" ;; +esac +export PATH + +ANODE_SESSION_BIN="$(command -v anode-session 2>/dev/null || true)" +if [ -z "$ANODE_SESSION_BIN" ]; then + printf 'anode-replace: error: anode-session not found on PATH\n' >&2 + exit 1 +fi + +unset KDE_FULL_SESSION KDE_SESSION_VERSION KDE_SESSION_UID \ + GNOME_DESKTOP_SESSION_ID MATE_DESKTOP_SESSION_ID CINNAMON_VERSION \ + XFCE_SESSION LXQT_SESSION_CONFIG TDE_FULL_SESSION \ + HYPRLAND_INSTANCE_SIGNATURE SWAYSOCK I3SOCK BSPWM_SOCKET \ + WINDOWMAKER E_START GDMSESSION || true + +XDG_CURRENT_DESKTOP="ANODE" +XDG_SESSION_DESKTOP="anode" +DESKTOP_SESSION="anode" +XDG_SESSION_TYPE="x11" +export XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP DESKTOP_SESSION XDG_SESSION_TYPE +if [ -n "$PROFILE" ]; then + ANODE_SESSION_PROFILE="$PROFILE" + export ANODE_SESSION_PROFILE +fi + +get_root_wm_win() { + command -v xprop >/dev/null 2>&1 || return 0 + xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | awk ' + /window id/ { + for (i = 1; i <= NF; i++) { + if ($i ~ /^0x[0-9a-fA-F]+/) { + sub(/,$/, "", $i) + print $i + exit + } + } + } + ' +} + +get_win_wm_name() { + _wid="$1" + [ -n "$_wid" ] || return 0 + command -v xprop >/dev/null 2>&1 || return 0 + _nm="$(xprop -id "$_wid" _NET_WM_NAME 2>/dev/null | awk ' + index($0, "=") > 0 { + v = $0 + sub(/^[^=]*=[ \t]*"?/, "", v) + sub(/"?[ \t]*$/, "", v) + print v + exit + } + ')" + if [ -n "$_nm" ]; then + printf '%s\n' "$_nm" + return 0 + fi + xprop -id "$_wid" WM_NAME 2>/dev/null | awk ' + index($0, "=") > 0 { + v = $0 + sub(/^[^=]*=[ \t]*"?/, "", v) + sub(/"?[ \t]*$/, "", v) + print v + exit + } + ' +} + +get_win_pid() { + _wid="$1" + [ -n "$_wid" ] || return 0 + command -v xprop >/dev/null 2>&1 || return 0 + xprop -id "$_wid" _NET_WM_PID 2>/dev/null | awk ' + index($0, "=") > 0 { + v = $0 + sub(/^[^=]*=[ \t]*/, "", v) + gsub(/[^0-9]/, "", v) + if (v != "") { + print v + exit + } + } + ' +} + +MY_UID="$(id -u)" +SELF_PID="$$" + +is_my_pid() { + _p="$1" + [ -n "$_p" ] || return 1 + (ps -eo uid=,pid= 2>/dev/null || ps -ax -o uid=,pid= 2>/dev/null || true) | awk -v u="$MY_UID" -v t="$_p" ' + $1 == u && $2 == t { found = 1; exit 0 } + END { exit found ? 0 : 1 } + ' +} + +kill_my_procs() { + (ps -eo uid=,pid=,comm= 2>/dev/null || ps -ax -o uid=,pid=,comm= 2>/dev/null || true) | awk -v u="$MY_UID" -v s="$SELF_PID" -v list="$*" ' + BEGIN { + n = split(list, arr, /[ \t]+/) + for (i = 1; i <= n; i++) { + if (arr[i] != "") want[arr[i]] = 1 + } + } + $1 == u && $2 > 1 && $2 != s { + c = $3 + sub(/^.*\//, "", c) + if (c in want) print $2 + } + ' | while read -r _kpid; do + kill -TERM "$_kpid" 2>/dev/null || true + done +} + +sync_activation_env() { + [ "${ANODE_NO_DBUS:-0}" = "1" ] && return 0 + if command -v dbus-update-activation-environment >/dev/null 2>&1; then + dbus-update-activation-environment --systemd \ + XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \ + DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || \ + dbus-update-activation-environment \ + XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \ + DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || true + fi + if command -v systemctl >/dev/null 2>&1; then + systemctl --user set-environment \ + XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \ + DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || true + systemctl --user unset-environment \ + KDE_FULL_SESSION KDE_SESSION_VERSION KDE_SESSION_UID \ + GNOME_DESKTOP_SESSION_ID MATE_DESKTOP_SESSION_ID CINNAMON_VERSION \ + XFCE_SESSION LXQT_SESSION_CONFIG TDE_FULL_SESSION \ + HYPRLAND_INSTANCE_SIGNATURE SWAYSOCK I3SOCK BSPWM_SOCKET \ + WINDOWMAKER E_START GDMSESSION >/dev/null 2>&1 || true + fi +} + +PREV_WM_WIN="$(get_root_wm_win || true)" +PREV_WM_NAME="$(get_win_wm_name "${PREV_WM_WIN:-}" || true)" +PREV_WM_PID="$(get_win_pid "${PREV_WM_WIN:-}" || true)" + +set -- --replace +if [ -n "$PROFILE" ]; then + set -- "$@" --profile "$PROFILE" +fi +if [ "$NO_AUTOSTART" = "1" ]; then + set -- "$@" --no-autostart +fi + +if [ "$DRY_RUN" = "1" ]; then + printf 'Display: %s\n' "$DISPLAY" + printf 'Detected WM: %s (window=%s pid=%s)\n' \ + "${PREV_WM_NAME:-none}" "${PREV_WM_WIN:-none}" "${PREV_WM_PID:-unknown}" + printf 'Panel cleanup: %s\n' "$( [ "$KEEP_PANELS" = "1" ] && printf 'skipped (--keep-panels)' || printf 'enabled' )" + printf 'Target identity: DE=ANODE, WM=ANODE WM\n' + printf 'Command: %s' "$ANODE_SESSION_BIN" + for _arg in "$@"; do + printf ' %s' "$_arg" + done + printf '\n' + exit 0 +fi + +sync_activation_env + +# Stop duplicate ANODE session daemons from an earlier ANODE instance +kill_my_procs anode-statusd anode-powerd anode-touchd anode-vkbd + +# Optionally stop conflicting third-party panels, notification daemons, and settings daemons +if [ "$KEEP_PANELS" != "1" ]; then + kill_my_procs \ + xfce4-panel mate-panel lxpanel tint2 polybar lemonbar fbpanel plank wingpanel \ + dunst xfce4-notifyd xsettingsd xfsettingsd +fi + +if [ "$FOREGROUND" = "1" ]; then + if [ -n "${PREV_WM_PID:-}" ] && is_my_pid "$PREV_WM_PID"; then + ( + sleep 1.5 + _cur_win="$(get_root_wm_win || true)" + if [ -n "${PREV_WM_WIN:-}" ] && [ "$_cur_win" = "$PREV_WM_WIN" ] && kill -0 "$PREV_WM_PID" 2>/dev/null; then + kill -TERM "$PREV_WM_PID" 2>/dev/null || true + fi + ) /dev/null 2>&1 & + fi + exec "$ANODE_SESSION_BIN" "$@" +fi + +( + trap '' HUP + exec "$ANODE_SESSION_BIN" "$@" +) /dev/null 2>&1 & +SESSION_PID=$! + +_tick=0 +_fallback_sent=0 +_replaced=0 +while [ "$_tick" -lt 50 ]; do + if ! kill -0 "$SESSION_PID" 2>/dev/null; then + printf 'anode-replace: error: anode-session exited prematurely\n' >&2 + exit 1 + fi + + if [ "$_tick" -ge 15 ] && [ "$_fallback_sent" = "0" ] && [ -n "${PREV_WM_PID:-}" ]; then + _cur_win="$(get_root_wm_win || true)" + if [ -n "${PREV_WM_WIN:-}" ] && [ "$_cur_win" = "$PREV_WM_WIN" ] && is_my_pid "$PREV_WM_PID"; then + kill -TERM "$PREV_WM_PID" 2>/dev/null || true + _fallback_sent=1 + fi + fi + + if command -v xprop >/dev/null 2>&1; then + _cur_win="$(get_root_wm_win || true)" + if [ -n "${_cur_win:-}" ] && [ "$_cur_win" != "${PREV_WM_WIN:-}" ]; then + _cur_name="$(get_win_wm_name "$_cur_win" || true)" + case "$_cur_name" in + *ANODE*) + _replaced=1 + break + ;; + esac + fi + elif [ "$_tick" -ge 5 ]; then + _replaced=1 + break + fi + + _tick=$(( _tick + 1 )) + sleep 0.1 +done + +if [ "$_replaced" != "1" ]; then + printf 'anode-replace: error: timed out waiting for ANODE WM to take over %s\n' "$DISPLAY" >&2 + exit 1 +fi + +printf 'ANODE is now running on %s (DE: ANODE, WM: ANODE WM)\n' "$DISPLAY" diff --git a/scripts/anode-session b/scripts/anode-session index 95d3a1f..22a4705 100755 --- a/scripts/anode-session +++ b/scripts/anode-session @@ -4,10 +4,9 @@ set -u : "${XDG_CONFIG_HOME:=$HOME/.config}" : "${ANODE_PREFIX:=/usr/local}" -: "${XDG_CURRENT_DESKTOP:=ANODE}" -: "${XDG_SESSION_DESKTOP:=anode}" -: "${DESKTOP_SESSION:=anode}" SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +REPLACE_WM=0 +NO_AUTOSTART=0 while [ $# -gt 0 ]; do case "$1" in @@ -23,17 +22,51 @@ while [ $# -gt 0 ]; do ANODE_SESSION_PROFILE="${1#--profile=}" shift ;; + --replace) + REPLACE_WM=1 + shift + ;; + --no-autostart) + NO_AUTOSTART=1 + shift + ;; *) shift ;; esac done -export XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP DESKTOP_SESSION +unset KDE_FULL_SESSION KDE_SESSION_VERSION KDE_SESSION_UID \ + GNOME_DESKTOP_SESSION_ID MATE_DESKTOP_SESSION_ID CINNAMON_VERSION \ + XFCE_SESSION LXQT_SESSION_CONFIG TDE_FULL_SESSION \ + HYPRLAND_INSTANCE_SIGNATURE SWAYSOCK I3SOCK BSPWM_SOCKET \ + WINDOWMAKER E_START GDMSESSION || true + +XDG_CURRENT_DESKTOP="ANODE" +XDG_SESSION_DESKTOP="anode" +DESKTOP_SESSION="anode" +XDG_SESSION_TYPE="x11" +export XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP DESKTOP_SESSION XDG_SESSION_TYPE if [ -n "${ANODE_SESSION_PROFILE:-}" ]; then export ANODE_SESSION_PROFILE fi +if [ "${ANODE_NO_DBUS:-0}" != "1" ]; then + if command -v dbus-update-activation-environment >/dev/null 2>&1; then + dbus-update-activation-environment --systemd \ + XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \ + DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || \ + dbus-update-activation-environment \ + XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \ + DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || true + fi + if command -v systemctl >/dev/null 2>&1; then + systemctl --user set-environment \ + XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \ + DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || true + fi +fi + # Ensure ANODE prefix binaries are on PATH case ":$PATH:" in *":$SCRIPT_DIR:"*) ;; @@ -107,14 +140,24 @@ if [ ! -e "$XDG_CONFIG_HOME/anode/autostart" ]; then unset _tpl fi -# Launch i3-style and XDG session autostart entries once DWM is ready -if command -v anode-autostart >/dev/null 2>&1; then +# Launch i3-style and XDG session autostart entries once ANODE DWM is ready +if [ "$NO_AUTOSTART" != "1" ] && command -v anode-autostart >/dev/null 2>&1; then ( _i=0 if command -v xprop >/dev/null 2>&1; then - while [ "$_i" -lt 20 ]; do - if xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | grep -q "window id"; then - break + while [ "$_i" -lt 50 ]; do + _wm_id="$(xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | awk ' + /window id/ { + for (i = 1; i <= NF; i++) { + if ($i ~ /^0x[0-9a-fA-F]+/) { sub(/,$/, "", $i); print $i; exit } + } + } + ')" + if [ -n "${_wm_id:-}" ]; then + _wm_name="$(xprop -id "$_wm_id" _NET_WM_NAME 2>/dev/null || true)" + case "$_wm_name" in + *ANODE*) break ;; + esac fi _i=$(( _i + 1 )) sleep 0.1 @@ -128,7 +171,11 @@ if command -v anode-autostart >/dev/null 2>&1; then fi if command -v dwm >/dev/null 2>&1; then - dwm + if [ "$REPLACE_WM" = "1" ]; then + dwm --replace + else + dwm + fi else printf 'anode-session: dwm executable not found\n' >&2 exit 1 diff --git a/src/common/anode_xkb_parse.h b/src/common/anode_xkb_parse.h new file mode 100644 index 0000000..0a5bde7 --- /dev/null +++ b/src/common/anode_xkb_parse.h @@ -0,0 +1,198 @@ +#ifndef ANODE_XKB_PARSE_H +#define ANODE_XKB_PARSE_H + +#include +#include +#include + +static inline bool anode_xkb_ascii_is_ws(char c) { + return c == ' ' || c == '\t' || c == '\r' || c == '\n'; +} + +static inline bool anode_xkb_ascii_eq_ci(const char *a, size_t alen, const char *b) { + size_t blen = strlen(b); + if (alen != blen) return false; + for (size_t i = 0; i < alen; i++) { + char ca = a[i]; + char cb = b[i]; + if (ca >= 'A' && ca <= 'Z') ca = (char)(ca + ('a' - 'A')); + if (cb >= 'A' && cb <= 'Z') cb = (char)(cb + ('a' - 'A')); + if (ca != cb) return false; + } + return true; +} + +static inline bool anode_xkb_normalize_code(const char *src, size_t len, char *out, size_t out_sz) { + if (!out || out_sz == 0) return false; + out[0] = '\0'; + if (!src || len == 0) return false; + + size_t start = 0; + size_t end = len; + while (start < end && anode_xkb_ascii_is_ws(src[start])) start++; + while (end > start && anode_xkb_ascii_is_ws(src[end - 1])) end--; + + for (size_t i = start; i < end; i++) { + if (src[i] == ':' || src[i] == '(') { + end = i; + break; + } + } + while (end > start && anode_xkb_ascii_is_ws(src[end - 1])) end--; + + for (size_t i = start; i < end; i++) { + if (src[i] == '/') start = i + 1; + } + + size_t n = 0; + for (size_t i = start; i < end && n + 1 < out_sz; i++) { + char c = src[i]; + if (c >= 'A' && c <= 'Z') { + out[n++] = (char)(c + ('a' - 'A')); + } else if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { + out[n++] = c; + } + } + out[n] = '\0'; + return n > 0; +} + +static inline bool anode_xkb_is_ignored_sym(const char *tok, size_t len) { + static const char *const ignored[] = { + "pc", "base", "evdev", "inet", "group", "compose", "level2", "level3", "level5", + "ctrl", "caps", "capslock", "altwin", "shift", "keypad", "kpdl", "nbsp", + "eurosign", "rupeesign", "terminate", "srvr_ctrl", "esperanto", "parens", + "misc", "typo", "compat", "complete", "empty", "default", "basic", "olpc", + "extra", "grab", "hyper", "scrolllock", "fkeys", "mod_led", "japan", "korean", + "solaris", "sun_vndr", "sgi_vndr", "macintosh_vndr", "digital_vndr", + "fujitsu_vndr", "hp_vndr", "sony_vndr", "sharp_vndr", "nokia_vndr", + "xfree68_vndr", "nec_vndr", "apple" + }; + for (size_t i = 0; i < sizeof(ignored) / sizeof(ignored[0]); i++) { + if (anode_xkb_ascii_eq_ci(tok, len, ignored[i])) return true; + } + return false; +} + +static inline bool anode_xkb_layout_from_symbols(const char *symbols, unsigned int group, + char *out, size_t out_sz) { + if (!out || out_sz == 0) return false; + out[0] = '\0'; + if (!symbols || !symbols[0]) return false; + + const char *p = symbols; + while (*p) { + while (*p == '+' || *p == '|' || anode_xkb_ascii_is_ws(*p)) p++; + if (!*p) break; + + const char *tok_start = p; + while (*p && *p != '+' && *p != '|') p++; + const char *tok_end = p; + while (tok_end > tok_start && anode_xkb_ascii_is_ws(tok_end[-1])) tok_end--; + if (tok_end <= tok_start) continue; + + /* Check for trailing :N XKB group selector */ + unsigned int tok_grp = 1; + const char *eff_end = tok_end; + const char *colon = NULL; + for (const char *q = tok_end; q > tok_start; q--) { + if (q[-1] == ':') { + colon = q - 1; + break; + } + } + if (colon && colon + 1 < tok_end) { + bool all_digits = true; + unsigned int val = 0; + for (const char *q = colon + 1; q < tok_end; q++) { + if (*q < '0' || *q > '9') { + all_digits = false; + break; + } + val = val * 10U + (unsigned int)(*q - '0'); + } + if (all_digits && val > 0) { + tok_grp = val; + eff_end = colon; + } + } + + /* Strip optional (variant) suffix before matching component name */ + size_t base_len = (size_t)(eff_end - tok_start); + for (size_t i = 0; i < base_len; i++) { + if (tok_start[i] == '(') { + base_len = i; + break; + } + } + while (base_len > 0 && anode_xkb_ascii_is_ws(tok_start[base_len - 1])) base_len--; + if (base_len == 0) continue; + + if (anode_xkb_is_ignored_sym(tok_start, base_len)) continue; + + if (tok_grp == group + 1U) { + if (anode_xkb_normalize_code(tok_start, base_len, out, out_sz)) return true; + } + } + return false; +} + +static inline bool anode_xkb_layout_from_rules_prop(const unsigned char *prop, + unsigned long nbytes, + unsigned int group, + char *out, size_t out_sz) { + if (!out || out_sz == 0) return false; + out[0] = '\0'; + if (!prop || nbytes == 0) return false; + + /* _XKB_RULES_NAMES stores NUL-separated: rules, model, layouts, variants, options */ + unsigned long pos = 0; + unsigned int field = 0; + while (pos < nbytes && field < 2) { + if (prop[pos] == '\0') field++; + pos++; + } + if (field != 2 || pos >= nbytes) return false; + + unsigned long lay_start = pos; + unsigned long lay_end = lay_start; + while (lay_end < nbytes && prop[lay_end] != '\0') lay_end++; + + unsigned long cur = lay_start; + unsigned int idx = 0; + while (cur <= lay_end) { + unsigned long seg_end = cur; + while (seg_end < lay_end && prop[seg_end] != ',') seg_end++; + if (idx == group) { + return anode_xkb_normalize_code((const char *)(prop + cur), + (size_t)(seg_end - cur), out, out_sz); + } + if (seg_end >= lay_end) break; + cur = seg_end + 1; + idx++; + } + return false; +} + +static inline bool anode_xkb_layout_from_group_name(const char *gname, char *out, size_t out_sz) { + if (!out || out_sz < 2) { + if (out && out_sz > 0) out[0] = '\0'; + return false; + } + out[0] = '\0'; + if (!gname) return false; + + size_t n = 0; + for (const char *p = gname; *p && n < 2 && n + 1 < out_sz; p++) { + char c = *p; + if (c >= 'A' && c <= 'Z') { + out[n++] = (char)(c + ('a' - 'A')); + } else if (c >= 'a' && c <= 'z') { + out[n++] = c; + } + } + out[n] = '\0'; + return n > 0; +} + +#endif /* ANODE_XKB_PARSE_H */ diff --git a/src/daemons/anode-statusd.c b/src/daemons/anode-statusd.c index 7e0f772..51606ae 100644 --- a/src/daemons/anode-statusd.c +++ b/src/daemons/anode-statusd.c @@ -1,5 +1,6 @@ #define _POSIX_C_SOURCE 200809L #include "anode_plat.h" +#include "anode_xkb_parse.h" #include #include @@ -12,6 +13,8 @@ #include #include #include +#include +#include #include #ifdef __linux__ @@ -59,7 +62,65 @@ static int open_net_watch_fd(void) { return -1; } -static void build_status(char *out, size_t sz) { +static bool query_xkb_layout(Display *dpy, Window root, bool has_xkb, char *out, size_t out_sz) { + if (!out || out_sz == 0) return false; + out[0] = '\0'; + if (!has_xkb || !dpy) return false; + + XkbStateRec state; + memset(&state, 0, sizeof(state)); + if (XkbGetState(dpy, XkbUseCoreKbd, &state) != Success) return false; + unsigned int grp = (unsigned int)state.group; + + bool ok = false; + XkbDescPtr desc = XkbAllocKeyboard(); + if (desc) { + if (XkbGetNames(dpy, XkbSymbolsNameMask | XkbGroupNamesMask, desc) != Success) { + XkbFreeKeyboard(desc, 0, True); + desc = NULL; + } + } + + /* Priority 1: XKB symbols name (tracks active groups cleanly across setxkbmap / xkbcomp) */ + if (desc && desc->names && desc->names->symbols != None) { + char *sym = XGetAtomName(dpy, desc->names->symbols); + if (sym) { + ok = anode_xkb_layout_from_symbols(sym, grp, out, out_sz); + XFree(sym); + } + } + + /* Priority 2: root _XKB_RULES_NAMES property layouts CSV */ + if (!ok) { + Atom r_atom = XInternAtom(dpy, "_XKB_RULES_NAMES", True); + if (r_atom != None) { + Atom act_type = None; + int act_fmt = 0; + unsigned long nitems = 0, bytes_after = 0; + unsigned char *prop = NULL; + if (XGetWindowProperty(dpy, root, r_atom, 0, 1024, False, XA_STRING, + &act_type, &act_fmt, &nitems, &bytes_after, &prop) == Success && + prop && act_type == XA_STRING && act_fmt == 8 && nitems > 0) { + ok = anode_xkb_layout_from_rules_prop(prop, nitems, grp, out, out_sz); + } + if (prop) XFree(prop); + } + } + + /* Priority 3: first two ASCII letters of the XKB group name */ + if (!ok && desc && desc->names && grp < XkbNumKbdGroups && desc->names->groups[grp] != None) { + char *gname = XGetAtomName(dpy, desc->names->groups[grp]); + if (gname) { + ok = anode_xkb_layout_from_group_name(gname, out, out_sz); + XFree(gname); + } + } + + if (desc) XkbFreeKeyboard(desc, 0, True); + return ok; +} + +static void build_status(Display *dpy, Window root, bool has_xkb, char *out, size_t sz) { int vol = 0; bool muted = false; char vol_str[32] = ""; @@ -100,13 +161,20 @@ static void build_status(char *out, size_t sz) { snprintf(bat_str, sizeof(bat_str), "AC"); } + char kbd_str[16] = ""; + query_xkb_layout(dpy, root, has_xkb, kbd_str, sizeof(kbd_str)); + time_t now = time(NULL); struct tm tmbuf; localtime_r(&now, &tmbuf); char time_str[32]; strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M", &tmbuf); - if (vol_str[0]) { + if (vol_str[0] && kbd_str[0]) { + snprintf(out, sz, " %s | %s | %s | %s | %s ", vol_str, net_str, bat_str, kbd_str, time_str); + } else if (kbd_str[0]) { + snprintf(out, sz, " %s | %s | %s | %s ", net_str, bat_str, kbd_str, time_str); + } else if (vol_str[0]) { snprintf(out, sz, " %s | %s | %s | %s ", vol_str, net_str, bat_str, time_str); } else { snprintf(out, sz, " %s | %s | %s ", net_str, bat_str, time_str); @@ -133,6 +201,19 @@ int main(void) { fprintf(stderr, "anode-statusd: cannot open X11 display\n"); return 1; } + + int xkb_op = 0, xkb_ev = 0, xkb_err = 0; + int xkb_maj = XkbMajorVersion, xkb_min = XkbMinorVersion; + bool has_xkb = XkbQueryExtension(dpy, &xkb_op, &xkb_ev, &xkb_err, &xkb_maj, &xkb_min) != 0; + if (has_xkb) { + XkbSelectEvents(dpy, XkbUseCoreKbd, + XkbNewKeyboardNotifyMask | XkbMapNotifyMask | XkbNamesNotifyMask, + XkbNewKeyboardNotifyMask | XkbMapNotifyMask | XkbNamesNotifyMask); + XkbSelectEventDetails(dpy, XkbUseCoreKbd, XkbStateNotify, + XkbAllStateComponentsMask, XkbGroupStateMask); + XSync(dpy, False); + } + Window root = DefaultRootWindow(dpy); int xfd = ConnectionNumber(dpy); int netfd = open_net_watch_fd(); @@ -141,18 +222,20 @@ int main(void) { bool running = true; while (running) { + while (XPending(dpy) > 0) { + XEvent ev; + XNextEvent(dpy, &ev); + } + char cur[512]; - build_status(cur, sizeof(cur)); + build_status(dpy, root, has_xkb, cur, sizeof(cur)); if (strcmp(cur, last_status) != 0) { snprintf(last_status, sizeof(last_status), "%s", cur); XStoreName(dpy, root, cur); XFlush(dpy); } - while (XPending(dpy) > 0) { - XEvent ev; - XNextEvent(dpy, &ev); - } + if (XPending(dpy) > 0) continue; time_t now = time(NULL); struct tm tmbuf; @@ -178,6 +261,9 @@ int main(void) { } } } + if (pfds[1].revents & (POLLERR | POLLHUP)) { + running = false; + } if (netfd >= 0 && nfds > 2 && (pfds[2].revents & POLLIN)) { char nbuf[1024]; while (read(netfd, nbuf, sizeof(nbuf)) > 0) {} diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c index c252524..4996cee 100644 --- a/src/dwm/dwm.c +++ b/src/dwm/dwm.c @@ -62,7 +62,7 @@ enum { NetSupported, NetWMName, NetWMState, NetWMCheck, NetSystemTrayOrientationHorz, NetSystemTrayVisual, NetWMFullscreen, NetActiveWindow, NetWorkarea, NetWMWindowType, NetWMWindowTypeDialog, NetWMWindowTypeDock, - NetWMStrutPartial, NetWMStrut, NetClientList, NetLast }; + NetWMStrutPartial, NetWMStrut, NetClientList, NetWMPid, NetLast }; enum { Manager, Xembed, XembedInfo, XLast }; enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkLauncher, @@ -167,7 +167,7 @@ static void arrangemon(Monitor *m); static void attach(Client *c); static void attachstack(Client *c); static void buttonpress(XEvent *e); -static void checkotherwm(void); +static void acquirewm(void); static void cleanup(void); static void cleanupmon(Monitor *mon); static void clientmessage(XEvent *e); @@ -274,7 +274,10 @@ static void view(const Arg *arg); static Client *wintoclient(Window w); static Monitor *wintomon(Window w); static Client *wintosystrayicon(Window w); +static Time getservertime(Window w); +static void selectionclear(XEvent *e); static int xerror(Display *dpy, XErrorEvent *ee); +static int xerrorcheckother(Display *dpy, XErrorEvent *ee); static int xerrordummy(Display *dpy, XErrorEvent *ee); static int xerrorstart(Display *dpy, XErrorEvent *ee); static void zoom(const Arg *arg); @@ -296,6 +299,8 @@ static int (*xerrorxlib)(Display *, XErrorEvent *); static unsigned int numlockmask = 0; static volatile sig_atomic_t reload_pending = 0; static volatile sig_atomic_t restart_dwm = 0; +static int replace_wm = 0; +static int otherwm_err = 0; static int super_down = 0; static int super_dirty = 0; static unsigned long long super_down_ms = 0; @@ -320,9 +325,11 @@ static void (*handler[LASTEvent])(XEvent *) = { [PropertyNotify] = propertynotify, [ReparentNotify] = reparentnotify, [ResizeRequest] = resizerequest, + [SelectionClear] = selectionclear, [UnmapNotify] = unmapnotify }; static Atom wmatom[WMLast], netatom[NetLast], xatom[XLast]; +static Atom utf8string = None, wmselatom = None; static int running = 1; static Cur *cursor[CurLast]; static Clr **scheme; @@ -495,12 +502,125 @@ static void buttonpress(XEvent *e) { } } -static void checkotherwm(void) { - xerrorxlib = XSetErrorHandler(xerrorstart); - XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask); - XSync(dpy, False); - XSetErrorHandler(xerror); - XSync(dpy, False); +static Time getservertime(Window w) { + XEvent ev; + XSelectInput(dpy, w, PropertyChangeMask); + XChangeProperty(dpy, w, netatom[NetWMName], utf8string, 8, + PropModeAppend, (unsigned char *)"", 0); + XWindowEvent(dpy, w, PropertyChangeMask, &ev); + XSelectInput(dpy, w, 0); + return ev.xproperty.time; +} + +static void selectionclear(XEvent *e) { + if (e->xselectionclear.window == wmcheckwin && + e->xselectionclear.selection == wmselatom) { + restart_dwm = 0; + running = 0; + } +} + +static void acquirewm(void) { + char selname[32]; + Window prev_owner; + Time ts; + XClientMessageEvent cm; + + xerrorxlib = XSetErrorHandler(xerror); + screen = DefaultScreen(dpy); + root = RootWindow(dpy, screen); + snprintf(selname, sizeof(selname), "WM_S%d", screen); + wmselatom = XInternAtom(dpy, selname, False); + xatom[Manager] = XInternAtom(dpy, "MANAGER", False); + netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False); + utf8string = XInternAtom(dpy, "UTF8_STRING", False); + + wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0); + prev_owner = XGetSelectionOwner(dpy, wmselatom); + + if (!replace_wm) { + if (prev_owner != None) + die("dwm: another window manager is already running"); + xerrorxlib = XSetErrorHandler(xerrorstart); + XSelectInput(dpy, root, SubstructureRedirectMask); + XSync(dpy, False); + XSetErrorHandler(xerror); + XSync(dpy, False); + } else { + int prev_alive = (prev_owner != None && prev_owner != wmcheckwin) ? 1 : 0; + if (prev_alive) { + XSetErrorHandler(xerrordummy); + XSelectInput(dpy, prev_owner, StructureNotifyMask); + XSync(dpy, False); + XSetErrorHandler(xerror); + } + ts = getservertime(wmcheckwin); + XSetSelectionOwner(dpy, wmselatom, wmcheckwin, ts); + if (XGetSelectionOwner(dpy, wmselatom) != wmcheckwin) + die("dwm: failed to acquire WM_S selection"); + + memset(&cm, 0, sizeof(cm)); + cm.type = ClientMessage; + cm.window = root; + cm.message_type = xatom[Manager]; + cm.format = 32; + cm.data.l[0] = (long)ts; + cm.data.l[1] = (long)wmselatom; + cm.data.l[2] = (long)wmcheckwin; + XSendEvent(dpy, root, False, StructureNotifyMask, (XEvent *)&cm); + XSync(dpy, False); + + unsigned long long deadline = now_ms() + 5000ULL; + for (;;) { + while (XPending(dpy) > 0) { + XEvent ev; + XNextEvent(dpy, &ev); + if (prev_alive && ev.type == DestroyNotify && + ev.xdestroywindow.window == prev_owner) { + prev_alive = 0; + } + } + otherwm_err = 0; + XSetErrorHandler(xerrorcheckother); + XSelectInput(dpy, root, SubstructureRedirectMask); + XSync(dpy, False); + XSetErrorHandler(xerror); + if (!otherwm_err && prev_alive) { + XWindowAttributes wa; + XSetErrorHandler(xerrordummy); + if (!XGetWindowAttributes(dpy, prev_owner, &wa)) + prev_alive = 0; + XSync(dpy, False); + XSetErrorHandler(xerror); + } + if (!otherwm_err && !prev_alive) + break; + if (now_ms() >= deadline) + break; + { + struct pollfd pfd = { .fd = ConnectionNumber(dpy), .events = POLLIN }; + poll(&pfd, 1, 50); + } + } + if (otherwm_err) + die("dwm: timed out waiting for previous window manager to exit"); + return; + } + + ts = getservertime(wmcheckwin); + XSetSelectionOwner(dpy, wmselatom, wmcheckwin, ts); + if (XGetSelectionOwner(dpy, wmselatom) == wmcheckwin) { + memset(&cm, 0, sizeof(cm)); + cm.type = ClientMessage; + cm.window = root; + cm.message_type = xatom[Manager]; + cm.format = 32; + cm.data.l[0] = (long)ts; + cm.data.l[1] = (long)wmselatom; + cm.data.l[2] = (long)wmcheckwin; + XSendEvent(dpy, root, False, StructureNotifyMask, (XEvent *)&cm); + XSync(dpy, False); + } } static void cleanup(void) { @@ -538,6 +658,8 @@ static void cleanup(void) { free(scheme[SchemeNorm]); free(scheme[SchemeSel]); free(scheme); + XSelectInput(dpy, root, 0); + XDeleteProperty(dpy, root, netatom[NetWMCheck]); XDestroyWindow(dpy, wmcheckwin); drw_free(drw); XSync(dpy, False); @@ -1864,7 +1986,6 @@ static void setmfact(const Arg *arg) { static void setup(void) { XSetWindowAttributes wa; - Atom utf8string; struct sigaction sa; sigemptyset(&sa.sa_mask); @@ -1923,6 +2044,7 @@ static void setup(void) { netatom[NetWMStrutPartial] = XInternAtom(dpy, "_NET_WM_STRUT_PARTIAL", False); netatom[NetWMStrut] = XInternAtom(dpy, "_NET_WM_STRUT", False); netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False); + netatom[NetWMPid] = XInternAtom(dpy, "_NET_WM_PID", False); xatom[Manager] = XInternAtom(dpy, "MANAGER", False); xatom[Xembed] = XInternAtom(dpy, "_XEMBED", False); xatom[XembedInfo] = XInternAtom(dpy, "_XEMBED_INFO", False); @@ -1940,11 +2062,16 @@ static void setup(void) { updateworkarea(); updatestatus(); - wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0); XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmcheckwin, 1); XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8, - PropModeReplace, (unsigned char *)"dwm", 3); + PropModeReplace, (unsigned char *)"ANODE WM", 8); + XStoreName(dpy, wmcheckwin, "ANODE WM"); + { + unsigned long pid = (unsigned long)getpid(); + XChangeProperty(dpy, wmcheckwin, netatom[NetWMPid], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&pid, 1); + } XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmcheckwin, 1); XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32, @@ -2170,7 +2297,7 @@ static void updatebars(void) { .background_pixmap = ParentRelative, .event_mask = ButtonPressMask | ExposureMask }; - XClassHint ch = {"dwm", "dwm"}; + XClassHint ch = {"anode-wm", "ANODE"}; for (m = mons; m; m = m->next) { if (m->barwin) continue; w = (unsigned int)m->ww; @@ -2722,6 +2849,12 @@ static int xerror(Display *dpy, XErrorEvent *ee) { return xerrorxlib(dpy, ee); } +static int xerrorcheckother(Display *dpy, XErrorEvent *ee) { + (void)dpy; (void)ee; + otherwm_err = 1; + return 0; +} + static int xerrordummy(Display *dpy, XErrorEvent *ee) { (void)dpy; (void)ee; return 0; @@ -2742,16 +2875,20 @@ static void zoom(const Arg *arg) { } int main(int argc, char *argv[]) { - if (argc == 2 && !strcmp("-v", argv[1])) { - die("dwm-" VERSION); - } else if (argc != 1) { - die("usage: dwm [-v]"); + for (int i = 1; i < argc; i++) { + if (!strcmp("-v", argv[i])) { + die("dwm-" VERSION); + } else if (!strcmp("--replace", argv[i])) { + replace_wm = 1; + } else { + die("usage: dwm [-v] [--replace]"); + } } if (!setlocale(LC_CTYPE, "") || !XSupportsLocale()) fputs("warning: no locale support\n", stderr); if (!(dpy = XOpenDisplay(NULL))) die("dwm: cannot open display"); - checkotherwm(); + acquirewm(); setup(); scan(); { diff --git a/tests/test_posix_make.py b/tests/test_posix_make.py index a0a19c3..41596d4 100755 --- a/tests/test_posix_make.py +++ b/tests/test_posix_make.py @@ -55,6 +55,7 @@ def check_scripts() -> None: "scripts/anode-sync-gtk-theme", "scripts/anode-sync-dunst-theme", "scripts/anode-session", + "scripts/anode-replace", "scripts/anode-autostart", "scripts/anode-launcher", "data/env.sh", diff --git a/tests/test_replace.py b/tests/test_replace.py new file mode 100755 index 0000000..3e18375 --- /dev/null +++ b/tests/test_replace.py @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +"""Headless Xvfb tests for ANODE live X11 replacement and fastfetch DE/WM identity.""" + +import ctypes +import ctypes.util +import json +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import time + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +BUILD = os.path.join(ROOT, "build") +DWM_BIN = os.path.join(BUILD, "dwm", "dwm") +REPLACE_BIN = os.path.join(ROOT, "scripts", "anode-replace") + +libx11_name = ctypes.util.find_library("X11") or "libX11.so.6" +X11 = ctypes.CDLL(libx11_name) + +Window = ctypes.c_ulong +Atom = ctypes.c_ulong +Display_p = ctypes.c_void_p + + +class XWindowAttributes(ctypes.Structure): + _fields_ = [ + ("x", ctypes.c_int), ("y", ctypes.c_int), + ("width", ctypes.c_int), ("height", ctypes.c_int), + ("border_width", ctypes.c_int), ("depth", ctypes.c_int), + ("visual", ctypes.c_void_p), ("root", Window), + ("class", ctypes.c_int), ("bit_gravity", ctypes.c_int), + ("win_gravity", ctypes.c_int), ("backing_store", ctypes.c_int), + ("backing_planes", ctypes.c_ulong), ("backing_pixel", ctypes.c_ulong), + ("save_under", ctypes.c_int), ("colormap", ctypes.c_ulong), + ("map_installed", ctypes.c_int), ("map_state", ctypes.c_int), + ("all_event_masks", ctypes.c_long), ("your_event_mask", ctypes.c_long), + ("do_not_propagate_mask", ctypes.c_long), ("override_redirect", ctypes.c_int), + ("screen", ctypes.c_void_p), + ] + + +X11.XOpenDisplay.argtypes = [ctypes.c_char_p] +X11.XOpenDisplay.restype = Display_p +X11.XCloseDisplay.argtypes = [Display_p] +X11.XDefaultRootWindow.argtypes = [Display_p] +X11.XDefaultRootWindow.restype = Window +X11.XDefaultScreen.argtypes = [Display_p] +X11.XDefaultScreen.restype = ctypes.c_int +X11.XInternAtom.argtypes = [Display_p, ctypes.c_char_p, ctypes.c_int] +X11.XInternAtom.restype = Atom +X11.XGetSelectionOwner.argtypes = [Display_p, Atom] +X11.XGetSelectionOwner.restype = Window +X11.XGetWindowProperty.argtypes = [ + Display_p, Window, Atom, ctypes.c_long, ctypes.c_long, ctypes.c_int, Atom, + ctypes.POINTER(Atom), ctypes.POINTER(ctypes.c_int), + ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), +] +X11.XGetWindowProperty.restype = ctypes.c_int +X11.XFree.argtypes = [ctypes.c_void_p] +X11.XFetchName.argtypes = [Display_p, Window, ctypes.POINTER(ctypes.c_char_p)] +X11.XFetchName.restype = ctypes.c_int +X11.XCreateSimpleWindow.argtypes = [ + Display_p, Window, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, + ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong, +] +X11.XCreateSimpleWindow.restype = Window +X11.XMapWindow.argtypes = [Display_p, Window] +X11.XDestroyWindow.argtypes = [Display_p, Window] +X11.XGetWindowAttributes.argtypes = [Display_p, Window, ctypes.POINTER(XWindowAttributes)] +X11.XGetWindowAttributes.restype = ctypes.c_int +X11.XSync.argtypes = [Display_p, ctypes.c_int] + + +def pick_display(): + for d in range(70, 120): + if not os.path.exists(f"/tmp/.X{d}-lock") and not os.path.exists(f"/tmp/.X11-unix/X{d}"): + return f":{d}" + return ":95" + + +def wait_until(pred, timeout=6.0, interval=0.05): + end = time.monotonic() + timeout + while time.monotonic() < end: + res = pred() + if res: + return res + time.sleep(interval) + return None + + +def terminate(proc): + if proc and proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=3) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=2) + + +def get_win_prop_ulong(dpy, win, atom_name): + atom = X11.XInternAtom(dpy, atom_name.encode(), 0) + da = Atom() + di = ctypes.c_int() + n = ctypes.c_ulong() + dl = ctypes.c_ulong() + prop = ctypes.POINTER(ctypes.c_ubyte)() + rc = X11.XGetWindowProperty( + dpy, win, atom, 0, 1, 0, 0, + ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop), + ) + val = None + if rc == 0 and prop and di.value == 32 and n.value >= 1: + val = int(ctypes.cast(prop, ctypes.POINTER(ctypes.c_ulong))[0]) + if prop: + X11.XFree(prop) + return val + + +def get_win_prop_str(dpy, win, atom_name): + atom = X11.XInternAtom(dpy, atom_name.encode(), 0) + da = Atom() + di = ctypes.c_int() + n = ctypes.c_ulong() + dl = ctypes.c_ulong() + prop = ctypes.POINTER(ctypes.c_ubyte)() + rc = X11.XGetWindowProperty( + dpy, win, atom, 0, 256, 0, 0, + ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop), + ) + out = None + if rc == 0 and prop and di.value == 8 and n.value > 0: + out = bytes(prop[i] for i in range(n.value)).decode("utf-8", errors="ignore").rstrip("\x00") + if prop: + X11.XFree(prop) + return out + + +def make_env(tmp, disp): + home = os.path.join(tmp, "home") + xdg_home = os.path.join(home, ".config") + # Provide an isolated bin dir with anode binaries but without long-lived daemons interfering + bin_dir = os.path.join(tmp, "bin") + os.makedirs(xdg_home, exist_ok=True) + os.makedirs(bin_dir, exist_ok=True) + os.symlink(DWM_BIN, os.path.join(bin_dir, "dwm")) + os.symlink(os.path.join(ROOT, "scripts", "anode-session"), os.path.join(bin_dir, "anode-session")) + os.symlink(os.path.join(ROOT, "scripts", "anode-replace"), os.path.join(bin_dir, "anode-replace")) + os.symlink(os.path.join(ROOT, "scripts", "anode-apply-scale"), os.path.join(bin_dir, "anode-apply-scale")) + os.symlink(os.path.join(ROOT, "scripts", "anode-apply-theme"), os.path.join(bin_dir, "anode-apply-theme")) + + env = dict(os.environ) + env["DISPLAY"] = disp + env["HOME"] = home + env["XDG_CONFIG_HOME"] = xdg_home + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["ANODE_NO_DBUS"] = "1" + env["PATH"] = bin_dir + ":" + env.get("PATH", "/usr/bin:/bin") + for k in ( + "WAYLAND_DISPLAY", "SWAYSOCK", "HYPRLAND_INSTANCE_SIGNATURE", "I3SOCK", + "KDE_FULL_SESSION", "GNOME_DESKTOP_SESSION_ID", + ): + env.pop(k, None) + return env + + +def kill_pid_and_wait(pid): + if not pid or pid <= 1: + return + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + return + for _ in range(30): + try: + os.kill(pid, 0) + time.sleep(0.05) + except ProcessLookupError: + return + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def test_fastfetch_identity(): + disp = pick_display() + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp) + env["XDG_CURRENT_DESKTOP"] = "ANODE" + env["XDG_SESSION_DESKTOP"] = "anode" + env["DESKTOP_SESSION"] = "anode" + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dwm = None + dpy = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy, f"Xvfb failed on {disp}" + root = X11.XDefaultRootWindow(dpy) + scr = X11.XDefaultScreen(dpy) + wm_sel = X11.XInternAtom(dpy, f"WM_S{scr}".encode(), 0) + + dwm = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + wmcheck = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0) + assert wmcheck, "dwm did not publish _NET_SUPPORTING_WM_CHECK" + assert get_win_prop_str(dpy, wmcheck, "_NET_WM_NAME") == "ANODE WM" + assert get_win_prop_ulong(dpy, wmcheck, "_NET_WM_PID") == dwm.pid + assert X11.XGetSelectionOwner(dpy, wm_sel) == wmcheck + + nm = ctypes.c_char_p() + assert X11.XFetchName(dpy, wmcheck, ctypes.byref(nm)) and nm.value == b"ANODE WM" + X11.XFree(nm) + + if shutil.which("fastfetch"): + r = subprocess.run( + ["fastfetch", "--format", "json", "--structure", "DE:WM"], + env=env, capture_output=True, text=True, check=True, + ) + data = json.loads(r.stdout) + mods = {item["type"]: item.get("result", {}) for item in data} + assert mods.get("DE", {}).get("prettyName") == "ANODE", f"unexpected DE: {data}" + assert mods.get("WM", {}).get("prettyName") == "ANODE WM", f"unexpected WM: {data}" + finally: + terminate(dwm) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def test_icccm_replace_and_client_preservation(): + disp = pick_display() + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp) + env["XDG_CURRENT_DESKTOP"] = "XFCE" + env["KDE_FULL_SESSION"] = "true" + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dwm1 = None + dpy = None + new_pid = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy + root = X11.XDefaultRootWindow(dpy) + + dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0) + assert wm1 + + client = X11.XCreateSimpleWindow(dpy, root, 40, 40, 300, 200, 0, 0, 0xffffff) + X11.XMapWindow(dpy, client) + X11.XSync(dpy, 0) + + dry = subprocess.run([REPLACE_BIN, "--dry-run"], env=env, capture_output=True, text=True) + assert dry.returncode == 0, dry.stderr + assert "ANODE WM" in dry.stdout + + rep = subprocess.run( + [REPLACE_BIN, "--no-autostart", "--keep-panels"], + env=env, capture_output=True, text=True, + ) + assert rep.returncode == 0, f"anode-replace failed: stdout={rep.stdout} stderr={rep.stderr}" + assert "DE: ANODE, WM: ANODE WM" in rep.stdout + + # Original dwm must exit cleanly via SelectionClear + assert wait_until(lambda: dwm1.poll() is not None, timeout=5.0), "old dwm did not exit on SelectionClear" + assert dwm1.returncode == 0, f"old dwm exited non-zero: {dwm1.returncode}" + + wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK") + assert wm2 and wm2 != wm1, f"expected new _NET_SUPPORTING_WM_CHECK window (wm1={wm1}, wm2={wm2})" + assert get_win_prop_str(dpy, wm2, "_NET_WM_NAME") == "ANODE WM" + new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID") + assert new_pid and new_pid != dwm1.pid + + # Mapped client window must survive replacement + attr = XWindowAttributes() + assert X11.XGetWindowAttributes(dpy, client, ctypes.byref(attr)) != 0 + X11.XDestroyWindow(dpy, client) + finally: + terminate(dwm1) + kill_pid_and_wait(new_pid) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def test_non_icccm_wm_fallback_replace(): + disp = pick_display() + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp) + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + mock_wm = None + dpy = None + new_pid = None + mock_code = ( + "import ctypes, ctypes.util, os, signal, time\n" + "X11 = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6')\n" + "X11.XOpenDisplay.restype = ctypes.c_void_p\n" + "X11.XDefaultRootWindow.argtypes = [ctypes.c_void_p]\n" + "X11.XDefaultRootWindow.restype = ctypes.c_ulong\n" + "X11.XSelectInput.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_long]\n" + "X11.XCreateSimpleWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong]\n" + "X11.XCreateSimpleWindow.restype = ctypes.c_ulong\n" + "X11.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]\n" + "X11.XInternAtom.restype = ctypes.c_ulong\n" + "X11.XChangeProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]\n" + "X11.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]\n" + "dpy = X11.XOpenDisplay(None)\n" + "root = X11.XDefaultRootWindow(dpy)\n" + "X11.XSelectInput(dpy, root, 1 << 20)\n" + "w = X11.XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0)\n" + "a_chk = X11.XInternAtom(dpy, b'_NET_SUPPORTING_WM_CHECK', 0)\n" + "a_nm = X11.XInternAtom(dpy, b'_NET_WM_NAME', 0)\n" + "a_pid = X11.XInternAtom(dpy, b'_NET_WM_PID', 0)\n" + "a_utf = X11.XInternAtom(dpy, b'UTF8_STRING', 0)\n" + "a_win = X11.XInternAtom(dpy, b'WINDOW', 0)\n" + "a_card = X11.XInternAtom(dpy, b'CARDINAL', 0)\n" + "wv = ctypes.c_ulong(w)\n" + "pv = ctypes.c_ulong(os.getpid())\n" + "X11.XChangeProperty(dpy, w, a_chk, a_win, 32, 0, ctypes.byref(wv), 1)\n" + "X11.XChangeProperty(dpy, w, a_nm, a_utf, 8, 0, b'LegacyWM', 8)\n" + "X11.XChangeProperty(dpy, w, a_pid, a_card, 32, 0, ctypes.byref(pv), 1)\n" + "X11.XChangeProperty(dpy, root, a_chk, a_win, 32, 0, ctypes.byref(wv), 1)\n" + "X11.XSync(dpy, 0)\n" + "signal.signal(signal.SIGTERM, lambda s, f: os._exit(0))\n" + "while True: time.sleep(0.2)\n" + ) + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy + root = X11.XDefaultRootWindow(dpy) + + mock_wm = subprocess.Popen([sys.executable, "-c", mock_code], env=env) + wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0) + assert wm1 + assert get_win_prop_str(dpy, wm1, "_NET_WM_NAME") == "LegacyWM" + + rep = subprocess.run( + [REPLACE_BIN, "--no-autostart", "--keep-panels"], + env=env, capture_output=True, text=True, + ) + assert rep.returncode == 0, f"fallback replace failed: stdout={rep.stdout} stderr={rep.stderr}" + assert wait_until(lambda: mock_wm.poll() is not None, timeout=3.0), "legacy WM was not stopped" + + wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK") + assert wm2 and wm2 != wm1 + assert get_win_prop_str(dpy, wm2, "_NET_WM_NAME") == "ANODE WM" + new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID") + finally: + terminate(mock_wm) + kill_pid_and_wait(new_pid) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def main(): + if not shutil.which("Xvfb"): + print("test_replace: Xvfb not installed (skipping)") + return 0 + assert os.path.isfile(DWM_BIN), f"missing {DWM_BIN}" + test_fastfetch_identity() + test_icccm_replace_and_client_preservation() + test_non_icccm_wm_fallback_replace() + print("test_replace: OK") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_units.c b/tests/test_units.c index 7933709..6ccf727 100644 --- a/tests/test_units.c +++ b/tests/test_units.c @@ -12,6 +12,7 @@ #include "anode_wifi_list.h" #include "anode_bt_list.h" #include "anode_power_policy.h" +#include "anode_xkb_parse.h" #include "anode-touch-gesture.h" static void test_scale_math(void) { @@ -180,6 +181,50 @@ static void test_power_policy_and_gestures(void) { assert(anode_touch_finish(&tr, 1750, 500, 3200, 1920, 1080, 1.0) == ANODE_GEST_CONTROL); } +static void test_xkb_layout_parser(void) { + char buf[16]; + + assert(anode_xkb_layout_from_symbols("pc+us+inet(evdev)", 0, buf, sizeof(buf))); + assert(strcmp(buf, "us") == 0); + + const char *multi = "pc+us+de(nodeadkeys):2+ru(phonetic):3+inet(evdev)+group(alt_shift_toggle)"; + assert(anode_xkb_layout_from_symbols(multi, 0, buf, sizeof(buf))); + assert(strcmp(buf, "us") == 0); + assert(anode_xkb_layout_from_symbols(multi, 1, buf, sizeof(buf))); + assert(strcmp(buf, "de") == 0); + assert(anode_xkb_layout_from_symbols(multi, 2, buf, sizeof(buf))); + assert(strcmp(buf, "ru") == 0); + assert(!anode_xkb_layout_from_symbols(multi, 3, buf, sizeof(buf))); + + assert(anode_xkb_layout_from_symbols("pc+US(intl)+FR(oss):2+inet(evdev)", 0, buf, sizeof(buf))); + assert(strcmp(buf, "us") == 0); + assert(anode_xkb_layout_from_symbols("pc+US(intl)+FR(oss):2+inet(evdev)", 1, buf, sizeof(buf))); + assert(strcmp(buf, "fr") == 0); + + assert(anode_xkb_layout_from_symbols("pc+nec_vndr/jp+sun_vndr/us:2+inet(evdev)", 0, buf, sizeof(buf))); + assert(strcmp(buf, "jp") == 0); + assert(anode_xkb_layout_from_symbols("pc+nec_vndr/jp+sun_vndr/us:2+inet(evdev)", 1, buf, sizeof(buf))); + assert(strcmp(buf, "us") == 0); + + assert(anode_xkb_layout_from_symbols("pc+eurosign(e):2+ua:2+inet(evdev)", 1, buf, sizeof(buf))); + assert(strcmp(buf, "ua") == 0); + + static const unsigned char rules_prop[] = "evdev\0pc105\0US,de,UA\0,nodeadkeys,\0grp:alt_shift_toggle\0"; + assert(anode_xkb_layout_from_rules_prop(rules_prop, sizeof(rules_prop), 0, buf, sizeof(buf))); + assert(strcmp(buf, "us") == 0); + assert(anode_xkb_layout_from_rules_prop(rules_prop, sizeof(rules_prop), 1, buf, sizeof(buf))); + assert(strcmp(buf, "de") == 0); + assert(anode_xkb_layout_from_rules_prop(rules_prop, sizeof(rules_prop), 2, buf, sizeof(buf))); + assert(strcmp(buf, "ua") == 0); + assert(!anode_xkb_layout_from_rules_prop(rules_prop, sizeof(rules_prop), 3, buf, sizeof(buf))); + + assert(anode_xkb_layout_from_group_name("English (US)", buf, sizeof(buf))); + assert(strcmp(buf, "en") == 0); + assert(anode_xkb_layout_from_group_name("Russian", buf, sizeof(buf))); + assert(strcmp(buf, "ru") == 0); + assert(!anode_xkb_layout_from_group_name("!!!", buf, sizeof(buf))); +} + static void test_platform_probe(void) { anode_net_iface_t ifs[ANODE_MAX_IFACES]; int n = anode_list_net_ifaces(ifs, ANODE_MAX_IFACES); @@ -201,6 +246,7 @@ int main(void) { test_audio_parsers(); test_wifi_and_bt_parsers(); test_power_policy_and_gestures(); + test_xkb_layout_parser(); test_platform_probe(); printf("test_units: ALL PASSED\n"); return 0; diff --git a/tests/test_x11_xvfb.py b/tests/test_x11_xvfb.py index c8f8aa4..dd91d6e 100755 --- a/tests/test_x11_xvfb.py +++ b/tests/test_x11_xvfb.py @@ -4,6 +4,7 @@ import ctypes import ctypes.util import os +import re import shutil import signal import socket @@ -101,6 +102,8 @@ X11.XGetWMHints.argtypes = [Display_p, Window] X11.XGetWMHints.restype = ctypes.POINTER(XWMHints) X11.XFetchName.argtypes = [Display_p, Window, ctypes.POINTER(ctypes.c_char_p)] X11.XFetchName.restype = ctypes.c_int +X11.XkbLockGroup.argtypes = [Display_p, ctypes.c_uint, ctypes.c_uint] +X11.XkbLockGroup.restype = ctypes.c_int def pick_display(): @@ -270,10 +273,11 @@ def test_resolution(res_str, scale_str, width, height): assert wait_until(lambda: (lambda w: w if w and len(w) >= 4 and w[3] < wa0[3] else None)(get_cardinal_prop(dpy, root, "_NET_WORKAREA"))), "Workarea did not re-reserve on vkbd show" terminate(vkbd) - # Test anode-statusd updates root WM_NAME + # Test anode-statusd updates root WM_NAME and tracks XKB layout left of datetime sd = subprocess.Popen([os.path.join(BUILD, "daemons", "anode-statusd")], env=env) procs.append(sd) - def has_status(): + + def get_status(): nm = ctypes.c_char_p() if X11.XFetchName(dpy, root, ctypes.byref(nm)) and nm.value: s = nm.value.decode("utf-8", errors="ignore") @@ -281,7 +285,38 @@ def test_resolution(res_str, scale_str, width, height): if "|" in s: return s return None - assert wait_until(has_status), "anode-statusd did not publish status to root WM_NAME" + + def get_kbd_left_of_dt(): + s = get_status() + if not s: + return None + parts = [p.strip() for p in s.split("|")] + if len(parts) < 4: + return None + if not re.fullmatch(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}", parts[-1]): + return None + kbd = parts[-2] + if not kbd or not kbd.isascii() or not kbd.isalnum() or kbd != kbd.lower(): + return None + return kbd + + init_kbd = wait_until(get_kbd_left_of_dt) + assert init_kbd, f"anode-statusd missing lowercase XKB layout left of datetime: {get_status()!r}" + if shutil.which("setxkbmap"): + subprocess.run( + ["setxkbmap", "-layout", "us,de,ru", "-variant", ",nodeadkeys,"], + env=env, check=True, + ) + assert wait_until(lambda: get_kbd_left_of_dt() == "us"), f"Expected 'us': {get_status()!r}" + X11.XkbLockGroup(dpy, 0x0100, 1) + X11.XSync(dpy, 0) + assert wait_until(lambda: get_kbd_left_of_dt() == "de"), f"Expected 'de': {get_status()!r}" + X11.XkbLockGroup(dpy, 0x0100, 2) + X11.XSync(dpy, 0) + assert wait_until(lambda: get_kbd_left_of_dt() == "ru"), f"Expected 'ru': {get_status()!r}" + X11.XkbLockGroup(dpy, 0x0100, 0) + X11.XSync(dpy, 0) + assert wait_until(lambda: get_kbd_left_of_dt() == "us"), f"Expected 'us' restore: {get_status()!r}" terminate(sd) # Test core + GemUI utilities launch, map cleanly inside screen, and exit cleanly