From 07d9134d2dda7f951e9a33c6d404ba2a5620f325 Mon Sep 17 00:00:00 2001 From: Luxferre Date: Thu, 26 Nov 2026 14:46:03 +0200 Subject: [PATCH] feat: improve session switching, fractional DPI/GTK theming, XDG launcher, CPU/RAM status, and power policy --- Makefile | 17 +- data/env.sh | 32 +++ scripts/anode-apply-scale | 71 +++-- scripts/anode-apply-theme | 89 ++++++- scripts/anode-autostart | 33 ++- scripts/anode-launcher | 459 +++++++++++++++++++++++++++++--- scripts/anode-replace | 282 +++++++++++++++++--- scripts/anode-session | 29 +- scripts/anode-sync-dunst-theme | 25 +- scripts/anode-sync-gtk-theme | 180 +++++++++---- src/apps/anode-display.c | 7 +- src/common/anode_plat.c | 127 ++++++++- src/common/anode_plat.h | 6 + src/common/anode_power_policy.h | 13 +- src/common/anode_scale.h | 9 +- src/common/anode_sys_parse.h | 126 +++++++++ src/daemons/anode-checkpw.c | 61 +++++ src/daemons/anode-powerd.c | 67 ++++- src/daemons/anode-statusd.c | 125 ++++----- src/dmenu/dmenu.c | 17 +- src/dwm/dwm.c | 69 ++++- src/st/x.c | 50 +++- tests/test_autostart.py | 45 ++++ tests/test_launcher.py | 174 ++++++++++++ tests/test_replace.py | 425 ++++++++++++++++++++++++++++- tests/test_theme_scale.py | 221 ++++++++++++++- tests/test_units.c | 60 ++++- tests/test_x11_xvfb.py | 153 ++++++++++- 28 files changed, 2670 insertions(+), 302 deletions(-) create mode 100644 src/common/anode_sys_parse.h create mode 100755 tests/test_launcher.py diff --git a/Makefile b/Makefile index ad0db13..e92ca36 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,7 @@ PREFIX = /usr/local MANPREFIX = $(PREFIX)/share/man +XSESSIONSDIR = $(PREFIX)/share/xsessions DESTDIR = CC = cc CXX = c++ @@ -27,7 +28,7 @@ build/flags.sh: scripts/detect-env.sh CC="$(CC)" CXX="$(CXX)" PKG_CONFIG="$(PKG_CONFIG)" WITH_GTKTTK="$(WITH_GTKTTK)" sh scripts/detect-env.sh build/flags.sh # --- Common platform abstraction --- -build/common/anode_plat.o: src/common/anode_plat.c src/common/anode_plat.h build/flags.sh +build/common/anode_plat.o: src/common/anode_plat.c src/common/anode_plat.h src/common/anode_sys_parse.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -Wextra -fPIC -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" -c src/common/anode_plat.c -o build/common/anode_plat.o # --- Patched DWM --- @@ -155,7 +156,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 src/common/anode_xkb_parse.h build/flags.sh +build/daemons/anode-statusd.o: src/daemons/anode-statusd.c src/common/anode_plat.h src/common/anode_sys_parse.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 @@ -298,7 +299,7 @@ install: all "$(DESTDIR)$(PREFIX)/include" \ "$(DESTDIR)$(PREFIX)/share/anode/themes" \ "$(DESTDIR)$(PREFIX)/share/anode/autostart.d" \ - "$(DESTDIR)$(PREFIX)/share/xsessions" \ + "$(DESTDIR)$(XSESSIONSDIR)" \ "$(DESTDIR)$(MANPREFIX)/man1" cp -f build/dwm/dwm "$(DESTDIR)$(PREFIX)/bin/dwm" cp -f build/dmenu/dmenu build/dmenu/stest src/dmenu/dmenu_path src/dmenu/dmenu_run "$(DESTDIR)$(PREFIX)/bin/" @@ -329,6 +330,7 @@ install: all "$(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" + if [ "`id -u`" = "0" ] && [ -z "$(DESTDIR)" ]; then chmod 4755 "$(PREFIX)/bin/anode-checkpw" 2>/dev/null || true; fi cp -f build/libgemui/libgemui.so "$(DESTDIR)$(PREFIX)/lib/libgemui.so" chmod 755 "$(DESTDIR)$(PREFIX)/lib/libgemui.so" cp -f src/libgemui/gemui.h "$(DESTDIR)$(PREFIX)/include/gemui.h" @@ -343,8 +345,8 @@ install: all chmod 644 "$(DESTDIR)$(PREFIX)/share/anode/autostart" cp -f src/st/st.info "$(DESTDIR)$(PREFIX)/share/anode/st.info" chmod 644 "$(DESTDIR)$(PREFIX)/share/anode/st.info" - sed "s|@PREFIX@|$(PREFIX)|g" data/anode.desktop > "$(DESTDIR)$(PREFIX)/share/xsessions/anode.desktop" - chmod 644 "$(DESTDIR)$(PREFIX)/share/xsessions/anode.desktop" + sed "s|@PREFIX@|$(PREFIX)|g" data/anode.desktop > "$(DESTDIR)$(XSESSIONSDIR)/anode.desktop" + chmod 644 "$(DESTDIR)$(XSESSIONSDIR)/anode.desktop" sed "s/VERSION/$(DWM_VERSION)/g" src/dwm/dwm.1 > "$(DESTDIR)$(MANPREFIX)/man1/dwm.1" sed "s/VERSION/$(DMENU_VERSION)/g" src/dmenu/dmenu.1 > "$(DESTDIR)$(MANPREFIX)/man1/dmenu.1" sed "s/VERSION/$(DMENU_VERSION)/g" src/dmenu/stest.1 > "$(DESTDIR)$(MANPREFIX)/man1/stest.1" @@ -394,7 +396,7 @@ uninstall: "$(DESTDIR)$(PREFIX)/lib/libgemui.so" \ "$(DESTDIR)$(PREFIX)/include/gemui.h" \ "$(DESTDIR)$(PREFIX)/lib/pkgconfig/gemui.pc" \ - "$(DESTDIR)$(PREFIX)/share/xsessions/anode.desktop" \ + "$(DESTDIR)$(XSESSIONSDIR)/anode.desktop" \ "$(DESTDIR)$(MANPREFIX)/man1/dwm.1" \ "$(DESTDIR)$(MANPREFIX)/man1/dmenu.1" \ "$(DESTDIR)$(MANPREFIX)/man1/stest.1" \ @@ -405,7 +407,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 src/common/anode_xkb_parse.h 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 src/common/anode_sys_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,6 +415,7 @@ test: all build/tests/test_units ./build/tests/test_units python3 tests/test_theme_scale.py python3 tests/test_autostart.py + python3 tests/test_launcher.py python3 tests/test_x11_xvfb.py python3 tests/test_replace.py diff --git a/data/env.sh b/data/env.sh index 166095c..f082b4a 100755 --- a/data/env.sh +++ b/data/env.sh @@ -8,6 +8,38 @@ : "${ANODE_PREFIX:=/usr/local}" export XDG_CONFIG_HOME XDG_DATA_HOME XDG_CACHE_HOME XDG_STATE_HOME ANODE_PREFIX +_anode_xdg_out="" +_anode_append_data_dir() { + _d="$1" + [ -n "$_d" ] || return 0 + case ":$_anode_xdg_out:" in + *":$_d:"*) ;; + *) _anode_xdg_out="${_anode_xdg_out:+$_anode_xdg_out:}$_d" ;; + esac +} +_anode_old_ifs="$IFS" +IFS=: +set -f +for _d in ${XDG_DATA_DIRS:-$ANODE_PREFIX/share:/usr/local/share:/usr/share}; do + _anode_append_data_dir "$_d" +done +set +f +IFS="$_anode_old_ifs" +for _d in \ + "$XDG_DATA_HOME/flatpak/exports/share" \ + "/var/lib/flatpak/exports/share" \ + "/var/lib/snapd/desktop" +do + [ -d "$_d" ] && _anode_append_data_dir "$_d" +done +for _d in "$ANODE_PREFIX/share" "/usr/local/share" "/usr/share"; do + _anode_append_data_dir "$_d" +done +XDG_DATA_DIRS="$_anode_xdg_out" +export XDG_DATA_DIRS +unset _anode_xdg_out _anode_old_ifs _d +unset -f _anode_append_data_dir + # Load active scale settings generated by anode-apply-scale if [ -f "$XDG_CONFIG_HOME/anode/scale.env" ]; then . "$XDG_CONFIG_HOME/anode/scale.env" diff --git a/scripts/anode-apply-scale b/scripts/anode-apply-scale index 128d1e9..718ba05 100755 --- a/scripts/anode-apply-scale +++ b/scripts/anode-apply-scale @@ -57,7 +57,20 @@ done detect_edid_scale() { _dpi="96" - if [ -n "${DISPLAY:-}" ] && command -v xrandr >/dev/null 2>&1; then + if [ -n "${DISPLAY:-}" ] && command -v xdpyinfo >/dev/null 2>&1; then + _xdpy_dpi="$(xdpyinfo 2>/dev/null | awk '/resolution:/ { + split($2, a, "x") + d = a[1] + 0 + if (d >= 48 && d <= 384 && (d < 94 || d > 98)) { + print d + exit + } + }' || true)" + if [ -n "${_xdpy_dpi:-}" ]; then + _dpi="$_xdpy_dpi" + fi + fi + if [ "$_dpi" = "96" ] && [ -n "${DISPLAY:-}" ] && command -v xrandr >/dev/null 2>&1; then _xrandr_dpi="$(xrandr --query 2>/dev/null | awk ' / connected/ { if (match($0, /[0-9]+x[0-9]+/) && match($0, /[0-9]+mm x [0-9]+mm/)) { @@ -82,12 +95,6 @@ detect_edid_scale() { _dpi="$_xrandr_dpi" fi fi - if [ "$_dpi" = "96" ] && [ -n "${DISPLAY:-}" ] && command -v xdpyinfo >/dev/null 2>&1; then - _xdpy_dpi="$(xdpyinfo 2>/dev/null | awk '/resolution:/ { split($2, a, "x"); if (a[1] > 0) { print a[1]; exit } }' || true)" - if [ -n "${_xdpy_dpi:-}" ]; then - _dpi="$_xdpy_dpi" - fi - fi awk -v d="$_dpi" 'BEGIN { s = (d + 0) / 96.0 s = int(s * 20.0 + 0.5) / 20.0 @@ -113,19 +120,27 @@ CALC="$(awk -v raw="$SCALE" -v touch="$TOUCH" 'BEGIN { s = int(s * 100.0 + 0.5) / 100.0 xft_dpi = int(96.0 * s + 0.5) gdk_scale = (s < 1.75) ? 1 : int(s + 0.5) - cur_sz = int(24.0 * s + 0.5) - if (cur_sz < 16) cur_sz = 16 - if (cur_sz > 96) cur_sz = 96 + if (gdk_scale <= 1) gdk_dpi = "1.0" + else if (gdk_scale == 2) gdk_dpi = "0.5" + else if (gdk_scale == 4) gdk_dpi = "0.25" + else gdk_dpi = sprintf("%.3f", 1.0 / gdk_scale) + raw_cur = 24.0 * s + if (raw_cur < 20.0) cur_sz = 16 + else if (raw_cur < 32.0) cur_sz = 24 + else if (raw_cur < 44.0) cur_sz = 32 + else if (raw_cur < 64.0) cur_sz = 48 + else cur_sz = 64 t = (touch == "1" || touch == 1) ? 1 : 0 - printf "%.2f %d %d %d %d\n", s, xft_dpi, gdk_scale, cur_sz, t + printf "%.2f %d %d %s %d %d\n", s, xft_dpi, gdk_scale, gdk_dpi, cur_sz, t }')" set -- $CALC SCALE="$1" XFT_DPI="$2" GDK_SCALE="$3" -XCURSOR_SIZE="$4" -TOUCH="$5" +GDK_DPI_SCALE="$4" +XCURSOR_SIZE="$5" +TOUCH="$6" mkdir -p "$CONF_DIR" @@ -146,7 +161,7 @@ cat > "$TMP_ENV" </dev/null 2>&1; then - anode-apply-theme + ANODE_SCALE="$SCALE" ANODE_TOUCH="$TOUCH" anode-apply-theme + fi +fi + +if [ -n "${DISPLAY:-}" ] && [ "${ANODE_NO_SIGNAL:-0}" != "1" ]; then + if command -v xsetroot >/dev/null 2>&1; then + XCURSOR_SIZE="$XCURSOR_SIZE" xsetroot -cursor_name left_ptr >/dev/null 2>&1 || true + 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 \ + ANODE_SCALE="$SCALE" ANODE_TOUCH="$TOUCH" \ + GDK_SCALE="$GDK_SCALE" GDK_DPI_SCALE="$GDK_DPI_SCALE" \ + QT_SCALE_FACTOR="$SCALE" XCURSOR_SIZE="$XCURSOR_SIZE" >/dev/null 2>&1 || \ + dbus-update-activation-environment \ + ANODE_SCALE="$SCALE" ANODE_TOUCH="$TOUCH" \ + GDK_SCALE="$GDK_SCALE" GDK_DPI_SCALE="$GDK_DPI_SCALE" \ + QT_SCALE_FACTOR="$SCALE" XCURSOR_SIZE="$XCURSOR_SIZE" >/dev/null 2>&1 || true + fi + if command -v systemctl >/dev/null 2>&1; then + systemctl --user set-environment \ + ANODE_SCALE="$SCALE" ANODE_TOUCH="$TOUCH" \ + GDK_SCALE="$GDK_SCALE" GDK_DPI_SCALE="$GDK_DPI_SCALE" \ + QT_SCALE_FACTOR="$SCALE" XCURSOR_SIZE="$XCURSOR_SIZE" >/dev/null 2>&1 || true + fi fi fi diff --git a/scripts/anode-apply-theme b/scripts/anode-apply-theme index f4a5d62..8dc6d6b 100755 --- a/scripts/anode-apply-theme +++ b/scripts/anode-apply-theme @@ -54,13 +54,16 @@ if [ -z "$XTH_FILE" ] || [ ! -r "$XTH_FILE" ]; then exit 1 fi -SCALE="1.00" -TOUCH="0" +SCALE="" +TOUCH="" if [ -f "$SCALE_CONF" ]; then . "$SCALE_CONF" +else + if [ -n "${ANODE_SCALE:-}" ]; then SCALE="$ANODE_SCALE"; fi + if [ -n "${ANODE_TOUCH:-}" ]; then TOUCH="$ANODE_TOUCH"; fi fi -if [ -n "${ANODE_SCALE:-}" ]; then SCALE="$ANODE_SCALE"; fi -if [ -n "${ANODE_TOUCH:-}" ]; then TOUCH="$ANODE_TOUCH"; fi +: "${SCALE:=1.00}" +: "${TOUCH:=0}" THEME_NAME="$(awk -F: '/^theme\.name[[:space:]]*:/ { sub(/^[[:space:]]+/, "", $2); print $2; exit }' "$XTH_FILE" || true)" if [ -z "$THEME_NAME" ]; then @@ -68,6 +71,54 @@ if [ -z "$THEME_NAME" ]; then fi mkdir -p "$CONF_DIR" +LOCAL_XRES="$CONF_DIR/Xresources.local" +PRESERVED_ST="" +if [ -r "$HOME/.Xresources" ]; then + _lfile_arg="" + if [ -r "$LOCAL_XRES" ]; then + _lfile_arg="$LOCAL_XRES" + fi + PRESERVED_ST="$(awk -v lfile="$_lfile_arg" ' + function trim(s) { + gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s) + return s + } + BEGIN { + if (lfile != "") { + while ((getline line < lfile) > 0) { + sl = trim(line) + if (sl == "" || substr(sl, 1, 1) == "!" || substr(sl, 1, 1) == "#") continue + pl = index(sl, ":") + if (pl > 0) { + kl = trim(substr(sl, 1, pl - 1)) + local_keys[kl] = 1 + } + } + close(lfile) + } + } + /^[ \t]*![ \t]*User overrides from Xresources\.local/ { exit } + { + s = trim($0) + if (s == "" || substr(s, 1, 1) == "!" || substr(s, 1, 1) == "#") next + p = index(s, ":") + if (p > 0) { + k = trim(substr(s, 1, p - 1)) + if (substr(k, 1, 3) == "St." && !(k in local_keys)) { + if (!(k in seen)) { + seen[k] = 1 + order[++n] = k + } + lines[k] = s + } + } + } + END { + for (i = 1; i <= n; i++) print lines[order[i]] + } + ' "$HOME/.Xresources" 2>/dev/null || true)" +fi + TMP_XRES="$HOME/.Xresources.tmp.$$" awk -v scale_str="$SCALE" -v touch_str="$TOUCH" -v tname="$THEME_NAME" ' @@ -118,17 +169,20 @@ END { if (scaled_font_px < 8) scaled_font_px = 8 if (scaled_font_px > 96) scaled_font_px = 96 - scaled_cur = rint(cur_sz * s) - if (scaled_cur < 16) scaled_cur = 16 - if (scaled_cur > 96) scaled_cur = 96 + raw_cur = cur_sz * s + if (raw_cur < 20.0) scaled_cur = 16 + else if (raw_cur < 32.0) scaled_cur = 24 + else if (raw_cur < 44.0) scaled_cur = 32 + else if (raw_cur < 64.0) scaled_cur = 48 + else scaled_cur = 64 scaled_bw = rint(bw * s) if (scaled_bw < 1) scaled_bw = 1 if (scaled_bw > 10) scaled_bw = 10 - scaled_dm_lh = rint(36.0 * s) - if (scaled_dm_lh < 22) scaled_dm_lh = 22 - if (t == 1 && scaled_dm_lh < rint(44.0 * s)) scaled_dm_lh = rint(44.0 * s) + scaled_dm_lh = rint(26.0 * s) + if (scaled_dm_lh < 20) scaled_dm_lh = 20 + if (t == 1 && scaled_dm_lh < rint(36.0 * s)) scaled_dm_lh = rint(36.0 * s) font_face = ("theme.fontFace" in vals && vals["theme.fontFace"] != "") ? vals["theme.fontFace"] : "Fira Code" icon_face = ("theme.iconFontFace" in vals && vals["theme.iconFontFace"] != "") ? vals["theme.iconFontFace"] : "DejaVuSansM Nerd Font" @@ -185,6 +239,21 @@ END { } ' "$XTH_FILE" > "$TMP_XRES" +if [ -n "${PRESERVED_ST:-}" ]; then + { + printf '\n! Preserved user St.* overrides\n' + printf '%s\n' "$PRESERVED_ST" + } >> "$TMP_XRES" +fi + +if [ -r "$LOCAL_XRES" ]; then + { + printf '\n! User overrides from Xresources.local\n' + cat "$LOCAL_XRES" + printf '\n' + } >> "$TMP_XRES" +fi + mv -f "$TMP_XRES" "$HOME/.Xresources" TMP_TC="$THEME_CONF.tmp.$$" diff --git a/scripts/anode-autostart b/scripts/anode-autostart index 3b1b20b..66034ea 100755 --- a/scripts/anode-autostart +++ b/scripts/anode-autostart @@ -142,19 +142,38 @@ is_proc_running() { _tgt="$1" [ -n "$_tgt" ] || return 1 _self="$$" - (ps -eo pid=,comm=,args= 2>/dev/null || ps -ax -o pid=,comm=,args= 2>/dev/null || true) | awk -v tgt="$_tgt" -v self="$_self" ' + _my_uid="$(id -u)" + _cands="$( (ps -eo uid=,pid=,comm=,args= 2>/dev/null || ps -ax -o uid=,pid=,comm=,args= 2>/dev/null || true) | awk -v tgt="$_tgt" -v self="$_self" -v myuid="$_my_uid" ' { - pid = $1; comm = $2; arg1 = $3 - if (pid == self) next + uid = $1; pid = $2; comm = $3; arg1 = $4 + if (uid != myuid || pid == self) next sub(/^.*\//, "", comm) sub(/^.*\//, "", arg1) if (comm == tgt || arg1 == tgt) { - found = 1 - exit 0 + print pid } } - END { exit found ? 0 : 1 } - ' + ' )" + [ -n "${_cands:-}" ] || return 1 + + _cur_sid="${XDG_SESSION_ID:-}" + _cur_dbus="${DBUS_SESSION_BUS_ADDRESS:-}" + for _cpid in $_cands; do + if [ -r "/proc/$_cpid/environ" ] && { [ -n "$_cur_sid" ] || [ -n "$_cur_dbus" ]; }; then + _penv="$(tr '\0' '\n' < "/proc/$_cpid/environ" 2>/dev/null || true)" + _p_sid="$(printf '%s\n' "$_penv" | awk 'substr($0, 1, 15) == "XDG_SESSION_ID=" { print substr($0, 16); exit }')" + _p_dbus="$(printf '%s\n' "$_penv" | awk 'substr($0, 1, 25) == "DBUS_SESSION_BUS_ADDRESS=" { print substr($0, 26); exit }')" + if [ -n "$_cur_sid" ] && [ -n "${_p_sid:-}" ] && [ "$_p_sid" != "$_cur_sid" ]; then + continue + fi + if [ -n "$_cur_dbus" ] && [ -n "${_p_dbus:-}" ] && [ "$_p_dbus" != "$_cur_dbus" ]; then + continue + fi + return 0 + fi + return 0 + done + return 1 } launch_cmd() { diff --git a/scripts/anode-launcher b/scripts/anode-launcher index 7b5ff37..c2dc63c 100755 --- a/scripts/anode-launcher +++ b/scripts/anode-launcher @@ -1,64 +1,439 @@ #!/bin/sh -# ANODE dynamic launcher using patched dmenu (strict POSIX sh) +# ANODE dynamic XDG Desktop Entry & app launcher using patched dmenu (strict POSIX sh) set -u +usage() { + cat <<'EOF' +Usage: anode-launcher [--list] [-h|--help] + +Options: + --list Print resolved "labelworkdirtermcmd" entries and exit + -h, --help Show this help +EOF +} + +LIST_ONLY=0 +while [ $# -gt 0 ]; do + case "$1" in + --list) + LIST_ONLY=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + printf 'anode-launcher: unknown argument: %s\n' "$1" >&2 + exit 2 + ;; + esac +done + : "${XDG_DATA_HOME:=$HOME/.local/share}" +: "${XDG_CACHE_HOME:=$HOME/.cache}" +: "${XDG_CURRENT_DESKTOP:=ANODE}" : "${ANODE_PREFIX:=/usr/local}" -CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/anode" +CACHE_DIR="$XDG_CACHE_HOME/anode" mkdir -p "$CACHE_DIR" +MANIFEST_TMP="$CACHE_DIR/launcher-manifest.$$" +XDG_TMP="$CACHE_DIR/launcher-xdg.$$" APPS_TMP="$CACHE_DIR/launcher-apps.$$" -cleanup() { rm -f "$APPS_TMP"; } +cleanup() { rm -f "$MANIFEST_TMP" "$XDG_TMP" "$APPS_TMP"; } trap cleanup EXIT INT TERM -{ - printf 'Terminal\tst\n' - printf 'Control Center & Power\tanode-power\n' - printf 'Network & Wi-Fi\tanode-net\n' - printf 'Audio & Volume\tanode-audio\n' - printf 'Display & Scaling\tanode-display\n' - printf 'Date & Timezone\tanode-datetime\n' - printf 'Themes & Fonts\tanode-themes\n' - printf 'Virtual Keyboard Toggle\tanode-media-key vkbd-toggle\n' - printf 'Lock Screen\tanode-lock\n' +NEWLINE="$(printf '\n_')" +NEWLINE="${NEWLINE%_}" +TAB="$(printf '\t')" +APP_DIRS_NL="" - IFS=: - for _base in "$XDG_DATA_HOME" "${XDG_DATA_DIRS:-$ANODE_PREFIX/share:/usr/local/share:/usr/share}"; do - _dir="$_base/applications" - [ -d "$_dir" ] || continue - for _f in "$_dir"/*.desktop; do - [ -f "$_f" ] || continue - awk ' - /^\[Desktop Entry\]/ { in_entry=1; next } - /^\[/ { in_entry=0 } - in_entry && /^Name=/ && !name { sub(/^Name=/, ""); name=$0 } - in_entry && /^Exec=/ && !exec_cmd { sub(/^Exec=/, ""); exec_cmd=$0 } - in_entry && /^NoDisplay=true/ { hidden=1 } - in_entry && /^Terminal=true/ { isterm=1 } - END { - if (!hidden && name != "" && exec_cmd != "") { - gsub(/%[fFuUdDnNickvm]/, "", exec_cmd) - gsub(/^[ \t]+|[ \t]+$/, "", exec_cmd) - if (isterm) printf "%s (term)\tst -e %s\n", name, exec_cmd - else printf "%s\t%s\n", name, exec_cmd - } - } - ' "$_f" - done +append_app_dir() { + _b="$1" + while :; do + case "$_b" in + */) [ "$_b" = "/" ] && break; _b="${_b%/}" ;; + *) break ;; + esac done - unset IFS + [ -n "$_b" ] || return 0 + case "$_b" in + */applications) _ad="$_b" ;; + *) _ad="$_b/applications" ;; + esac + [ -d "$_ad" ] || return 0 + case "$NEWLINE$APP_DIRS_NL$NEWLINE" in + *"$NEWLINE$_ad$NEWLINE"*) return 0 ;; + esac + APP_DIRS_NL="${APP_DIRS_NL:+$APP_DIRS_NL$NEWLINE}$_ad" +} + +append_app_dir "$XDG_DATA_HOME" + +OLD_IFS="$IFS" +IFS=: +set -f +for _base in ${XDG_DATA_DIRS:-$ANODE_PREFIX/share:/usr/local/share:/usr/share}; do + append_app_dir "$_base" +done +set +f +IFS="$OLD_IFS" + +for _fb in \ + "$XDG_DATA_HOME/flatpak/exports/share" \ + "/var/lib/flatpak/exports/share" \ + "/var/lib/snapd/desktop" \ + "$ANODE_PREFIX/share" \ + "/usr/local/share" \ + "/usr/share" +do + append_app_dir "$_fb" +done + +check_try_exec() { + _te="$1" + [ -n "$_te" ] || return 0 + case "$_te" in + */*) [ -x "$_te" ] && return 0 || return 1 ;; + *) command -v "$_te" >/dev/null 2>&1 && return 0 || return 1 ;; + esac +} + +: > "$MANIFEST_TMP" +OLD_IFS="$IFS" +IFS="$NEWLINE" +for _adir in $APP_DIRS_NL; do + [ -d "$_adir" ] || continue + find "$_adir" \( -type f -o -type l \) -name '*.desktop' 2>/dev/null | LC_ALL=C sort | \ + while IFS= read -r _f; do + [ -n "$_f" ] && [ -f "$_f" ] && [ -r "$_f" ] || continue + _rel="${_f#"$_adir"/}" + case "$_rel" in + */*) _did="$(printf '%s' "$_rel" | tr '/' '-')" ;; + *) _did="$_rel" ;; + esac + printf '%s\t%s\n' "$_did" "$_f" >> "$MANIFEST_TMP" + done +done +IFS="$OLD_IFS" + +RAW_LOC="${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" + +awk -v cur_desk="$XDG_CURRENT_DESKTOP" -v raw_loc="$RAW_LOC" ' +function trim(s) { + gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s) + return s +} +function clean_tab(s) { + gsub(/\t+/, " ", s) + return trim(s) +} +function unescape_xdg(s, out, i, c, nc) { + out = "" + for (i = 1; i <= length(s); i++) { + c = substr(s, i, 1) + if (c == "\\" && i < length(s)) { + nc = substr(s, i + 1, 1) + if (nc == "s") { out = out " "; i++; continue } + if (nc == "n") { out = out " "; i++; continue } + if (nc == "t") { out = out " "; i++; continue } + if (nc == "r") { out = out " "; i++; continue } + if (nc == "\\") { out = out "\\"; i++; continue } + } + out = out c + } + return clean_tab(out) +} +function sh_quote(s, out, pos) { + out = "" + while ((pos = index(s, "\047")) > 0) { + out = out substr(s, 1, pos - 1) "\047\\\047\047" + s = substr(s, pos + 1) + } + return "\047" out s "\047" +} +function replace_lit(s, needle, rep, out, p, nlen) { + out = "" + nlen = length(needle) + while ((p = index(s, needle)) > 0) { + out = out substr(s, 1, p - 1) rep + s = substr(s, p + nlen) + } + return out s +} +function list_matches(list_str, cur_str, na, nb, a, b, i, j) { + na = split(list_str, a, /[;:]/) + nb = split(cur_str, b, /:/) + for (i = 1; i <= na; i++) { + if (a[i] == "") continue + for (j = 1; j <= nb; j++) { + if (b[j] != "" && tolower(a[i]) == tolower(b[j])) return 1 + } + } + return 0 +} +function loc_score(k, kl, lb, rb) { + lb = index(k, "[") + rb = index(k, "]") + if (lb <= 0 || rb <= lb) return 1 + kl = substr(k, lb + 1, rb - lb - 1) + if (kl == "") return 1 + if (loc_full != "" && kl == loc_full) return 5 + if (loc_lc != "" && kl == loc_lc) return 4 + if (loc_lmod != "" && kl == loc_lmod) return 3 + if (loc_lang != "" && kl == loc_lang) return 2 + return 0 +} +function base_key(k, lb) { + lb = index(k, "[") + return (lb > 0) ? substr(k, 1, lb - 1) : k +} +function expand_exec(raw, name, icon, fpath, s, ic_rep) { + s = unescape_xdg(raw) + gsub(/%%/, "\001", s) + gsub(/[ \t]*@@[uUfF]?[ \t]+%[uUfF][ \t]+@@[ \t]*/, " ", s) + gsub(/[ \t]*["\047]?%[fFuUdDnNvm]["\047]?[ \t]*/, " ", s) + if (index(s, "%c") > 0) { + s = replace_lit(s, "%c", sh_quote(name)) + } + if (index(s, "%k") > 0) { + s = replace_lit(s, "%k", sh_quote(fpath)) + } + if (index(s, "%i") > 0) { + ic_rep = (icon != "") ? ("--icon " sh_quote(icon)) : "" + s = replace_lit(s, "%i", ic_rep) + } + s = replace_lit(s, "\001", "%") + return clean_tab(s) +} +function clear_entry_state( i, ak) { + section = "" + dtype = "" + app_name = ""; app_name_sc = 0 + gen_name = ""; gen_name_sc = 0 + exec_raw = ""; try_exec = ""; icon = ""; workdir = "" + nodisplay = ""; hidden = ""; only_in = ""; not_in = "" + terminal = ""; actions_str = ""; dbus_act = "" + for (i = 1; i <= n_act_seen; i++) { + ak = act_seen_list[i] + delete act_name[ak] + delete act_name_sc[ak] + delete act_exec[ak] + delete act_only[ak] + delete act_not[ak] + delete act_icon[ak] + } + for (i = 1; i <= n_act_seen; i++) delete act_seen[act_seen_list[i]] + n_act_seen = 0 +} +BEGIN { + FS = "\t" + n_act_seen = 0 + l = raw_loc + if (l != "" && l != "C" && l != "POSIX") { + sub(/\..*$/, "", l) + loc_full = l + loc_lang = l; sub(/_.*/, "", loc_lang); sub(/@.*/, "", loc_lang) + if (index(l, "@") > 0) { + mod = substr(l, index(l, "@")) + loc_lc = l; sub(/@.*/, "", loc_lc) + loc_lmod = loc_lang mod + } else { + loc_lc = l + loc_lmod = "" + } + } else { + loc_full = ""; loc_lc = ""; loc_lmod = ""; loc_lang = "" + } +} +{ + did = $1 + fpath = $2 + if (did == "" || fpath == "") next + if (did in seen_id) next + seen_id[did] = 1 + + clear_entry_state() + while ((rc = (getline raw < fpath)) > 0) { + s = trim(raw) + if (s == "" || substr(s, 1, 1) == "#") continue + if (substr(s, 1, 1) == "[") { + if (s == "[Desktop Entry]") { + section = "main" + } else if (substr(s, 1, 16) == "[Desktop Action " && substr(s, length(s), 1) == "]") { + aid = substr(s, 17, length(s) - 17) + section = "action:" aid + if (!(aid in act_seen)) { + act_seen[aid] = 1 + act_seen_list[++n_act_seen] = aid + } + } else { + section = "other" + } + continue + } + eq = index(s, "=") + if (eq <= 0) continue + k = trim(substr(s, 1, eq - 1)) + v = trim(substr(s, eq + 1)) + bk = base_key(k) + sc = loc_score(k) + + if (section == "main") { + if (bk == "Type" && k == "Type") dtype = v + else if (bk == "Name" && sc > 0 && sc > app_name_sc) { app_name = unescape_xdg(v); app_name_sc = sc } + else if (bk == "GenericName" && sc > 0 && sc > gen_name_sc) { gen_name = unescape_xdg(v); gen_name_sc = sc } + else if (k == "Exec" && exec_raw == "") exec_raw = v + else if (k == "TryExec" && try_exec == "") try_exec = unescape_xdg(v) + else if (k == "Icon" && icon == "") icon = unescape_xdg(v) + else if (k == "Path" && workdir == "") workdir = unescape_xdg(v) + else if (k == "NoDisplay") nodisplay = v + else if (k == "Hidden") hidden = v + else if (k == "OnlyShowIn") only_in = v + else if (k == "NotShowIn") not_in = v + else if (k == "Terminal") terminal = v + else if (k == "Actions") actions_str = v + else if (k == "DBusActivatable") dbus_act = v + } else if (substr(section, 1, 7) == "action:") { + aid = substr(section, 8) + if (bk == "Name" && sc > 0 && sc > act_name_sc[aid]) { act_name[aid] = unescape_xdg(v); act_name_sc[aid] = sc } + else if (k == "Exec" && act_exec[aid] == "") act_exec[aid] = v + else if (k == "OnlyShowIn") act_only[aid] = v + else if (k == "NotShowIn") act_not[aid] = v + else if (k == "Icon" && act_icon[aid] == "") act_icon[aid] = unescape_xdg(v) + } + } + close(fpath) + + if (dtype != "" && tolower(dtype) != "application") next + if (tolower(hidden) == "true" || tolower(nodisplay) == "true") next + if (only_in != "" && !list_matches(only_in, cur_desk)) next + if (not_in != "" && list_matches(not_in, cur_desk)) next + if (app_name == "") next + + term_flag = (tolower(terminal) == "true") ? 1 : 0 + if (exec_raw != "") { + cmd = expand_exec(exec_raw, app_name, icon, fpath) + } else if (tolower(dbus_act) == "true") { + bus_id = did + sub(/\.desktop$/, "", bus_id) + obj_path = "/" bus_id + gsub(/\./, "/", obj_path) + gsub(/-/, "_", obj_path) + cmd = "gdbus call --session --dest " sh_quote(bus_id) " --object-path " sh_quote(obj_path) " --method org.freedesktop.Application.Activate \047{}\047" + } else { + cmd = "" + } + if (cmd == "") next + + label = app_name + if (gen_name != "" && index(tolower(app_name), tolower(gen_name)) == 0) { + label = label " (" gen_name ")" + } + if (term_flag) label = label " [term]" + + skey = tolower(app_name) + printf "%s\t0000\t%s\t%s\t%s\t%d\t%s\n", skey, clean_tab(try_exec), label, clean_tab(workdir), term_flag, cmd + + if (actions_str != "") { + na = split(actions_str, act_arr, /;/) + seq = 0 + for (i = 1; i <= na; i++) { + aid = trim(act_arr[i]) + if (aid == "" || !(aid in act_seen)) continue + if (act_only[aid] != "" && !list_matches(act_only[aid], cur_desk)) continue + if (act_not[aid] != "" && list_matches(act_not[aid], cur_desk)) continue + aname = act_name[aid] + araw = act_exec[aid] + if (aname == "" || araw == "") continue + aicon = (act_icon[aid] != "") ? act_icon[aid] : icon + acmd = expand_exec(araw, aname, aicon, fpath) + if (acmd == "") continue + seq++ + alabel = app_name ": " aname (term_flag ? " [term]" : "") + printf "%s\t%04d\t%s\t%s\t%s\t%d\t%s\n", skey, seq, clean_tab(try_exec), alabel, clean_tab(workdir), term_flag, acmd + } + } +} +' "$MANIFEST_TMP" | LC_ALL=C sort -t "$TAB" -k1,1 -k2,2 | cut -f3- > "$XDG_TMP" + +BAD_TE="" +OLD_IFS="$IFS" +IFS="$NEWLINE" +set -f +for _te in $(awk -F'\t' '$1 != "" && !s[$1]++ { print $1 }' "$XDG_TMP"); do + if ! check_try_exec "$_te"; then + BAD_TE="${BAD_TE:+$BAD_TE$NEWLINE}$_te" + fi +done +set +f +IFS="$OLD_IFS" + +{ + printf 'Terminal\t\t0\tst\n' + printf 'Control Center & Power\t\t0\tanode-power\n' + printf 'Network & Wi-Fi\t\t0\tanode-net\n' + printf 'Audio & Volume\t\t0\tanode-audio\n' + printf 'Display & Scaling\t\t0\tanode-display\n' + printf 'Date & Timezone\t\t0\tanode-datetime\n' + printf 'Themes & Fonts\t\t0\tanode-themes\n' + printf 'Virtual Keyboard Toggle\t\t0\tanode-media-key vkbd-toggle\n' + printf 'Lock Screen\t\t0\tanode-lock\n' + + awk -F'\t' -v bad_nl="$BAD_TE" ' + BEGIN { + n = split(bad_nl, a, /\n/) + for (i = 1; i <= n; i++) { + if (a[i] != "") bad[a[i]] = 1 + } + } + ($1 != "" && ($1 in bad)) { next } + $2 != "" && $5 != "" { + printf "%s\t%s\t%s\t%s\n", $2, $3, $4, $5 + } + ' "$XDG_TMP" if command -v dmenu_path >/dev/null 2>&1; then dmenu_path | while IFS= read -r _bin; do - [ -n "$_bin" ] && printf '%s\t%s\n' "$_bin" "$_bin" + [ -n "$_bin" ] && printf '%s\t\t0\t%s\n' "$_bin" "$_bin" done fi } | awk -F'\t' '!seen[$1]++ { print $0 }' > "$APPS_TMP" -CHOICE="$(cut -f1 "$APPS_TMP" | dmenu -i -l 12 -p "Run:")" || exit 0 +if [ "$LIST_ONLY" = "1" ]; then + cat "$APPS_TMP" + exit 0 +fi + +CHOICE="$(cut -f1 "$APPS_TMP" | dmenu -i -l 0 -p "Run:")" || exit 0 [ -n "$CHOICE" ] || exit 0 -CMD="$(awk -F'\t' -v ch="$CHOICE" '$1 == ch { print $2; exit }' "$APPS_TMP")" -[ -n "$CMD" ] || CMD="$CHOICE" +MATCHED="$(awk -F'\t' -v ch="$CHOICE" '$1 == ch { print; exit }' "$APPS_TMP")" +if [ -n "$MATCHED" ]; then + _wd="$(printf '%s\n' "$MATCHED" | cut -f2)" + _tm="$(printf '%s\n' "$MATCHED" | cut -f3)" + CMD="$(printf '%s\n' "$MATCHED" | cut -f4-)" +else + _wd="" + _tm="0" + CMD="$CHOICE" +fi +[ -n "${CMD:-}" ] || CMD="$CHOICE" -exec /bin/sh -c "exec $CMD" >/dev/null 2>&1 & +if [ -n "${_wd:-}" ] && [ -d "$_wd" ]; then + cd "$_wd" || true +fi + +if [ "${_tm:-0}" = "1" ]; then + if command -v setsid >/dev/null 2>&1; then + exec setsid st -e /bin/sh -c "exec $CMD" /dev/null 2>&1 & + else + exec st -e /bin/sh -c "exec $CMD" /dev/null 2>&1 & + fi +else + if command -v setsid >/dev/null 2>&1; then + exec setsid /bin/sh -c "exec $CMD" /dev/null 2>&1 & + else + exec /bin/sh -c "exec $CMD" /dev/null 2>&1 & + fi +fi diff --git a/scripts/anode-replace b/scripts/anode-replace index 1a61b31..f82f73f 100755 --- a/scripts/anode-replace +++ b/scripts/anode-replace @@ -3,6 +3,7 @@ set -eu : "${XDG_CONFIG_HOME:=$HOME/.config}" +: "${XDG_CACHE_HOME:=$HOME/.cache}" : "${ANODE_PREFIX:=/usr/local}" SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" @@ -10,21 +11,26 @@ PROFILE="${ANODE_SESSION_PROFILE:-}" KEEP_PANELS=0 FOREGROUND=0 NO_AUTOSTART=0 +FORCE=0 +SWITCH_SESSION=0 DRY_RUN=0 usage() { cat <<'EOF' Usage: anode-replace [OPTIONS] -Live-replace the currently running X11 window manager / session with ANODE. +Live-replace the currently running X11 window manager / session with ANODE, or +switch to a fresh ANODE display-manager session. 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 + --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 + --force Proceed with in-place replacement even if WM is DM session leader + --switch-session Switch to an ANODE LightDM session cleanly (schedules one-shot ~/.xprofile handoff when a user session is already active) + --dry-run Print detected WM and planned actions without replacing + -h, --help Show this help EOF } @@ -51,6 +57,14 @@ while [ $# -gt 0 ]; do NO_AUTOSTART=1 shift ;; + --force) + FORCE=1 + shift + ;; + --switch-session) + SWITCH_SESSION=1 + shift + ;; --dry-run) DRY_RUN=1 shift @@ -66,11 +80,6 @@ while [ $# -gt 0 ]; do 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" ;; @@ -87,23 +96,8 @@ if [ -z "$ANODE_SESSION_BIN" ]; then 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() { + [ -n "${DISPLAY:-}" ] || return 0 command -v xprop >/dev/null 2>&1 || return 0 xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | awk ' /window id/ { @@ -120,7 +114,7 @@ get_root_wm_win() { get_win_wm_name() { _wid="$1" - [ -n "$_wid" ] || return 0 + [ -n "$_wid" ] && [ -n "${DISPLAY:-}" ] || 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 { @@ -148,7 +142,7 @@ get_win_wm_name() { get_win_pid() { _wid="$1" - [ -n "$_wid" ] || return 0 + [ -n "$_wid" ] && [ -n "${DISPLAY:-}" ] || return 0 command -v xprop >/dev/null 2>&1 || return 0 xprop -id "$_wid" _NET_WM_PID 2>/dev/null | awk ' index($0, "=") > 0 { @@ -166,6 +160,59 @@ get_win_pid() { MY_UID="$(id -u)" SELF_PID="$$" +find_wm_pid_by_name() { + _wmname="$1" + [ -n "$_wmname" ] || return 0 + _tok="$(printf '%s' "$_wmname" | awk '{ + w = tolower($1) + gsub(/[^a-z0-9._-]/, "", w) + if (w == "anode") w = "dwm" + print w + exit + }')" + [ -n "$_tok" ] || return 0 + (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 t="$_tok" ' + $1 == u && $2 > 1 && $2 != s { + c = $3 + sub(/^.*\//, "", c) + if (tolower(c) == t) { + print $2 + exit + } + } + ' +} + +get_ppid() { + _p="$1" + [ -n "$_p" ] || return 0 + (ps -eo pid=,ppid= 2>/dev/null || ps -ax -o pid=,ppid= 2>/dev/null || true) | awk -v t="$_p" ' + $1 == t { print $2; exit } + ' +} + +get_pid_comm() { + _p="$1" + [ -n "$_p" ] || return 0 + (ps -eo pid=,comm= 2>/dev/null || ps -ax -o pid=,comm= 2>/dev/null || true) | awk -v t="$_p" ' + $1 == t { + c = $2 + sub(/^.*\//, "", c) + print c + exit + } + ' +} + +is_session_leader_parent() { + case "${1:-}" in + lightdm|sddm|sddm-helper|gdm|gdm-x-session|gdm-session-wor*|xdm|lxdm|lxdm-binary|slim|ly|greetd|emptty|xinit|startx|Xsession|xsession|login|agetty) + return 0 + ;; + esac + return 1 +} + is_my_pid() { _p="$1" [ -n "$_p" ] || return 1 @@ -193,6 +240,62 @@ kill_my_procs() { done } +dm_user_has_active_session() { + _u="$1" + command -v dm-tool >/dev/null 2>&1 || return 1 + dm-tool list-seats 2>/dev/null | awk -v u="$_u" -v sq="'" ' + { + s = $0 + gsub(/^[ \t]+|[ \t]+$/, "", s) + if (s == ("UserName=" sq u sq) || s == ("UserName=\"" u "\"") || s == ("UserName=" u)) { + found = 1 + exit 0 + } + } + END { exit found ? 0 : 1 } + ' +} + +ensure_xprofile_hook() { + _xp="$HOME/.xprofile" + if [ -f "$_xp" ] && grep -q '^# >>> anode-switch-once >>>$' "$_xp" 2>/dev/null; then + return 0 + fi + if [ -s "$_xp" ]; then + printf '\n' >> "$_xp" + fi + cat <<'EOF' >> "$_xp" +# >>> anode-switch-once >>> +_anode_sw="${XDG_CACHE_HOME:-$HOME/.cache}/anode/switch-once" +if [ -r "$_anode_sw" ]; then + _anode_bin="" + _anode_prof="" + { IFS= read -r _anode_bin || true; IFS= read -r _anode_prof || true; } < "$_anode_sw" + rm -f "$_anode_sw" + if [ -n "$_anode_bin" ] && [ -x "$_anode_bin" ]; then + case "${0:-}" in + *Xsession*) + if [ -n "$_anode_prof" ]; then + set -- "$_anode_bin" --profile "$_anode_prof" + else + set -- "$_anode_bin" + fi + ;; + *) + if [ -n "$_anode_prof" ]; then + exec "$_anode_bin" --profile "$_anode_prof" + else + exec "$_anode_bin" + fi + ;; + esac + fi +fi +unset _anode_sw _anode_bin _anode_prof +# <<< anode-switch-once <<< +EOF +} + sync_activation_env() { [ "${ANODE_NO_DBUS:-0}" = "1" ] && return 0 if command -v dbus-update-activation-environment >/dev/null 2>&1; then @@ -219,6 +322,100 @@ sync_activation_env() { 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)" +if [ -z "${PREV_WM_PID:-}" ] && [ -n "${PREV_WM_NAME:-}" ]; then + PREV_WM_PID="$(find_wm_pid_by_name "$PREV_WM_NAME" || true)" +fi + +PREV_WM_PPID="" +PREV_WM_PCOMM="" +IS_DM_SESSION_LEADER=0 +if [ -n "${PREV_WM_PID:-}" ]; then + PREV_WM_PPID="$(get_ppid "$PREV_WM_PID" || true)" + if [ -n "${PREV_WM_PPID:-}" ]; then + PREV_WM_PCOMM="$(get_pid_comm "$PREV_WM_PPID" || true)" + if is_session_leader_parent "${PREV_WM_PCOMM:-}"; then + IS_DM_SESSION_LEADER=1 + fi + fi +fi + +if [ "$SWITCH_SESSION" = "1" ]; then + TARGET_USER="${USER:-$(id -un)}" + if command -v dm-tool >/dev/null 2>&1 && ! dm_user_has_active_session "$TARGET_USER"; then + if [ "$DRY_RUN" = "1" ]; then + printf 'Would run: dm-tool switch-to-user %s anode\n' "$TARGET_USER" + exit 0 + fi + if [ ! -r /usr/share/xsessions/anode.desktop ] && [ ! -r /usr/share/lightdm/sessions/anode.desktop ]; then + printf 'anode-replace: error: anode.desktop is not installed in /usr/share/xsessions or /usr/share/lightdm/sessions\n' >&2 + printf 'Run: sudo make XSESSIONSDIR=/usr/share/xsessions install\n' >&2 + exit 1 + fi + exec dm-tool switch-to-user "$TARGET_USER" anode + fi + + SWITCH_FILE="$XDG_CACHE_HOME/anode/switch-once" + _wm_low="$(printf '%s' "${PREV_WM_NAME:-}" | awk '{ print tolower($1) }')" + _exit_desc="log out manually" + if [ "$_wm_low" = "i3" ] && [ -n "${DISPLAY:-}" ] && command -v i3-msg >/dev/null 2>&1; then + _exit_desc="i3-msg exit" + elif [ -n "${PREV_WM_PID:-}" ] && is_my_pid "$PREV_WM_PID"; then + _exit_desc="kill -TERM $PREV_WM_PID" + fi + + if [ "$DRY_RUN" = "1" ]; then + printf 'Display: %s\n' "${DISPLAY:-unset}" + printf 'Detected WM: %s (window=%s pid=%s parent=%s)\n' \ + "${PREV_WM_NAME:-none}" "${PREV_WM_WIN:-none}" "${PREV_WM_PID:-unknown}" "${PREV_WM_PCOMM:-unknown}" + if dm_user_has_active_session "$TARGET_USER"; then + printf 'Note: LightDM already has an active session for %s (dm-tool switch-to-user refocuses it without starting ANODE).\n' "$TARGET_USER" + fi + printf 'Switch sentinel: %s\n' "$SWITCH_FILE" + printf 'Profile hook: %s/.xprofile\n' "$HOME" + printf 'Target session: %s%s\n' "$ANODE_SESSION_BIN" "$( [ -n "$PROFILE" ] && printf ' --profile %s' "$PROFILE" || true )" + printf 'WM exit action: %s\n' "$_exit_desc" + exit 0 + fi + + mkdir -p "$XDG_CACHE_HOME/anode" + printf '%s\n%s\n' "$ANODE_SESSION_BIN" "$PROFILE" > "$SWITCH_FILE" + ensure_xprofile_hook + printf 'Scheduled one-shot ANODE session via ~/.xprofile; exiting %s to switch...\n' "${PREV_WM_NAME:-current WM}" + + if [ "$_wm_low" = "i3" ] && [ -n "${DISPLAY:-}" ] && command -v i3-msg >/dev/null 2>&1; then + unset I3SOCK SWAYSOCK || true + if i3-msg exit >/dev/null 2>&1; then + exit 0 + fi + fi + if [ -n "${PREV_WM_PID:-}" ] && is_my_pid "$PREV_WM_PID"; then + kill -TERM "$PREV_WM_PID" 2>/dev/null || true + exit 0 + fi + printf 'Log out of your current session and LightDM will start ANODE.\n' + exit 0 +fi + +if [ -z "${DISPLAY:-}" ]; then + printf 'anode-replace: error: DISPLAY is not set (run inside an active X11 session)\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 set -- --replace if [ -n "$PROFILE" ]; then @@ -232,6 +429,12 @@ 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 'Parent process: %s (pid=%s)\n' \ + "${PREV_WM_PCOMM:-unknown}" "${PREV_WM_PPID:-unknown}" + if [ "$IS_DM_SESSION_LEADER" = "1" ]; then + printf 'Warning: %s is the direct session child of %s; in-place replacement will end that session unless using --switch-session or ANODE at login.\n' \ + "${PREV_WM_NAME:-WM}" "$PREV_WM_PCOMM" + fi 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" @@ -242,6 +445,23 @@ if [ "$DRY_RUN" = "1" ]; then exit 0 fi +if [ "$IS_DM_SESSION_LEADER" = "1" ] && [ "$FORCE" != "1" ]; then + { + printf 'anode-replace: error: %s (pid %s) is running directly as the session child of %s (pid %s).\n' \ + "${PREV_WM_NAME:-the active WM}" "${PREV_WM_PID:-unknown}" \ + "${PREV_WM_PCOMM:-the display manager}" "${PREV_WM_PPID:-unknown}" + printf 'Replacing it in place causes %s to end the X11 session and kill the display.\n' \ + "${PREV_WM_PCOMM:-the display manager}" + printf 'Use one of these safe alternatives instead:\n' + printf ' 1. Install anode.desktop into /usr/share/xsessions and switch via ~/.xprofile/display manager:\n' + printf ' sudo make XSESSIONSDIR=/usr/share/xsessions install\n' + printf ' anode-replace --switch-session\n' + printf ' (Or select ANODE at login / set user-session=anode in /etc/lightdm/lightdm.conf.)\n' + printf ' 2. Pass --force only if you intentionally want to trigger WM replacement anyway.\n' + } >&2 + exit 1 +fi + sync_activation_env # Stop duplicate ANODE session daemons from an earlier ANODE instance @@ -250,7 +470,7 @@ 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 \ + xfce4-panel mate-panel lxpanel i3bar tint2 polybar lemonbar fbpanel plank wingpanel \ dunst xfce4-notifyd xsettingsd xfsettingsd fi diff --git a/scripts/anode-session b/scripts/anode-session index 22a4705..28d5806 100755 --- a/scripts/anode-session +++ b/scripts/anode-session @@ -171,11 +171,36 @@ if [ "$NO_AUTOSTART" != "1" ] && command -v anode-autostart >/dev/null 2>&1; the fi if command -v dwm >/dev/null 2>&1; then + _dwm_rc=0 if [ "$REPLACE_WM" = "1" ]; then - dwm --replace + dwm --replace || _dwm_rc=$? else - dwm + dwm || _dwm_rc=$? fi + if [ "$_dwm_rc" = "75" ]; then + # Replaced by another ICCCM WM: stop old background daemons and hold the + # session open until the replacement WM exits so display managers stay up. + cleanup_bg + BG_PIDS="" + sleep 0.5 + if command -v xprop >/dev/null 2>&1; then + _miss=0 + while :; do + _wid="$(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 "${_wid:-}" ] && xprop -id "$_wid" _NET_WM_NAME >/dev/null 2>&1; then + _miss=0 + else + _miss=$(( _miss + 1 )) + [ "$_miss" -ge 2 ] && break + fi + sleep 1 + done + fi + exit 0 + fi + exit "$_dwm_rc" else printf 'anode-session: dwm executable not found\n' >&2 exit 1 diff --git a/scripts/anode-sync-dunst-theme b/scripts/anode-sync-dunst-theme index 1aa546e..d5c141f 100755 --- a/scripts/anode-sync-dunst-theme +++ b/scripts/anode-sync-dunst-theme @@ -56,24 +56,24 @@ GEOM="$(awk -v s="$SCALE" -v bsz="$BASE_SZ" 'BEGIN { sc = s + 0.0 if (sc < 0.50) sc = 0.50 if (sc > 4.00) sc = 4.00 - w = int(340.0 * sc + 0.5); if (w < 220) w = 220 - hmax = int(180.0 * sc + 0.5); if (hmax < 80) hmax = 80 - ox = int(16.0 * sc + 0.5); if (ox < 8) ox = 8 - oy = int(42.0 * sc + 0.5); if (oy < 20) oy = 20 - pad = int(12.0 * sc + 0.5); if (pad < 6) pad = 6 - hpad = int(14.0 * sc + 0.5); if (hpad < 8) hpad = 8 + w = int(320.0 * sc + 0.5); if (w < 220) w = 220 + hmax = int(160.0 * sc + 0.5); if (hmax < 80) hmax = 80 + ox = int(14.0 * sc + 0.5); if (ox < 8) ox = 8 + oy = int(38.0 * sc + 0.5); if (oy < 20) oy = 20 + pad = int(10.0 * sc + 0.5); if (pad < 6) pad = 6 + hpad = int(12.0 * sc + 0.5); if (hpad < 8) hpad = 8 tpad = int(8.0 * sc + 0.5); if (tpad < 4) tpad = 4 fw = int(2.0 * sc + 0.5); if (fw < 1) fw = 1 - rad = int(8.0 * sc + 0.5); if (rad < 4) rad = 4 - pbar_h = int(8.0 * sc + 0.5); if (pbar_h < 4) pbar_h = 4 - fpt = int(((bsz + 0.0) * 0.72) + 0.5); if (fpt < 8) fpt = 8 - printf "%d %d %d %d %d %d %d %d %d %d %d\n", w, hmax, ox, oy, pad, hpad, tpad, fw, rad, pbar_h, fpt + rad = int(6.0 * sc + 0.5); if (rad < 3) rad = 3 + pbar_h = int(6.0 * sc + 0.5); if (pbar_h < 4) pbar_h = 4 + fpx = int((bsz + 0.0) + 0.5); if (fpx < 10) fpx = 10; if (fpx > 72) fpx = 72 + printf "%d %d %d %d %d %d %d %d %d %d %d\n", w, hmax, ox, oy, pad, hpad, tpad, fw, rad, pbar_h, fpx }')" set -- $GEOM D_W="$1" D_H="$2" D_OX="$3" D_OY="$4" D_PAD="$5" D_HPAD="$6" D_TPAD="$7" D_FW="$8" D_RAD="$9" shift 9 -D_PBAR="$1" D_FPT="$2" +D_PBAR="$1" D_FPX="$2" mkdir -p "$DUNST_DIR" TMP_RC="$DUNST_RC.tmp.$$" @@ -83,6 +83,7 @@ cat > "$TMP_RC" < "$TMP_RC" <= 0 && g >= 0 && b >= 0) { + lum = 0.299 * r + 0.587 * g + 0.114 * b + return (lum < 128.0) ? 1 : 0 + } + } + return 1 +} +BEGIN { sc = s + 0.0 if (sc < 0.50) sc = 0.50 if (sc > 4.00) sc = 4.00 gdk_sc = (sc < 1.75) ? 1 : int(sc + 0.5) - # Effective GTK logical scale multiplier when GDK_SCALE=1 vs 2 - eff = sc / gdk_sc - if (eff < 0.5) eff = 0.5 - pt = int(((bsz + 0.0) * 0.72 / gdk_sc) + 0.5) + logical_px = (bsz + 0.0) / sc + pt = int((logical_px * 0.65) + 0.5) if (pt < 7) pt = 7 - if (pt > 24) pt = 24 - btn_pv = int(6.0 * eff + 0.5); if (btn_pv < 3) btn_pv = 3 - btn_ph = int(12.0 * eff + 0.5); if (btn_ph < 6) btn_ph = 6 - rad = int(6.0 * eff + 0.5); if (rad < 3) rad = 3 - row_h = int(28.0 * eff + 0.5); if (row_h < 20) row_h = 20 - sb_w = int(12.0 * eff + 0.5); if (sb_w < 8) sb_w = 8 - is_d = (dark == "1" || dark == "true") ? 1 : 0 - printf "%d %d %d %d %d %d %d %d\n", gdk_sc, pt, btn_pv, btn_ph, rad, row_h, sb_w, is_d + if (pt > 22) pt = 22 + btn_pv = 3 + btn_ph = 8 + rad = 4 + row_h = 24 + sb_w = 8 + if (dark == "1" || tolower(dark) == "true") is_d = 1 + else if (dark == "0" || tolower(dark) == "false") is_d = 0 + else is_d = bg_is_dark(bg) + gtk_cur = int(((cur + 0.0) / gdk_sc) + 0.5); if (gtk_cur < 16) gtk_cur = 16 + printf "%d %d %d %d %d %d %d %d %d\n", gdk_sc, pt, btn_pv, btn_ph, rad, row_h, sb_w, is_d, gtk_cur }')" set -- $CALC GDK_SCALE_VAL="$1" @@ -101,6 +123,7 @@ RAD_PX="$5" ROW_H="$6" SB_W="$7" IS_DARK="$8" +GTK_CUR_SZ="$9" GTK_FONT="$FONT_FACE $GTK_PT" @@ -134,7 +157,17 @@ style "anode-default" { text[SELECTED] = "$SEL_FG" text[INSENSITIVE] = "$FG_MUTED" } +style "anode-menu" { + xthickness = 4 + ythickness = 4 + GtkMenu::horizontal-padding = 2 + GtkMenu::vertical-padding = 4 + GtkMenuItem::horizontal-padding = 6 + GtkMenuBar::internal-padding = 2 +} class "GtkWidget" style "anode-default" +class "GtkMenu" style "anode-menu" +widget_class "**" style "anode-menu" EOF mv -f "$GTK2_DIR/gtkrc.tmp.$$" "$GTK2_DIR/gtkrc" @@ -158,8 +191,30 @@ mkdir -p "$GTK3_THEME_DIR" "$GTK4_THEME_DIR" "$GTK3_CONF_DIR" "$GTK4_CONF_DIR" write_gtk_css() { _dest="$1" _is4="$2" + _user_override="$3" + _force_dark="$4" _tmp="${_dest}.tmp.$$" - cat > "$_tmp" < "$_tmp" + if [ "$_user_override" = "0" ]; then + if [ "$_is4" = "1" ]; then + if [ "$_use_dark" = "1" ]; then + printf '@import url("resource:///org/gtk/libgtk/theme/Default/Default-dark.css");\n' > "$_tmp" + else + printf '@import url("resource:///org/gtk/libgtk/theme/Default/Default-light.css");\n' > "$_tmp" + fi + else + if [ "$_use_dark" = "1" ]; then + printf '@import url("resource:///org/gtk/libgtk/theme/Adwaita/gtk-contained-dark.css");\n' > "$_tmp" + else + printf '@import url("resource:///org/gtk/libgtk/theme/Adwaita/gtk-contained.css");\n' > "$_tmp" + fi + fi + fi + cat >> "$_tmp" <> "$_tmp" < menuitem:hover, popover modelbutton:hover { + background-color: $SEL_BG; + color: $SEL_FG; +} + +button:not(.flat) { + background-color: $BG_BUTTON; + background-image: none; + color: $FG_BRIGHT; + border-color: $BORDER; +} +button:not(.flat):hover { background-color: $BG_OVERLAY; border-color: $ACCENT; } -button:checked, button.suggested-action { +button:not(.flat):checked, button:not(.flat):active, button.suggested-action { background-color: $SEL_BG; + background-image: none; color: $SEL_FG; border-color: $ACCENT; } +button.flat:not(:hover):not(:checked):not(:active) { + background-color: transparent; + background-image: none; + border-color: transparent; +} -entry, spinbutton, combobox button { +entry, textview, textview text, .view, treeview.view, list, listbox { background-color: $BG_INPUT; color: $FG_BRIGHT; - border: 1px solid $BORDER; - border-radius: ${RAD_PX}px; - padding: ${PAD_V}px; + border-color: $BORDER; } entry:focus { background-color: $BG_INPUT_FOC; border-color: $ACCENT; } -row:selected, .view:selected, treeview.view:selected, *:selected { +row:selected, .view:selected, treeview.view:selected, *:selected, selection { background-color: $SEL_BG; color: $SEL_FG; } +notebook header, notebook tab { + background-color: $BG_HEADER; + color: $FG_MAIN; + border-color: $DIVIDER; +} +notebook tab:checked { + background-color: $BG_MAIN; + color: $FG_BRIGHT; + border-color: $ACCENT; +} + +frame > border, scrolledwindow.frame, separator { + border-color: $DIVIDER; +} + scrollbar slider { - min-width: ${SB_W}px; - min-height: ${SB_W}px; - border-radius: ${RAD_PX}px; background-color: $BORDER; } scrollbar slider:hover { @@ -250,10 +338,10 @@ scrollbar slider:hover { tooltip, .tooltip { background-color: $BG_OVERLAY; color: $FG_BRIGHT; - border: 1px solid $ACCENT; - border-radius: ${RAD_PX}px; + border-color: $ACCENT; } EOF + fi if [ "$_is4" = "1" ]; then cat >> "$_tmp" < "$GTK3_CONF_DIR/settings.ini.tmp.$$" < "$XSET_DIR/xsettingsd.conf.tmp.$$" <= 0) ? touch_override : (st->touch_mode ? 1 : 0); snprintf(tbuf, sizeof(tbuf), "--touch=%d", t); + unsetenv("ANODE_SCALE"); + unsetenv("ANODE_TOUCH"); const char *av[] = {"anode-apply-scale", sbuf, tbuf, NULL}; if (anode_run_cmd_timeout(av, NULL, 0, 5000) == 0) { gemui_theme_reload(st->app); const gemui_theme_t *th = gemui_theme(st->app); st->scale = th ? th->scale : st->scale; st->touch_mode = th ? th->touch_mode : (t != 0); - gemui_show_toast(st->app, "Display scale updated", 1800); + char msg[64]; + snprintf(msg, sizeof(msg), "Display scale: %.2fx (%d DPI)", + st->scale, th ? th->dpi : (int)(96.0 * st->scale + 0.5)); + gemui_show_toast(st->app, msg, 1800); } else { gemui_show_toast(st->app, "Scale update failed", 2000); } diff --git a/src/common/anode_plat.c b/src/common/anode_plat.c index 63b5270..c69c443 100644 --- a/src/common/anode_plat.c +++ b/src/common/anode_plat.c @@ -23,6 +23,14 @@ #include #include #include +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +#include +#if defined(__OpenBSD__) +#include +#elif defined(__NetBSD__) +#include +#endif +#endif #ifndef ANODE_PREFIX #define ANODE_PREFIX "/usr/local" @@ -34,6 +42,21 @@ static uint64_t plat_now_ms(void) { return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); } +static int plat_read_buf(const char *path, char *buf, size_t sz) { + if (!path || !buf || sz < 2) return -1; + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return -1; + size_t off = 0; + while (off + 1 < sz) { + ssize_t n = read(fd, buf + off, sz - 1 - off); + if (n <= 0) break; + off += (size_t)n; + } + close(fd); + buf[off] = '\0'; + return off > 0 ? 0 : -1; +} + static int plat_read_line(const char *path, char *buf, size_t sz) { if (!path || !buf || sz == 0) return -1; FILE *f = fopen(path, "r"); @@ -525,7 +548,7 @@ bool anode_backlight_get(int *cur_out, int *max_out, char *backend_out, size_t b if (plat_read_line(p, b, sizeof(b)) == 0 && atoi(b) > 0) { mx = atoi(b); snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); - if (plat_read_line(p, b, sizeof(b)) == 0) { + if (access(p, W_OK) == 0 && plat_read_line(p, b, sizeof(b)) == 0) { cur = atoi(b); if (cur_out) *cur_out = cur; if (max_out) *max_out = mx; @@ -1037,3 +1060,105 @@ bool anode_find_wifi_iface(char *out, size_t sz) { } return false; } + +bool anode_read_cpu_sample(anode_cpu_sample_t *out) { + if (!out) return false; +#if defined(__linux__) || defined(__linux) + char buf[512]; + if (plat_read_buf("/proc/stat", buf, sizeof(buf)) == 0) { + return anode_parse_proc_stat_cpu(buf, out); + } + return false; +#elif defined(__FreeBSD__) + long cp[5]; + size_t len = sizeof(cp); + if (sysctlbyname("kern.cp_time", cp, &len, NULL, 0) == 0 && len >= sizeof(cp)) { + unsigned long long tot = 0; + for (int i = 0; i < 5; i++) tot += (unsigned long long)cp[i]; + out->total = tot; + out->idle = (unsigned long long)cp[4]; + return tot > 0; + } + return false; +#elif defined(__OpenBSD__) + int mib[2] = {CTL_KERN, KERN_CPTIME}; + long cp[5]; + size_t len = sizeof(cp); + if (sysctl(mib, 2, cp, &len, NULL, 0) == 0 && len >= sizeof(cp)) { + unsigned long long tot = 0; + for (int i = 0; i < 5; i++) tot += (unsigned long long)cp[i]; + out->total = tot; + out->idle = (unsigned long long)cp[4]; + return tot > 0; + } + return false; +#elif defined(__NetBSD__) + uint64_t cp[5]; + size_t len = sizeof(cp); + if (sysctlbyname("kern.cp_time", cp, &len, NULL, 0) == 0 && len >= sizeof(cp)) { + unsigned long long tot = 0; + for (int i = 0; i < 5; i++) tot += (unsigned long long)cp[i]; + out->total = tot; + out->idle = (unsigned long long)cp[4]; + return tot > 0; + } + return false; +#else + return false; +#endif +} + +bool anode_read_mem_usage_pct(int *pct_out) { + if (!pct_out) return false; +#if defined(__linux__) || defined(__linux) + char buf[4096]; + if (plat_read_buf("/proc/meminfo", buf, sizeof(buf)) == 0) { + return anode_parse_proc_meminfo_pct(buf, pct_out); + } + return false; +#elif defined(__FreeBSD__) + unsigned long phys = 0; + unsigned int pg = 0, vfree = 0, vinact = 0; + size_t s_phys = sizeof(phys), s_u = sizeof(pg); + if (sysctlbyname("hw.physmem", &phys, &s_phys, NULL, 0) != 0 || phys == 0) return false; + if (sysctlbyname("vm.stats.vm.v_page_size", &pg, &s_u, NULL, 0) != 0 || pg == 0) return false; + s_u = sizeof(vfree); + sysctlbyname("vm.stats.vm.v_free_count", &vfree, &s_u, NULL, 0); + s_u = sizeof(vinact); + sysctlbyname("vm.stats.vm.v_inactive_count", &vinact, &s_u, NULL, 0); + unsigned long long avail = (unsigned long long)(vfree + vinact) * (unsigned long long)pg; + if (avail > phys) avail = phys; + int pct = (int)(((phys - avail) * 100ULL + phys / 2ULL) / phys); + if (pct < 0) pct = 0; + if (pct > 100) pct = 100; + *pct_out = pct; + return true; +#elif defined(__OpenBSD__) + int mib[2] = {CTL_VM, VM_UVMEXP}; + struct uvmexp uvm; + size_t len = sizeof(uvm); + if (sysctl(mib, 2, &uvm, &len, NULL, 0) != 0 || uvm.npages <= 0) return false; + unsigned long long tot = (unsigned long long)uvm.npages; + unsigned long long avail = (unsigned long long)(uvm.free + uvm.inactive); + if (avail > tot) avail = tot; + int pct = (int)(((tot - avail) * 100ULL + tot / 2ULL) / tot); + if (pct < 0) pct = 0; + if (pct > 100) pct = 100; + *pct_out = pct; + return true; +#elif defined(__NetBSD__) + struct uvmexp_sysctl uvm; + size_t len = sizeof(uvm); + if (sysctlbyname("vm.uvmexp2", &uvm, &len, NULL, 0) != 0 || uvm.npages <= 0) return false; + unsigned long long tot = (unsigned long long)uvm.npages; + unsigned long long avail = (unsigned long long)(uvm.free + uvm.inactive); + if (avail > tot) avail = tot; + int pct = (int)(((tot - avail) * 100ULL + tot / 2ULL) / tot); + if (pct < 0) pct = 0; + if (pct > 100) pct = 100; + *pct_out = pct; + return true; +#else + return false; +#endif +} diff --git a/src/common/anode_plat.h b/src/common/anode_plat.h index 27fbf1a..b9e6ca1 100644 --- a/src/common/anode_plat.h +++ b/src/common/anode_plat.h @@ -7,6 +7,8 @@ #include #include +#include "anode_sys_parse.h" + #ifdef __cplusplus extern "C" { #endif @@ -77,6 +79,10 @@ int anode_power_action(const char *action); /* suspend, hibernate, reboot, power int anode_list_net_ifaces(anode_net_iface_t *out, int max_ifaces); bool anode_find_wifi_iface(char *out, size_t sz); +/* System telemetry (CPU & RAM usage) */ +bool anode_read_cpu_sample(anode_cpu_sample_t *out); +bool anode_read_mem_usage_pct(int *pct_out); + #ifdef __cplusplus } #endif diff --git a/src/common/anode_power_policy.h b/src/common/anode_power_policy.h index 2da07e1..c2959a4 100644 --- a/src/common/anode_power_policy.h +++ b/src/common/anode_power_policy.h @@ -32,9 +32,9 @@ typedef struct { static inline anode_power_cfg_t anode_power_cfg_default(void) { anode_power_cfg_t c; - c.dim_ms = 60000U; - c.lock_ms = 180000U; - c.suspend_ms = 600000U; + c.dim_ms = 300000U; /* 5 min */ + c.lock_ms = 600000U; /* 10 min */ + c.suspend_ms = 1800000U; /* 30 min (battery only) */ c.crit_batt_pct = 5; c.suspend_on_ac = false; return c; @@ -67,9 +67,10 @@ static inline void anode_power_policy_step(const anode_power_cfg_t *cfg, } } - /* User activity resumes from dimmed/suspended */ - if (idle_ms < cfg->dim_ms) { - if (*state == ANODE_PWR_DIMMED || *state == ANODE_PWR_SUSPENDED) { + /* User activity resumes from dimmed/locked/suspended */ + uint32_t resume_thresh = cfg->dim_ms > 0 ? cfg->dim_ms : (cfg->lock_ms > 0 ? cfg->lock_ms : cfg->suspend_ms); + if (resume_thresh == 0 || idle_ms < resume_thresh) { + if (*state == ANODE_PWR_DIMMED || *state == ANODE_PWR_LOCKED || *state == ANODE_PWR_SUSPENDED) { a.restore_brightness = true; } *state = screen_locked ? ANODE_PWR_LOCKED : ANODE_PWR_ACTIVE; diff --git a/src/common/anode_scale.h b/src/common/anode_scale.h index 1786f89..6ba5b44 100644 --- a/src/common/anode_scale.h +++ b/src/common/anode_scale.h @@ -131,12 +131,15 @@ static inline void anode_read_xres_scale_from_db(XrmDatabase db, Display *dpy, dpi = anode_clamp_dpi(v); have_dpi = 1; } - if (XrmGetResource(db, "anode.scale", "Anode.Scale", &type, &val) && val.addr && - anode_parse_positive_double(val.addr, &v)) { + if ((XrmGetResource(db, "anode.scale", "Anode.Scale", &type, &val) && val.addr && + anode_parse_positive_double(val.addr, &v)) || + (XrmGetResource(db, "theme.scale", "Theme.Scale", &type, &val) && val.addr && + anode_parse_positive_double(val.addr, &v))) { scale = anode_clamp_scale(v); have_scale = 1; } - if (XrmGetResource(db, "anode.touchMode", "Anode.TouchMode", &type, &val) && val.addr) { + if ((XrmGetResource(db, "anode.touchMode", "Anode.TouchMode", &type, &val) && val.addr) || + (XrmGetResource(db, "theme.touchMode", "Theme.TouchMode", &type, &val) && val.addr)) { touch = anode_parse_bool_str(val.addr, 0); } } diff --git a/src/common/anode_sys_parse.h b/src/common/anode_sys_parse.h new file mode 100644 index 0000000..1b7a3d9 --- /dev/null +++ b/src/common/anode_sys_parse.h @@ -0,0 +1,126 @@ +/* + * ANODE Cross-Unix CPU & Memory Parsers + */ +#ifndef ANODE_SYS_PARSE_H +#define ANODE_SYS_PARSE_H + +#include +#include +#include +#include +#include + +typedef struct { + unsigned long long total; + unsigned long long idle; +} anode_cpu_sample_t; + +static inline bool anode_parse_proc_stat_cpu(const char *text, anode_cpu_sample_t *out) { + if (!text || !out) return false; + out->total = 0; + out->idle = 0; + + const char *p = text; + while (*p) { + const char *nl = strchr(p, '\n'); + size_t len = nl ? (size_t)(nl - p) : strlen(p); + if (len >= 4 && strncmp(p, "cpu", 3) == 0 && isspace((unsigned char)p[3])) { + const char *cur = p + 3; + const char *end = p + len; + unsigned long long vals[10]; + int count = 0; + while (cur < end && count < 10) { + while (cur < end && isspace((unsigned char)*cur)) cur++; + if (cur >= end || !isdigit((unsigned char)*cur)) break; + char *next = NULL; + unsigned long long v = strtoull(cur, &next, 10); + if (next == cur || next > end) break; + vals[count++] = v; + cur = next; + } + if (count < 4) return false; + unsigned long long tot = 0; + for (int i = 0; i < count; i++) tot += vals[i]; + unsigned long long idl = vals[3] + (count > 4 ? vals[4] : 0ULL); + out->total = tot; + out->idle = idl; + return tot > 0; + } + if (!nl) break; + p = nl + 1; + } + return false; +} + +static inline int anode_cpu_usage_pct(const anode_cpu_sample_t *prev, + const anode_cpu_sample_t *cur) { + if (!prev || !cur || cur->total <= prev->total) return 0; + unsigned long long dt = cur->total - prev->total; + unsigned long long di = (cur->idle >= prev->idle) ? (cur->idle - prev->idle) : 0ULL; + if (di > dt) di = dt; + unsigned long long used = dt - di; + int pct = (int)((used * 100ULL + dt / 2ULL) / dt); + if (pct < 0) pct = 0; + if (pct > 100) pct = 100; + return pct; +} + +static inline bool anode_parse_proc_meminfo_pct(const char *text, int *pct_out) { + if (!text || !pct_out) return false; + unsigned long long mem_total = 0; + unsigned long long mem_avail = 0; + unsigned long long mem_free = 0; + unsigned long long buffers = 0; + unsigned long long cached = 0; + unsigned long long srecl = 0; + bool has_total = false; + bool has_avail = false; + + const char *p = text; + while (*p) { + const char *nl = strchr(p, '\n'); + size_t len = nl ? (size_t)(nl - p) : strlen(p); + const char *colon = memchr(p, ':', len); + if (colon) { + size_t klen = (size_t)(colon - p); + const char *vp = colon + 1; + const char *end = p + len; + while (vp < end && isspace((unsigned char)*vp)) vp++; + if (vp < end && isdigit((unsigned char)*vp)) { + char *next = NULL; + unsigned long long val = strtoull(vp, &next, 10); + if (next > vp) { + if (klen == 8 && strncmp(p, "MemTotal", 8) == 0) { + mem_total = val; + has_total = true; + } else if (klen == 12 && strncmp(p, "MemAvailable", 12) == 0) { + mem_avail = val; + has_avail = true; + } else if (klen == 7 && strncmp(p, "MemFree", 7) == 0) { + mem_free = val; + } else if (klen == 7 && strncmp(p, "Buffers", 7) == 0) { + buffers = val; + } else if (klen == 6 && strncmp(p, "Cached", 6) == 0) { + cached = val; + } else if (klen == 12 && strncmp(p, "SReclaimable", 12) == 0) { + srecl = val; + } + } + } + } + if (!nl) break; + p = nl + 1; + } + + if (!has_total || mem_total == 0) return false; + unsigned long long avail = has_avail ? mem_avail : (mem_free + buffers + cached + srecl); + if (avail > mem_total) avail = mem_total; + unsigned long long used = mem_total - avail; + int pct = (int)((used * 100ULL + mem_total / 2ULL) / mem_total); + if (pct < 0) pct = 0; + if (pct > 100) pct = 100; + *pct_out = pct; + return true; +} + +#endif /* ANODE_SYS_PARSE_H */ diff --git a/src/daemons/anode-checkpw.c b/src/daemons/anode-checkpw.c index 4a88174..529a182 100644 --- a/src/daemons/anode-checkpw.c +++ b/src/daemons/anode-checkpw.c @@ -5,7 +5,9 @@ #include #include #include +#include #include +#include #include #ifdef HAVE_SHADOW_H @@ -39,6 +41,63 @@ static void strip_eol(char *s) { } } +/* Fallback via setuid PAM helper (unix_chkpwd) when running non-root without /etc/shadow access */ +static bool verify_via_unix_chkpwd(const char *username, const char *password) { + if (!username || !username[0] || !password || !password[0]) return false; + struct passwd *pw = getpwnam(username); + if (!pw || pw->pw_uid != getuid()) return false; + + static const char *const helpers[] = { + "/sbin/unix_chkpwd", + "/usr/sbin/unix_chkpwd", + "/usr/libexec/unix_chkpwd" + }; + const char *helper = NULL; + for (size_t i = 0; i < sizeof(helpers) / sizeof(helpers[0]); i++) { + if (access(helpers[i], X_OK) == 0) { + helper = helpers[i]; + break; + } + } + if (!helper) return false; + + int pfd[2]; + if (pipe(pfd) != 0) return false; + + pid_t pid = fork(); + if (pid < 0) { + close(pfd[0]); + close(pfd[1]); + return false; + } + if (pid == 0) { + close(pfd[1]); + if (dup2(pfd[0], STDIN_FILENO) < 0) _exit(127); + if (pfd[0] > 2) close(pfd[0]); + int dn = open("/dev/null", O_WRONLY); + if (dn >= 0) { + dup2(dn, STDOUT_FILENO); + dup2(dn, STDERR_FILENO); + if (dn > 2) close(dn); + } + const char *av[] = {helper, username, "nullok", NULL}; + execv(helper, (char *const *)av); + _exit(127); + } + + close(pfd[0]); + size_t plen = strlen(password); + ssize_t w1 = write(pfd[1], password, plen); + ssize_t w2 = write(pfd[1], "", 1); + close(pfd[1]); + + int status = 0; + while (waitpid(pid, &status, 0) < 0) { + if (errno != EINTR) return false; + } + return w1 == (ssize_t)plen && w2 == 1 && WIFEXITED(status) && WEXITSTATUS(status) == 0; +} + int main(int argc, char *argv[]) { const char *user_arg = (argc > 1 && argv[1][0]) ? argv[1] : NULL; char line1[256] = {0}; @@ -100,6 +159,8 @@ int main(int argc, char *argv[]) { ok = const_time_eq(computed, stored_hash); wipe_mem(computed, strlen(computed)); } + } else { + ok = verify_via_unix_chkpwd(username, password); } wipe_mem(line1, sizeof(line1)); diff --git a/src/daemons/anode-powerd.c b/src/daemons/anode-powerd.c index cdf78b7..c1d9c6b 100644 --- a/src/daemons/anode-powerd.c +++ b/src/daemons/anode-powerd.c @@ -54,6 +54,40 @@ static bool lock_running(void) { return anode_run_cmd_timeout(cmd, NULL, 0, 1000) == 0; } +static void load_power_cfg(anode_power_cfg_t *cfg) { + *cfg = anode_power_cfg_default(); + char cdir[512]; + anode_config_dir(cdir, sizeof(cdir)); + char p[576]; + snprintf(p, sizeof(p), "%s/power.conf", cdir); + FILE *f = fopen(p, "r"); + if (!f) return; + char line[256]; + while (fgets(line, sizeof(line), f)) { + char *s = line; + while (*s == ' ' || *s == '\t') s++; + if (*s == '\0' || *s == '#' || *s == '\n') continue; + char *eq = strchr(s, '='); + if (!eq) continue; + *eq = '\0'; + const char *k = s; + const char *v = eq + 1; + long val = atol(v); + if (strcmp(k, "DIM_SEC") == 0) { + cfg->dim_ms = val > 0 ? (uint32_t)val * 1000U : 0U; + } else if (strcmp(k, "LOCK_SEC") == 0) { + cfg->lock_ms = val > 0 ? (uint32_t)val * 1000U : 0U; + } else if (strcmp(k, "SUSPEND_SEC") == 0) { + cfg->suspend_ms = val > 0 ? (uint32_t)val * 1000U : 0U; + } else if (strcmp(k, "SUSPEND_ON_AC") == 0) { + cfg->suspend_on_ac = (val != 0); + } else if (strcmp(k, "CRIT_BATT_PCT") == 0) { + if (val >= 1 && val <= 30) cfg->crit_batt_pct = (int)val; + } + } + fclose(f); +} + int main(void) { if (pipe(g_sig_pipe) != 0) return 1; for (int i = 0; i < 2; i++) { @@ -61,6 +95,8 @@ int main(void) { fcntl(g_sig_pipe[i], F_SETFD, fcntl(g_sig_pipe[i], F_GETFD, 0) | FD_CLOEXEC); } + signal(SIGPIPE, SIG_IGN); + struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_handler; @@ -70,9 +106,11 @@ int main(void) { sigaction(SIGHUP, &sa, NULL); Display *dpy = XOpenDisplay(NULL); - anode_power_cfg_t cfg = anode_power_cfg_default(); + anode_power_cfg_t cfg; + load_power_cfg(&cfg); anode_pwr_state_t state = ANODE_PWR_ACTIVE; - double saved_bright = 0.7; + double saved_bright = 1.0; + bool is_dimmed = false; bool running = true; while (running) { @@ -89,11 +127,19 @@ int main(void) { int cur = 0, maxv = 0; if (anode_backlight_get(&cur, &maxv, NULL, 0) && maxv > 0) { saved_bright = (double)cur / (double)maxv; + } else { + saved_bright = 1.0; } - anode_backlight_set(0.15); + if (saved_bright < 0.35) saved_bright = 1.0; + double dim_val = saved_bright * 0.45; + if (dim_val < 0.35) dim_val = 0.35; + if (dim_val > saved_bright) dim_val = saved_bright; + anode_backlight_set(dim_val); + is_dimmed = true; } - if (act.restore_brightness) { - anode_backlight_set(saved_bright >= 0.15 ? saved_bright : 0.7); + if (act.restore_brightness && is_dimmed) { + anode_backlight_set(saved_bright >= 0.35 ? saved_bright : 1.0); + is_dimmed = false; } if (act.warn_low_batt) { const char *nt[] = { @@ -114,17 +160,18 @@ int main(void) { } int timeout_ms = 15000; - if (idle_ms < cfg.dim_ms) { + if (cfg.dim_ms > 0 && idle_ms < cfg.dim_ms) { uint32_t rem = cfg.dim_ms - idle_ms; if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; - } else if (idle_ms < cfg.lock_ms) { + } else if (cfg.lock_ms > 0 && idle_ms < cfg.lock_ms) { uint32_t rem = cfg.lock_ms - idle_ms; if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; - } else if (!bat.on_ac && idle_ms < cfg.suspend_ms) { + } else if (cfg.suspend_ms > 0 && !bat.on_ac && idle_ms < cfg.suspend_ms) { uint32_t rem = cfg.suspend_ms - idle_ms; if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; } if (timeout_ms < 1000) timeout_ms = 1000; + if (is_dimmed && timeout_ms > 500) timeout_ms = 500; struct pollfd pfds[2]; nfds_t nfds = 0; @@ -141,6 +188,7 @@ int main(void) { while ((n = read(g_sig_pipe[0], buf, sizeof(buf))) > 0) { for (ssize_t i = 0; i < n; i++) { if (buf[i] == 'Q') running = false; + else if (buf[i] == 'R') load_power_cfg(&cfg); } } } @@ -152,6 +200,9 @@ int main(void) { } } + if (is_dimmed) { + anode_backlight_set(saved_bright >= 0.35 ? saved_bright : 1.0); + } if (dpy) XCloseDisplay(dpy); close(g_sig_pipe[0]); close(g_sig_pipe[1]); diff --git a/src/daemons/anode-statusd.c b/src/daemons/anode-statusd.c index 51606ae..fdea494 100644 --- a/src/daemons/anode-statusd.c +++ b/src/daemons/anode-statusd.c @@ -10,20 +10,12 @@ #include #include #include -#include #include #include #include #include #include -#ifdef __linux__ -#include -#include -#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) -#include -#endif - static int g_sig_pipe[2] = {-1, -1}; static void sig_handler(int sig) { @@ -36,32 +28,6 @@ static void sig_handler(int sig) { errno = saved; } -static int open_net_watch_fd(void) { -#ifdef __linux__ - int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); - if (fd >= 0) { - struct sockaddr_nl sa; - memset(&sa, 0, sizeof(sa)); - sa.nl_family = AF_NETLINK; - sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; - if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) == 0) { - fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); - fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); - return fd; - } - close(fd); - } -#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) - int fd = socket(PF_ROUTE, SOCK_RAW, 0); - if (fd >= 0) { - fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); - fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); - return fd; - } -#endif - return -1; -} - 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'; @@ -120,7 +86,18 @@ static bool query_xkb_layout(Display *dpy, Window root, bool has_xkb, char *out, return ok; } -static void build_status(Display *dpy, Window root, bool has_xkb, char *out, size_t sz) { +static void append_seg(char *out, size_t sz, size_t *pos, const char *seg) { + if (!seg || !seg[0] || *pos >= sz) return; + int n = snprintf(out + *pos, sz - *pos, "%s%s", (*pos == 0) ? " " : " | ", seg); + if (n > 0) { + if ((size_t)n < sz - *pos) *pos += (size_t)n; + else *pos = sz - 1; + } +} + +static void build_status(Display *dpy, Window root, bool has_xkb, + anode_cpu_sample_t *prev_cpu, bool *has_prev_cpu, int *last_cpu_pct, + char *out, size_t sz) { int vol = 0; bool muted = false; char vol_str[32] = ""; @@ -129,25 +106,25 @@ static void build_status(Display *dpy, Window root, bool has_xkb, char *out, siz else snprintf(vol_str, sizeof(vol_str), "VOL %d%%", vol); } - anode_net_iface_t ifaces[ANODE_MAX_IFACES]; - int n_if = anode_list_net_ifaces(ifaces, ANODE_MAX_IFACES); - const anode_net_iface_t *best = NULL; - for (int i = 0; i < n_if; i++) { - if (ifaces[i].is_loopback || !ifaces[i].is_up) continue; - if (ifaces[i].ipv4[0]) { - best = &ifaces[i]; - if (ifaces[i].is_wireless) break; - } else if (!best && ifaces[i].ipv6[0]) { - best = &ifaces[i]; + char cpu_str[32] = ""; + anode_cpu_sample_t cur_cpu; + if (anode_read_cpu_sample(&cur_cpu)) { + if (!*has_prev_cpu) { + *prev_cpu = cur_cpu; + *has_prev_cpu = true; + } else if (cur_cpu.total < prev_cpu->total) { + *prev_cpu = cur_cpu; + } else if (cur_cpu.total - prev_cpu->total >= 10ULL) { + *last_cpu_pct = anode_cpu_usage_pct(prev_cpu, &cur_cpu); + *prev_cpu = cur_cpu; } + snprintf(cpu_str, sizeof(cpu_str), "CPU %d%%", *last_cpu_pct); } - char net_str[128]; - if (best) { - snprintf(net_str, sizeof(net_str), "%s %s", - best->is_wireless ? "WiFi" : best->name, - best->ipv4[0] ? best->ipv4 : best->ipv6); - } else { - snprintf(net_str, sizeof(net_str), "NET off"); + + char ram_str[32] = ""; + int ram_pct = 0; + if (anode_read_mem_usage_pct(&ram_pct)) { + snprintf(ram_str, sizeof(ram_str), "RAM %d%%", ram_pct); } anode_battery_info_t bat; @@ -170,14 +147,17 @@ static void build_status(Display *dpy, Window root, bool has_xkb, char *out, siz char time_str[32]; strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M", &tmbuf); - 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); + if (sz > 0) out[0] = '\0'; + size_t pos = 0; + append_seg(out, sz, &pos, vol_str); + append_seg(out, sz, &pos, cpu_str); + append_seg(out, sz, &pos, ram_str); + append_seg(out, sz, &pos, bat_str); + append_seg(out, sz, &pos, kbd_str); + append_seg(out, sz, &pos, time_str); + if (pos + 1 < sz) { + out[pos++] = ' '; + out[pos] = '\0'; } } @@ -216,7 +196,10 @@ int main(void) { Window root = DefaultRootWindow(dpy); int xfd = ConnectionNumber(dpy); - int netfd = open_net_watch_fd(); + + anode_cpu_sample_t prev_cpu = {0, 0}; + bool has_prev_cpu = anode_read_cpu_sample(&prev_cpu); + int last_cpu_pct = 0; char last_status[512] = {0}; bool running = true; @@ -228,7 +211,7 @@ int main(void) { } char cur[512]; - build_status(dpy, root, has_xkb, cur, sizeof(cur)); + build_status(dpy, root, has_xkb, &prev_cpu, &has_prev_cpu, &last_cpu_pct, cur, sizeof(cur)); if (strcmp(cur, last_status) != 0) { snprintf(last_status, sizeof(last_status), "%s", cur); XStoreName(dpy, root, cur); @@ -241,15 +224,14 @@ int main(void) { struct tm tmbuf; localtime_r(&now, &tmbuf); int timeout_ms = (60 - tmbuf.tm_sec) * 1000 + 50; - if (timeout_ms < 1000) timeout_ms = 60000; + if (timeout_ms < 250) timeout_ms = 250; + if (timeout_ms > 2000) timeout_ms = 2000; - struct pollfd pfds[3]; - nfds_t nfds = 0; - pfds[nfds++] = (struct pollfd){.fd = g_sig_pipe[0], .events = POLLIN}; - pfds[nfds++] = (struct pollfd){.fd = xfd, .events = POLLIN}; - if (netfd >= 0) pfds[nfds++] = (struct pollfd){.fd = netfd, .events = POLLIN}; + struct pollfd pfds[2]; + pfds[0] = (struct pollfd){.fd = g_sig_pipe[0], .events = POLLIN}; + pfds[1] = (struct pollfd){.fd = xfd, .events = POLLIN}; - int pr = poll(pfds, nfds, timeout_ms); + int pr = poll(pfds, 2, timeout_ms); if (pr < 0 && errno != EINTR) break; if (pfds[0].revents & POLLIN) { @@ -264,13 +246,8 @@ 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) {} - } } - if (netfd >= 0) close(netfd); close(g_sig_pipe[0]); close(g_sig_pipe[1]); XCloseDisplay(dpy); diff --git a/src/dmenu/dmenu.c b/src/dmenu/dmenu.c index c264fcc..8af0a81 100644 --- a/src/dmenu/dmenu.c +++ b/src/dmenu/dmenu.c @@ -110,7 +110,7 @@ static void load_xresources(void) { double dpi = 96.0; anode_read_xres_scale_from_db(xdb, dpy, &dpi, &ui_scale, NULL); - lineheight = (unsigned int)anode_scale_px(36, ui_scale); + lineheight = (unsigned int)anode_scale_px(26, ui_scale); min_lineheight = lineheight; const char *dm_lh = xdb ? xrm_get(xdb, "dmenu.lineheight", NULL, NULL) : NULL; @@ -860,7 +860,7 @@ static void setup(void) { int sx = 0, sy = 0, sw = 0, sh = 0; - bh = MAX((int)drw->fonts->h + anode_scale_px(9, ui_scale), (int)lineheight); + bh = MAX((int)drw->fonts->h + anode_scale_px(6, ui_scale), (int)lineheight); if (!explicit_lineheight && bh < (int)min_lineheight) bh = (int)min_lineheight; promptw = (prompt && *prompt) ? (int)TEXTW(prompt) : 0; @@ -903,12 +903,19 @@ static void setup(void) { x = sx; y = sy; mw = sw; - mh = sh; { - int avail_lines = (mh - bh) / bh; + int avail_lines = (sh - bh) / bh; if (avail_lines < 1) avail_lines = 1; - if (!explicit_lines || lines == 0 || (int)lines > avail_lines) + if (!explicit_lines || lines == 0) { lines = (unsigned int)avail_lines; + mh = sh; + } else { + if ((int)lines > avail_lines) + lines = (unsigned int)avail_lines; + mh = ((int)lines + 1) * bh; + if (mh > sh) mh = sh; + if (!topbar) y = sy + sh - mh; + } } inputw = mw / 3; match(); diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c index 4996cee..9cf3a6f 100644 --- a/src/dwm/dwm.c +++ b/src/dwm/dwm.c @@ -299,6 +299,7 @@ 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 replaced_by_other = 0; static int replace_wm = 0; static int otherwm_err = 0; static int super_down = 0; @@ -515,6 +516,7 @@ static Time getservertime(Window w) { static void selectionclear(XEvent *e) { if (e->xselectionclear.window == wmcheckwin && e->xselectionclear.selection == wmselatom) { + replaced_by_other = 1; restart_dwm = 0; running = 0; } @@ -909,10 +911,20 @@ static void drawbar(Monitor *m) { if (c->isurgent) urg |= c->tags; } - /* Launcher touch button */ + /* Launcher touch button (vector 3-bar hamburger icon, font-independent) */ drw_setscheme(drw, scheme[SchemeSel]); - int lpad = (launcher_w - (int)drw_font_getwidth(drw, "\xef\x83\x89", False)) / 2; - drw_text(drw, 0, 0, (unsigned int)launcher_w, (unsigned int)bh, (unsigned int)MAX(lpad, 4), "\xef\x83\x89", 0, False); + drw_rect(drw, 0, 0, (unsigned int)launcher_w, (unsigned int)bh, 1, 1); + { + int iw = anode_scale_px(16, ui_scale); + int ih = MAX(anode_scale_px(2, ui_scale), 2); + int ig = MAX(anode_scale_px(3, ui_scale), 3); + if (iw > launcher_w - 8) iw = MAX(launcher_w - 8, 6); + int tot_h = 3 * ih + 2 * ig; + int ix = (launcher_w - iw) / 2; + int iy = (bh - tot_h) / 2; + for (int bi = 0; bi < 3; bi++) + drw_rect(drw, ix, iy + bi * (ih + ig), (unsigned int)iw, (unsigned int)ih, 1, 0); + } x = launcher_w; for (i = 0; i < LENGTH(tags); i++) { @@ -1333,7 +1345,8 @@ static void loadxres(void) { XrmInitialize(); XrmDatabase db = anode_open_xres_db(dpy); double dpi = 96.0; - anode_read_xres_scale_from_db(db, dpy, &dpi, &ui_scale, NULL); + int touch_i = 0; + anode_read_xres_scale_from_db(db, dpy, &dpi, &ui_scale, &touch_i); borderpx = (unsigned int)anode_scale_px((int)base_borderpx, ui_scale); snap = (unsigned int)anode_scale_px((int)base_snap, ui_scale); @@ -1357,6 +1370,7 @@ static void loadxres(void) { font = xres_font; } + int cur_sz = 0; if (db) { if ((v = xrm_lookup(db, "dwm.normbgcolor", "dwm.background", "theme.bgBar"))) snprintf(normbgcolor, sizeof(normbgcolor), "%s", v); @@ -1374,8 +1388,40 @@ static void loadxres(void) { int b = atoi(v); if (b >= 1 && b <= 12) borderpx = (unsigned int)b; } + if ((v = xrm_lookup(db, "Xcursor.size", NULL, NULL))) { + int cs = atoi(v); + if (cs >= 16 && cs <= 96) cur_sz = cs; + } XrmDestroyDatabase(db); } + + if (cur_sz <= 0) { + double raw_cur = 24.0 * ui_scale; + if (raw_cur < 20.0) cur_sz = 16; + else if (raw_cur < 32.0) cur_sz = 24; + else if (raw_cur < 44.0) cur_sz = 32; + else if (raw_cur < 64.0) cur_sz = 48; + else cur_sz = 64; + } + + int gdk_sc = (ui_scale < 1.75) ? 1 : (int)(ui_scale + 0.5); + if (gdk_sc < 1) gdk_sc = 1; + char sbuf[16], tbuf[16], gsbuf[16], gdbuf[16], cbuf[16]; + snprintf(sbuf, sizeof(sbuf), "%.2f", ui_scale); + snprintf(tbuf, sizeof(tbuf), "%d", touch_i ? 1 : 0); + snprintf(gsbuf, sizeof(gsbuf), "%d", gdk_sc); + if (gdk_sc <= 1) snprintf(gdbuf, sizeof(gdbuf), "1.0"); + else if (gdk_sc == 2) snprintf(gdbuf, sizeof(gdbuf), "0.5"); + else if (gdk_sc == 4) snprintf(gdbuf, sizeof(gdbuf), "0.25"); + else snprintf(gdbuf, sizeof(gdbuf), "%.3f", 1.0 / (double)gdk_sc); + snprintf(cbuf, sizeof(cbuf), "%d", cur_sz); + + setenv("ANODE_SCALE", sbuf, 1); + setenv("ANODE_TOUCH", tbuf, 1); + setenv("GDK_SCALE", gsbuf, 1); + setenv("GDK_DPI_SCALE", gdbuf, 1); + setenv("QT_SCALE_FACTOR", sbuf, 1); + setenv("XCURSOR_SIZE", cbuf, 1); } static void reloadxres(const Arg *arg) { @@ -1390,9 +1436,18 @@ static void reloadxres(const Arg *arg) { dwmfont = drw_font_create(drw, font); drw_setfont(drw, dwmfont); lrpad = (int)dwmfont->h + anode_scale_px(4, ui_scale); - bh = MAX((int)dwmfont->h + anode_scale_px(12, ui_scale), anode_scale_px(30, ui_scale)); + bh = MAX((int)dwmfont->h + anode_scale_px(6, ui_scale), anode_scale_px(24, ui_scale)); drw_resize(drw, (unsigned int)sw, (unsigned int)bh); + if (cursor[CurNormal]) { drw_cur_free(drw, cursor[CurNormal]); cursor[CurNormal] = NULL; } + if (cursor[CurResize]) { drw_cur_free(drw, cursor[CurResize]); cursor[CurResize] = NULL; } + if (cursor[CurMove]) { drw_cur_free(drw, cursor[CurMove]); cursor[CurMove] = NULL; } + cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr); + cursor[CurResize] = drw_cur_create(drw, XC_sizing); + cursor[CurMove] = drw_cur_create(drw, XC_fleur); + if (cursor[CurNormal]) + XDefineCursor(dpy, root, cursor[CurNormal]->cursor); + free(scheme[SchemeNorm]); free(scheme[SchemeSel]); scheme[SchemeNorm] = drw_scm_create(drw, (const char **)colors[SchemeNorm], 3); @@ -2014,7 +2069,7 @@ static void setup(void) { dwmfont = drw_font_create(drw, font); drw_setfont(drw, dwmfont); lrpad = (int)dwmfont->h + anode_scale_px(4, ui_scale); - bh = MAX((int)dwmfont->h + anode_scale_px(12, ui_scale), anode_scale_px(30, ui_scale)); + bh = MAX((int)dwmfont->h + anode_scale_px(6, ui_scale), anode_scale_px(24, ui_scale)); updategeom(); { @@ -2906,5 +2961,5 @@ int main(int argc, char *argv[]) { setenv("ANODE_DWM_RESTARTED", "1", 1); execvp(argv[0], argv); } - return EXIT_SUCCESS; + return replaced_by_other ? 75 : EXIT_SUCCESS; } diff --git a/src/st/x.c b/src/st/x.c index cbce980..97d397a 100644 --- a/src/st/x.c +++ b/src/st/x.c @@ -273,6 +273,7 @@ static int frccap = 0; static char *usedfont = NULL; static double usedfontsize = 0; static double defaultfontsize = 0; +static double st_xft_dpi = 96.0; static char *opt_class = NULL; static char **opt_cmd = NULL; @@ -1106,6 +1107,14 @@ xloadfont(Font *f, FcPattern *pattern) return 1; FcConfigSubstitute(NULL, configured, FcMatchPattern); + { + double pat_dpi = 0.0; + if (st_xft_dpi >= 48.0 && + FcPatternGetDouble(pattern, FC_DPI, 0, &pat_dpi) != FcResultMatch) { + FcPatternDel(configured, FC_DPI); + FcPatternAddDouble(configured, FC_DPI, st_xft_dpi); + } + } XftDefaultSubstitute(xw.dpy, xw.scr, configured); match = FcFontMatch(NULL, configured, &result); @@ -2387,8 +2396,10 @@ run(void) xloadcols(); xunloadfonts(); hbunloadfonts(); - xloadfonts(opt_font ? opt_font : font, 0); + usedfont = opt_font ? opt_font : font; + xloadfonts(usedfont, 0); cresize(win.w, win.h); + xhints(); redraw(); XFlush(xw.dpy); } @@ -2529,18 +2540,41 @@ config_init(void) XrmInitialize(); db = anode_open_xres_db(xw.dpy); anode_read_xres_scale_from_db(db, xw.dpy, &dpi, &scale, NULL); + st_xft_dpi = dpi; /* Scale base defaults dynamically before reading explicit st.* overrides */ borderpx = anode_scale_px(2, scale); cursorthickness = (unsigned int)anode_scale_px(2, scale); + int has_font = 0, has_bg = 0, has_fg = 0, has_cs = 0; + if (db) { - for (p = resources; p < resources + LEN(resources); p++) - resource_load(db, p->name, p->type, p->dst); + for (p = resources; p < resources + LEN(resources); p++) { + if (resource_load(db, p->name, p->type, p->dst) == 0) { + if (strcmp(p->name, "font") == 0) has_font = 1; + else if (strcmp(p->name, "background") == 0) has_bg = 1; + else if (strcmp(p->name, "foreground") == 0) has_fg = 1; + else if (strcmp(p->name, "cursorColor") == 0) has_cs = 1; + } + } + if (!opt_name && !opt_class) { + char *cap_type = NULL, *probe_type = NULL; + XrmValue cap_val, probe_val; + if (XrmGetResource(db, "__anode_probe__.font", "St.font", &cap_type, &cap_val) && + cap_type && strcmp(cap_type, "String") == 0 && cap_val.addr && cap_val.addr[0]) { + int have_wild = XrmGetResource(db, "__anode_probe__.font", + "__anode_probe__.font", &probe_type, &probe_val) && + probe_type && strcmp(probe_type, "String") == 0 && probe_val.addr; + if (!have_wild || strcmp(cap_val.addr, probe_val.addr) != 0) { + font = strdup(cap_val.addr); + has_font = 1; + } + } + } } - /* Apply Fira Code font sized for current scale unless st.font was explicitly set */ - if (!db || !(XrmGetResource(db, "st.font", "*", &type, &ret) && ret.addr && ret.addr[0])) { + /* Apply Fira Code font sized for current scale unless st.font / St.font was explicitly set */ + if (!has_font) { const char *ff = NULL, *bsz = NULL; if (db && XrmGetResource(db, "theme.fontFace", "*", &type, &ret) && ret.addr && ret.addr[0]) ff = ret.addr; @@ -2555,7 +2589,7 @@ config_init(void) font = st_theme_font; } if (db) { - if (!(XrmGetResource(db, "st.background", "*", &type, &ret) && ret.addr && ret.addr[0])) { + if (!has_bg) { if (XrmGetResource(db, "theme.bgHeader", "*", &type, &ret) && ret.addr && ret.addr[0]) { snprintf(st_theme_bg, sizeof(st_theme_bg), "%s", ret.addr); colorname[256] = st_theme_bg; @@ -2564,12 +2598,12 @@ config_init(void) colorname[256] = st_theme_bg; } } - if (!(XrmGetResource(db, "st.foreground", "*", &type, &ret) && ret.addr && ret.addr[0]) && + if (!has_fg && XrmGetResource(db, "theme.fgMain", "*", &type, &ret) && ret.addr && ret.addr[0]) { snprintf(st_theme_fg, sizeof(st_theme_fg), "%s", ret.addr); colorname[257] = st_theme_fg; } - if (!(XrmGetResource(db, "st.cursorColor", "*", &type, &ret) && ret.addr && ret.addr[0]) && + if (!has_cs && XrmGetResource(db, "theme.accent", "*", &type, &ret) && ret.addr && ret.addr[0]) { snprintf(st_theme_cs, sizeof(st_theme_cs), "%s", ret.addr); colorname[258] = st_theme_cs; diff --git a/tests/test_autostart.py b/tests/test_autostart.py index de29d5c..1f6f71b 100755 --- a/tests/test_autostart.py +++ b/tests/test_autostart.py @@ -191,6 +191,50 @@ def test_directives_includes_once_and_reload(): kill_pids_from_file(m_once_skip) +def test_exec_once_session_isolation(): + with tempfile.TemporaryDirectory() as tmp: + env, _, xdg_home, _, _, bin_dir = make_base_env(tmp) + conf_dir = os.path.join(xdg_home, "anode") + sess_bin = os.path.join(bin_dir, "anode_sess_once") + compile_sleep_dummy(sess_bin) + + m_dead = os.path.join(tmp, "dead_sess.pid") + m_live = os.path.join(tmp, "live_sess.pid") + + dead_env = dict(env) + dead_env["XDG_SESSION_ID"] = "anode-dead-session-999" + dead_env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/tmp/anode-dead-dbus-999" + + live_env = dict(env) + live_env["XDG_SESSION_ID"] = "anode-live-session-1" + live_env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/tmp/anode-live-dbus-1" + + dead_proc = subprocess.Popen([sess_bin, m_dead], env=dead_env) + try: + assert wait_until(lambda: os.path.exists(m_dead), timeout=3.0) + write_text(os.path.join(conf_dir, "autostart"), f"exec_once anode_sess_once '{m_live}'\n") + + res1 = run_autostart(["start"], live_env) + assert res1.returncode == 0, res1.stderr + assert wait_until(lambda: os.path.exists(m_live), timeout=4.0), ( + "exec_once was blocked by stale process from another session" + ) + + # Re-running start within the same session must still deduplicate + res2 = run_autostart(["start"], live_env) + assert res2.returncode == 0, res2.stderr + time.sleep(0.35) + with open(m_live, "r", encoding="utf-8") as f: + pids = [line.strip() for line in f if line.strip()] + assert len(pids) == 1, f"exec_once duplicated within same session: {pids}" + finally: + if dead_proc.poll() is None: + dead_proc.terminate() + dead_proc.wait(timeout=2) + kill_pids_from_file(m_live) + kill_pids_from_file(m_dead) + + def test_profiles(): with tempfile.TemporaryDirectory() as tmp: env, _, xdg_home, _, _, _ = make_base_env(tmp) @@ -470,6 +514,7 @@ def test_dwm_sighup_reload_xvfb(): if __name__ == "__main__": test_directives_includes_once_and_reload() + test_exec_once_session_isolation() test_profiles() test_dropins_desktop_filters_and_xdg_masking() test_check_errors() diff --git a/tests/test_launcher.py b/tests/test_launcher.py new file mode 100755 index 0000000..4e01fdb --- /dev/null +++ b/tests/test_launcher.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Verify XDG Desktop Entry, Flatpak symlink, localization, and action handling in anode-launcher.""" + +import os +import subprocess +import tempfile + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +LAUNCHER = os.path.join(ROOT, "scripts", "anode-launcher") + + +def write_file(path, text, mode=0o644): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + os.chmod(path, mode) + + +def run_launcher_list(env): + res = subprocess.run([LAUNCHER, "--list"], env=env, capture_output=True, text=True) + assert res.returncode == 0, f"anode-launcher --list failed: {res.stderr}" + entries = {} + ordered_labels = [] + for line in res.stdout.splitlines(): + if not line: + continue + parts = line.split("\t", 3) + assert len(parts) == 4, f"Malformed output line: {line!r}" + label, workdir, term, cmd = parts + entries[label] = (workdir, term, cmd) + ordered_labels.append(label) + return entries, ordered_labels + + +def test_xdg_and_flatpak_integration(): + with tempfile.TemporaryDirectory() as tmp: + home = os.path.join(tmp, "home") + xdg_data = os.path.join(tmp, "xdg_data") + flatpak_root = os.path.join(tmp, "flatpak_exports", "share") + flatpak_real = os.path.join(tmp, "flatpak_app") + usr_share = os.path.join(tmp, "usr_share") + fbin = os.path.join(tmp, "bin") + for d in (home, xdg_data, flatpak_root, flatpak_real, usr_share, fbin): + os.makedirs(d, exist_ok=True) + + tool_path = os.path.join(fbin, "my_existing_tool") + write_file(tool_path, "#!/bin/sh\nexit 0\n", 0o755) + + # 1. Symlinked Flatpak .desktop with @@u %U @@ file-forwarding placeholders + discord_real = os.path.join(flatpak_real, "com.discordapp.Discord.desktop") + write_file( + discord_real, + "[Desktop Entry]\n" + "Name=Discord\n" + "GenericName=Internet Messenger\n" + "Exec=/bin/sh -c flatpak run --file-forwarding com.discordapp.Discord @@u %U @@\n" + "Type=Application\n", + ) + os.makedirs(os.path.join(flatpak_root, "applications"), exist_ok=True) + os.symlink( + discord_real, + os.path.join(flatpak_root, "applications", "com.discordapp.Discord.desktop"), + ) + + # 2. Recursive subdir desktop masked by Desktop File ID in XDG_DATA_HOME + write_file( + os.path.join(usr_share, "applications", "sub", "nested.desktop"), + "[Desktop Entry]\nName=NestedApp\nExec=sh -c true\nType=Application\n", + ) + write_file( + os.path.join(xdg_data, "applications", "sub-nested.desktop"), + "[Desktop Entry]\nName=NestedApp\nHidden=true\nExec=sh -c true\nType=Application\n", + ) + write_file( + os.path.join(usr_share, "applications", "nodisp.desktop"), + "[Desktop Entry]\nName=ShouldHide\nNoDisplay=true\nExec=sh -c true\nType=Application\n", + ) + + # 3. OnlyShowIn / NotShowIn / TryExec filters + write_file( + os.path.join(usr_share, "applications", "gnomeonly.desktop"), + "[Desktop Entry]\nName=GnomeOnly\nOnlyShowIn=GNOME;KDE;\nExec=sh -c true\nType=Application\n", + ) + write_file( + os.path.join(usr_share, "applications", "notanode.desktop"), + "[Desktop Entry]\nName=NotAnode\nNotShowIn=ANODE;XFCE;\nExec=sh -c true\nType=Application\n", + ) + write_file( + os.path.join(usr_share, "applications", "anodeonly.desktop"), + "[Desktop Entry]\nName=AnodeOnly\nOnlyShowIn=ANODE;\nExec=sh -c anode\nType=Application\n", + ) + write_file( + os.path.join(usr_share, "applications", "badtry.desktop"), + "[Desktop Entry]\nName=BadTry\nTryExec=definitely_missing_bin_999\nExec=sh -c true\nType=Application\n", + ) + + # 4. Terminal=true, Path=, field codes (%i %c %k %%), and Actions= + write_file( + os.path.join(usr_share, "applications", "termtool.desktop"), + "[Desktop Entry]\n" + "Name=TermTool\n" + "Name[uk]=УкрТерм\n" + "Icon=term-icon\n" + "Path=/tmp\n" + "TryExec=my_existing_tool\n" + "Terminal=true\n" + "Exec=my_existing_tool %i %c %k %% %f\n" + "Actions=AltRun;\n" + "Type=Application\n\n" + "[Desktop Action AltRun]\n" + "Name=Secondary\n" + "Name[uk]=Другий\n" + "Exec=my_existing_tool --alt\n", + ) + + # 5. DBusActivatable=true without Exec= + write_file( + os.path.join(usr_share, "applications", "org.example.DbusApp.desktop"), + "[Desktop Entry]\n" + "Name=DbusApp\n" + "DBusActivatable=true\n" + "Type=Application\n", + ) + + env = dict(os.environ) + env["HOME"] = home + env["XDG_DATA_HOME"] = xdg_data + env["XDG_DATA_DIRS"] = f"{flatpak_root}:{usr_share}" + env["XDG_CURRENT_DESKTOP"] = "ANODE" + env["XDG_CACHE_HOME"] = os.path.join(tmp, "cache") + env["PATH"] = fbin + ":" + env.get("PATH", "/usr/bin:/bin") + env["LC_ALL"] = "C" + env["LC_MESSAGES"] = "C" + + entries, labels = run_launcher_list(env) + + assert "Discord (Internet Messenger)" in entries, labels + d_wd, d_tm, d_cmd = entries["Discord (Internet Messenger)"] + assert d_tm == "0" and "@@u" not in d_cmd and "%U" not in d_cmd, d_cmd + assert "--file-forwarding com.discordapp.Discord" in d_cmd, d_cmd + + assert "NestedApp" not in entries, "Desktop File ID Hidden=true masking failed" + assert "ShouldHide" not in entries, "NoDisplay=true leaked" + assert "GnomeOnly" not in entries, "OnlyShowIn failed" + assert "NotAnode" not in entries, "NotShowIn failed" + assert "BadTry" not in entries, "TryExec filter failed" + assert "AnodeOnly" in entries + + t_lbl = "TermTool [term]" + a_lbl = "TermTool: Secondary [term]" + assert t_lbl in entries and a_lbl in entries, labels + assert labels.index(a_lbl) == labels.index(t_lbl) + 1 + wd, tm, cmd = entries[t_lbl] + assert wd == "/tmp" and tm == "1" + assert "--icon 'term-icon' 'TermTool'" in cmd, cmd + assert "termtool.desktop" in cmd and cmd.endswith(" %"), cmd + assert "%f" not in cmd and "%i" not in cmd and "%c" not in cmd and "%k" not in cmd + + assert "DbusApp" in entries + _, _, dbus_cmd = entries["DbusApp"] + assert "org.example.DbusApp" in dbus_cmd and "/org/example/DbusApp" in dbus_cmd, dbus_cmd + + # 6. Localized Name[uk] check + loc_env = dict(env) + loc_env.pop("LC_ALL", None) + loc_env["LC_MESSAGES"] = "uk_UA.UTF-8" + loc_entries, loc_labels = run_launcher_list(loc_env) + assert "УкрТерм [term]" in loc_entries, loc_labels + assert "УкрТерм: Другий [term]" in loc_entries, loc_labels + + +if __name__ == "__main__": + test_xdg_and_flatpak_integration() + print("test_launcher: ALL PASSED") diff --git a/tests/test_replace.py b/tests/test_replace.py index 3e18375..0f1f871 100755 --- a/tests/test_replace.py +++ b/tests/test_replace.py @@ -274,9 +274,9 @@ def test_icccm_replace_and_client_preservation(): 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 + # Original dwm must exit cleanly via SelectionClear (status 75) 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}" + assert dwm1.returncode == 75, f"old dwm exited with {dwm1.returncode}, expected 75" 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})" @@ -369,6 +369,423 @@ def test_non_icccm_wm_fallback_replace(): terminate(xvfb) +def test_anode_session_holds_open_on_replace(): + 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, + ) + sess1 = None + dpy = None + new_pid = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy + root = X11.XDefaultRootWindow(dpy) + + sess1 = subprocess.Popen( + [os.path.join(tmp, "bin", "anode-session"), "--no-autostart"], + 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 + assert get_win_prop_str(dpy, wm1, "_NET_WM_NAME") == "ANODE WM" + + rep = subprocess.run( + [REPLACE_BIN, "--no-autostart", "--keep-panels"], + env=env, capture_output=True, text=True, + ) + assert rep.returncode == 0, f"replace inside anode-session failed: {rep.stderr}" + + wm2 = wait_until( + lambda: (lambda w: w if w and w != wm1 else None)(get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")), + timeout=5.0, + ) + assert wm2 + new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID") + assert new_pid + + # Original anode-session must stay alive after its dwm yields with status 75 + time.sleep(0.8) + assert sess1.poll() is None, f"anode-session exited prematurely on replacement ({sess1.returncode})" + + # Once the replacement WM exits, the original session holder should also exit cleanly + kill_pid_and_wait(new_pid) + new_pid = None + assert wait_until(lambda: sess1.poll() is not None, timeout=5.0), "anode-session did not exit after replacement WM died" + assert sess1.returncode == 0 + finally: + terminate(sess1) + kill_pid_and_wait(new_pid) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def compile_x11_flags(): + try: + r = subprocess.run( + ["pkg-config", "--cflags", "--libs", "x11"], + capture_output=True, text=True, check=True, + ) + return r.stdout.split() + except Exception: + return ["-lX11"] + + +def test_dm_session_leader_guard(): + disp = pick_display() + cc = os.environ.get("CC", "cc") + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp) + dm_bin = os.path.join(tmp, "bin", "lightdm") + wm_bin = os.path.join(tmp, "bin", "mockwm_tst") + + dm_c = os.path.join(tmp, "lightdm.c") + with open(dm_c, "w", encoding="utf-8") as f: + f.write( + "#include \n" + "#include \n" + "int main(int argc, char **argv) {\n" + " if (argc < 2) return 1;\n" + " pid_t p = fork();\n" + " if (p == 0) { execvp(argv[1], argv + 1); _exit(127); }\n" + " int st = 0;\n" + " waitpid(p, &st, 0);\n" + " return WIFEXITED(st) ? WEXITSTATUS(st) : 1;\n" + "}\n" + ) + subprocess.run([cc, "-O2", dm_c, "-o", dm_bin], check=True) + + wm_c = os.path.join(tmp, "mockwm_tst.c") + with open(wm_c, "w", encoding="utf-8") as f: + f.write( + "#define _POSIX_C_SOURCE 200809L\n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "static volatile sig_atomic_t alive = 1;\n" + "static void stop_sig(int s) { (void)s; alive = 0; }\n" + "int main(void) {\n" + " signal(SIGTERM, stop_sig);\n" + " Display *d = XOpenDisplay(NULL);\n" + " if (!d) return 1;\n" + " Window root = DefaultRootWindow(d);\n" + " XSelectInput(d, root, SubstructureRedirectMask);\n" + " Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n" + " Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n" + " Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n" + " Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n" + " XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n" + " XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"mockwm_tst\", 10);\n" + " XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n" + " XSync(d, False);\n" + " while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n" + " XDestroyWindow(d, w);\n" + " XCloseDisplay(d);\n" + " return 0;\n" + "}\n" + ) + subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dm_proc = None + dpy = None + new_pid = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy + root = X11.XDefaultRootWindow(dpy) + + dm_proc = subprocess.Popen([dm_bin, wm_bin], 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") == "mockwm_tst" + assert get_win_prop_ulong(dpy, wm1, "_NET_WM_PID") is None + + dry = subprocess.run([REPLACE_BIN, "--dry-run"], env=env, capture_output=True, text=True) + assert dry.returncode == 0 + assert "lightdm" in dry.stdout + assert "Warning:" in dry.stdout + + blocked = subprocess.run( + [REPLACE_BIN, "--no-autostart", "--keep-panels"], + env=env, capture_output=True, text=True, + ) + assert blocked.returncode != 0, "expected DM session-leader guard to refuse without --force" + assert "lightdm" in blocked.stderr + assert "--switch-session" in blocked.stderr + assert "--force" in blocked.stderr + assert dm_proc.poll() is None, "blocked replace must leave mock DM/WM running" + + forced = subprocess.run( + [REPLACE_BIN, "--force", "--no-autostart", "--keep-panels"], + env=env, capture_output=True, text=True, + ) + assert forced.returncode == 0, f"--force failed: stdout={forced.stdout} stderr={forced.stderr}" + 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(dm_proc) + kill_pid_and_wait(new_pid) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def test_switch_session_xprofile_handoff(): + import pwd + + disp = pick_display() + cc = os.environ.get("CC", "cc") + cur_user = os.environ.get("USER") or pwd.getpwuid(os.getuid()).pw_name + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp) + xdg_cache = os.path.join(tmp, "cache") + env["XDG_CACHE_HOME"] = xdg_cache + dm_bin = os.path.join(tmp, "bin", "lightdm") + wm_bin = os.path.join(tmp, "bin", "mockwm_tst") + + # Stub dm-tool reporting current user already has an active LightDM session + dm_tool_stub = os.path.join(tmp, "bin", "dm-tool") + with open(dm_tool_stub, "w", encoding="utf-8") as f: + f.write( + f"#!/bin/sh\n" + f"if [ \"${{1:-}}\" = \"list-seats\" ]; then\n" + f" printf \"Seat0\\n CanSwitch=true\\n Session0\\n UserName='%s'\\n\" '{cur_user}'\n" + f" exit 0\n" + f"fi\n" + f"exit 0\n" + ) + os.chmod(dm_tool_stub, 0o755) + + dm_c = os.path.join(tmp, "lightdm.c") + with open(dm_c, "w", encoding="utf-8") as f: + f.write( + "#include \n" + "#include \n" + "int main(int argc, char **argv) {\n" + " if (argc < 2) return 1;\n" + " pid_t p = fork();\n" + " if (p == 0) { execvp(argv[1], argv + 1); _exit(127); }\n" + " int st = 0;\n" + " waitpid(p, &st, 0);\n" + " return WIFEXITED(st) ? WEXITSTATUS(st) : 1;\n" + "}\n" + ) + subprocess.run([cc, "-O2", dm_c, "-o", dm_bin], check=True) + + wm_c = os.path.join(tmp, "mockwm_tst.c") + with open(wm_c, "w", encoding="utf-8") as f: + f.write( + "#define _POSIX_C_SOURCE 200809L\n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "static volatile sig_atomic_t alive = 1;\n" + "static void stop_sig(int s) { (void)s; alive = 0; }\n" + "int main(void) {\n" + " signal(SIGTERM, stop_sig);\n" + " Display *d = XOpenDisplay(NULL);\n" + " if (!d) return 1;\n" + " Window root = DefaultRootWindow(d);\n" + " XSelectInput(d, root, SubstructureRedirectMask);\n" + " Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n" + " Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n" + " Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n" + " Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n" + " XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n" + " XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"mockwm_tst\", 10);\n" + " XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n" + " XSync(d, False);\n" + " while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n" + " XDestroyWindow(d, w);\n" + " XCloseDisplay(d);\n" + " return 0;\n" + "}\n" + ) + subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True) + + xprofile = os.path.join(env["HOME"], ".xprofile") + # Intentionally omit trailing newline to verify safe hook append + with open(xprofile, "w", encoding="utf-8") as f: + f.write("export USER_VAR=kept") + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dm_proc = None + dpy = None + switch_file = os.path.join(xdg_cache, "anode", "switch-once") + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy + root = X11.XDefaultRootWindow(dpy) + + dm_proc = subprocess.Popen([dm_bin, wm_bin], env=env) + assert wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0) + + dry = subprocess.run( + [REPLACE_BIN, "--switch-session", "--profile", "work", "--dry-run"], + env=env, capture_output=True, text=True, + ) + assert dry.returncode == 0, dry.stderr + assert ".xprofile" in dry.stdout and "switch-once" in dry.stdout + assert not os.path.exists(switch_file), "--dry-run must not write switch-once" + with open(xprofile, "r", encoding="utf-8") as f: + assert f.read() == "export USER_VAR=kept" + + sw = subprocess.run( + [REPLACE_BIN, "--switch-session", "--profile", "work"], + env=env, capture_output=True, text=True, + ) + assert sw.returncode == 0, f"--switch-session failed: {sw.stderr}" + assert wait_until(lambda: dm_proc.poll() is not None, timeout=4.0), "WM did not exit for session switch" + assert os.path.exists(switch_file), "switch-once sentinel was not created" + + # Simulate LightDM /etc/lightdm/Xsession sourcing ~/.xprofile then running $@ + xsession_sim = os.path.join(tmp, "Xsession") + with open(xsession_sim, "w", encoding="utf-8") as f: + f.write("#!/bin/sh\n. \"$HOME/.xprofile\"\nprintf 'USER_VAR=%s ARGS=%s\\n' \"${USER_VAR:-}\" \"$*\"\n") + os.chmod(xsession_sim, 0o755) + + run1 = subprocess.run(["/bin/sh", xsession_sim, "i3"], env=env, capture_output=True, text=True, check=True) + expected_sess = os.path.join(ROOT, "scripts", "anode-session") + assert f"USER_VAR=kept ARGS={expected_sess} --profile work" == run1.stdout.strip(), run1.stdout + assert not os.path.exists(switch_file), "switch-once sentinel was not consumed on login" + + # Subsequent login must return to original default session (one-shot) + run2 = subprocess.run(["/bin/sh", xsession_sim, "i3"], env=env, capture_output=True, text=True, check=True) + assert "USER_VAR=kept ARGS=i3" == run2.stdout.strip(), run2.stdout + + # Re-running --switch-session without X11 WM still running must keep hook idempotent + sw_env = dict(env) + sw_env.pop("DISPLAY", None) + sw2 = subprocess.run( + [REPLACE_BIN, "--switch-session"], + env=sw_env, capture_output=True, text=True, + ) + assert sw2.returncode == 0, sw2.stderr + with open(xprofile, "r", encoding="utf-8") as f: + xp_txt = f.read() + assert xp_txt.count("# >>> anode-switch-once >>>") == 1, "xprofile hook was duplicated" + assert "export USER_VAR=kept\n" in xp_txt + finally: + terminate(dm_proc) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def test_switch_session_stale_i3sock_fallback(): + import pwd + + disp = pick_display() + cc = os.environ.get("CC", "cc") + cur_user = os.environ.get("USER") or pwd.getpwuid(os.getuid()).pw_name + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp) + env["XDG_CACHE_HOME"] = os.path.join(tmp, "cache") + env["I3SOCK"] = "/nonexistent/i3/ipc-socket.9999" + + dm_tool_stub = os.path.join(tmp, "bin", "dm-tool") + with open(dm_tool_stub, "w", encoding="utf-8") as f: + f.write( + f"#!/bin/sh\n" + f"if [ \"${{1:-}}\" = \"list-seats\" ]; then\n" + f" printf \"Seat0\\n CanSwitch=true\\n Session0\\n UserName='%s'\\n\" '{cur_user}'\n" + f"fi\nexit 0\n" + ) + os.chmod(dm_tool_stub, 0o755) + + seen_file = os.path.join(tmp, "i3sock_seen") + i3_msg_stub = os.path.join(tmp, "bin", "i3-msg") + with open(i3_msg_stub, "w", encoding="utf-8") as f: + f.write( + f"#!/bin/sh\n" + f"printf '%s\\n' \"${{I3SOCK:-UNSET}}\" > '{seen_file}'\n" + f"exit 1\n" + ) + os.chmod(i3_msg_stub, 0o755) + + wm_bin = os.path.join(tmp, "bin", "mock_i3") + wm_c = os.path.join(tmp, "mock_i3.c") + with open(wm_c, "w", encoding="utf-8") as f: + f.write( + "#define _POSIX_C_SOURCE 200809L\n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "static volatile sig_atomic_t alive = 1;\n" + "static void stop_sig(int s) { (void)s; alive = 0; }\n" + "int main(void) {\n" + " signal(SIGTERM, stop_sig);\n" + " Display *d = XOpenDisplay(NULL);\n" + " if (!d) return 1;\n" + " Window root = DefaultRootWindow(d);\n" + " XSelectInput(d, root, SubstructureRedirectMask);\n" + " Window w = XCreateSimpleWindow(d, root, 0, 0, 1, 1, 0, 0, 0);\n" + " Atom ac = XInternAtom(d, \"_NET_SUPPORTING_WM_CHECK\", False);\n" + " Atom an = XInternAtom(d, \"_NET_WM_NAME\", False);\n" + " Atom ap = XInternAtom(d, \"_NET_WM_PID\", False);\n" + " Atom au = XInternAtom(d, \"UTF8_STRING\", False);\n" + " unsigned long pid = (unsigned long)getpid();\n" + " XChangeProperty(d, w, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n" + " XChangeProperty(d, w, an, au, 8, PropModeReplace, (unsigned char *)\"i3\", 2);\n" + " XChangeProperty(d, w, ap, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);\n" + " XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&w, 1);\n" + " XSync(d, False);\n" + " while (alive) { struct timespec ts = {0, 100000000L}; nanosleep(&ts, NULL); }\n" + " XDestroyWindow(d, w);\n" + " XCloseDisplay(d);\n" + " return 0;\n" + "}\n" + ) + subprocess.run([cc, "-O2", wm_c, "-o", wm_bin] + compile_x11_flags(), check=True) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + wm_proc = None + dpy = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy + root = X11.XDefaultRootWindow(dpy) + wm_proc = subprocess.Popen([wm_bin], env=env) + assert wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0) + + sw = subprocess.run([REPLACE_BIN, "--switch-session"], env=env, capture_output=True, text=True) + assert sw.returncode == 0, sw.stderr + assert wait_until(lambda: wm_proc.poll() is not None, timeout=4.0), "PID fallback did not stop WM after i3-msg failure" + with open(seen_file, "r", encoding="utf-8") as f: + assert f.read().strip() == "UNSET", "anode-replace did not unset stale I3SOCK before invoking i3-msg" + finally: + terminate(wm_proc) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + def main(): if not shutil.which("Xvfb"): print("test_replace: Xvfb not installed (skipping)") @@ -377,6 +794,10 @@ def main(): test_fastfetch_identity() test_icccm_replace_and_client_preservation() test_non_icccm_wm_fallback_replace() + test_anode_session_holds_open_on_replace() + test_dm_session_leader_guard() + test_switch_session_xprofile_handoff() + test_switch_session_stale_i3sock_fallback() print("test_replace: OK") return 0 diff --git a/tests/test_theme_scale.py b/tests/test_theme_scale.py index bb06a4f..1c78dee 100755 --- a/tests/test_theme_scale.py +++ b/tests/test_theme_scale.py @@ -34,13 +34,13 @@ def parse_xres(path): def test_fractional_scales(): scales = [ - ("0.75", 72, "1", 11), - ("1.00", 96, "1", 15), - ("1.25", 120, "1", 19), - ("1.50", 144, "1", 23), - ("1.75", 168, "2", 26), - ("2.00", 192, "2", 30), - ("2.50", 240, "3", 38), + ("0.75", 72, "1", "1.0", 11, 16, 16), + ("1.00", 96, "1", "1.0", 15, 24, 24), + ("1.25", 120, "1", "1.0", 19, 24, 24), + ("1.50", 144, "1", "1.0", 23, 32, 32), + ("1.75", 168, "2", "0.5", 26, 32, 16), + ("2.00", 192, "2", "0.5", 30, 48, 24), + ("2.50", 240, "3", "0.333", 38, 48, 16), ] with tempfile.TemporaryDirectory() as tmp: env = dict(os.environ) @@ -50,33 +50,81 @@ def test_fractional_scales(): env["ANODE_PREFIX"] = ROOT env["ANODE_NO_SIGNAL"] = "1" - for s_str, exp_dpi, exp_gdk, exp_px in scales: + for s_str, exp_dpi, exp_gdk, exp_gdk_dpi, exp_px, exp_cur, exp_gtk_cur in scales: run_env(env, [APPLY_SCALE, s_str, "--touch=1"]) scale_env_p = os.path.join(tmp, ".config", "anode", "scale.env") with open(scale_env_p, "r", encoding="utf-8") as f: senv = f.read() assert f'export GDK_SCALE="{exp_gdk}"' in senv, senv - assert 'export GDK_DPI_SCALE="1.0"' in senv, senv + assert f'export GDK_DPI_SCALE="{exp_gdk_dpi}"' in senv, senv assert f'export QT_SCALE_FACTOR="{s_str}"' in senv, senv assert 'export QT_FONT_DPI="96"' in senv, senv assert 'export QT_AUTO_SCREEN_SCALE_FACTOR="0"' in senv, senv assert 'export QT_SCALE_FACTOR_ROUNDING_POLICY="PassThrough"' in senv, senv + assert f'export XCURSOR_SIZE="{exp_cur}"' in senv, senv + + scale_conf_p = os.path.join(tmp, ".config", "anode", "scale.conf") + with open(scale_conf_p, "r", encoding="utf-8") as f: + sconf = f.read() + assert f"XCURSOR_SIZE={exp_cur}" in sconf, sconf xres = parse_xres(os.path.join(tmp, ".Xresources")) assert int(xres["Xft.dpi"]) == exp_dpi, f"scale={s_str} dpi={xres['Xft.dpi']}" assert int(xres["theme.baseFontSize"]) == exp_px, f"scale={s_str} base={xres['theme.baseFontSize']}" + assert int(xres["Xcursor.size"]) == exp_cur, f"scale={s_str} cur={xres['Xcursor.size']}" assert xres["theme.fontFace"] == "Fira Code" assert "Fira Code" in xres["st.font"] and f"pixelsize={exp_px}" in xres["st.font"] assert "Fira Code" in xres["dwm.font"] and f"{exp_px}px" in xres["dwm.font"] assert xres["*TkTheme"] == "gtkTtk" assert xres["theme.touchMode"] == "1" - # Verify xsettingsd omits Xft/DPI so GTK3 does not double-scale + # Verify xsettingsd omits Xft/DPI and keeps unscaled logical pt + GDK-adjusted cursor xs_p = os.path.join(tmp, ".config", "xsettingsd", "xsettingsd.conf") with open(xs_p, "r", encoding="utf-8") as f: xs = f.read() assert "Xft/DPI" not in xs, f"Xft/DPI must not exist in xsettingsd.conf:\n{xs}" assert f"Gdk/WindowScalingFactor {exp_gdk}" in xs, xs + assert 'Gtk/FontName "Fira Code 10"' in xs, xs + assert f"Gtk/CursorThemeSize {exp_gtk_cur}" in xs, xs + + with open(os.path.join(tmp, ".gtkrc-2.0"), "r", encoding="utf-8") as f: + gtk2 = f.read() + assert 'gtk-font-name="Fira Code 10"' in gtk2, gtk2 + assert f"gtk-cursor-theme-size={exp_cur}" in gtk2, gtk2 + + for gver in ("gtk-3.0", "gtk-4.0"): + with open(os.path.join(tmp, ".config", gver, "settings.ini"), "r", encoding="utf-8") as f: + gini = f.read() + assert "gtk-font-name=Fira Code 10" in gini, gini + assert f"gtk-cursor-theme-size={exp_gtk_cur}" in gini, gini + with open(os.path.join(tmp, ".config", gver, "gtk.css"), "r", encoding="utf-8") as f: + gcss = f.read() + assert "@define-color" in gcss, gcss + for bad in ("min-height:", "min-width:", "padding:", "margin:", "font-family:"): + assert bad not in gcss, f"Unexpected {bad} in .config/{gver}/gtk.css" + + tcss_p = os.path.join(tmp, ".themes", "ANODE-AnodeDefault", gver, "gtk.css") + with open(tcss_p, "r", encoding="utf-8") as f: + tcss = f.read() + exp_imp = ( + '@import url("resource:///org/gtk/libgtk/theme/Default/Default-dark.css");' + if gver == "gtk-4.0" + else '@import url("resource:///org/gtk/libgtk/theme/Adwaita/gtk-contained-dark.css");' + ) + assert tcss.splitlines()[0] == exp_imp, tcss.splitlines()[:3] + for bad in ("min-height:", "min-width:", "padding:", "margin:", "font-family:"): + assert bad not in tcss, f"Unexpected {bad} in theme {gver}/gtk.css" + + for qver in ("qt5ct", "qt6ct"): + with open(os.path.join(tmp, ".config", qver, f"{qver}.conf"), "r", encoding="utf-8") as f: + qconf = f.read() + assert 'general="Fira Code,10,' in qconf, qconf + assert 'fixed="Fira Code,10,' in qconf, qconf + + with open(os.path.join(tmp, ".config", "dunst", "dunstrc"), "r", encoding="utf-8") as f: + drc = f.read() + assert "scale = 1" in drc, drc + assert f"font = Fira Code {exp_px}px" in drc, drc # Verify Qt5 + Qt6 + Kvantum + Dunst + GTK2/3/4 files for p in [ @@ -138,7 +186,158 @@ def test_all_22_themes_and_legacy_192dpi_import(): assert int(xres["dwm.borderpx"]) == 2, xres["dwm.borderpx"] +def test_st_overrides_and_xresources_local(): + with tempfile.TemporaryDirectory() as tmp: + env = dict(os.environ) + env.pop("DISPLAY", None) + env["HOME"] = tmp + env["XDG_CONFIG_HOME"] = os.path.join(tmp, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + run_env(env, [APPLY_SCALE, "1.50", "--touch=0", "--no-apply"]) + + xres_p = os.path.join(tmp, ".Xresources") + with open(xres_p, "w", encoding="utf-8") as f: + f.write("St.font: Fira Code:size=14:antialias=true:autohint=true\n") + f.write("St.alpha: 0.95\n") + + # Repeated theme applications must preserve St.* cleanly without duplication + run_env(env, [APPLY_THEME, "AnodeDefault"]) + run_env(env, [APPLY_THEME, "AnodeDefault"]) + with open(xres_p, "r", encoding="utf-8") as f: + content = f.read() + assert content.count("St.font:") == 1, content + assert content.count("St.alpha:") == 1, content + assert "St.font: Fira Code:size=14:antialias=true:autohint=true" in content, content + + # Adding Xresources.local must replace duplicate keys from preserved section and persist + local_p = os.path.join(tmp, ".config", "anode", "Xresources.local") + with open(local_p, "w", encoding="utf-8") as f: + f.write("St.font: Fira Code:size=16:antialias=true\n") + f.write("*.cursorBlink: true\n") + + run_env(env, [APPLY_THEME, "AnodeDefault"]) + run_env(env, [APPLY_THEME, "AnodeDefault"]) + with open(xres_p, "r", encoding="utf-8") as f: + content2 = f.read() + assert content2.count("St.font:") == 1, content2 + assert content2.count("St.alpha:") == 1, content2 + assert content2.count("*.cursorBlink:") == 1, content2 + assert "St.font: Fira Code:size=16:antialias=true" in content2, content2 + + +def test_auto_scale_honors_explicit_server_dpi(): + with tempfile.TemporaryDirectory() as tmp: + fbin = os.path.join(tmp, "bin") + os.makedirs(fbin) + xdpy_p = os.path.join(fbin, "xdpyinfo") + xrandr_p = os.path.join(fbin, "xrandr") + with open(xdpy_p, "w", encoding="utf-8") as f: + f.write("#!/bin/sh\necho ' dimensions: 1920x1200 pixels (338x211 millimeters)'\necho ' resolution: 144x144 dots per inch'\n") + with open(xrandr_p, "w", encoding="utf-8") as f: + f.write("#!/bin/sh\necho 'eDP connected primary 1920x1200+0+0 (normal left inverted right x axis y axis) 301mm x 188mm'\n") + os.chmod(xdpy_p, 0o755) + os.chmod(xrandr_p, 0o755) + + env = dict(os.environ) + env["DISPLAY"] = ":99" + env["HOME"] = tmp + env["XDG_CONFIG_HOME"] = os.path.join(tmp, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["PATH"] = fbin + ":" + env.get("PATH", "") + + run_env(env, [APPLY_SCALE, "auto", "--no-apply"]) + with open(os.path.join(tmp, ".config", "anode", "scale.conf"), "r", encoding="utf-8") as f: + sconf = f.read() + assert "SCALE=1.50" in sconf, sconf + assert "XCURSOR_SIZE=32" in sconf, sconf + + +def test_stale_env_does_not_override_scale_conf(): + with tempfile.TemporaryDirectory() as tmp: + env = dict(os.environ) + env.pop("DISPLAY", None) + env["HOME"] = tmp + env["XDG_CONFIG_HOME"] = os.path.join(tmp, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["ANODE_NO_DBUS"] = "1" + + run_env(env, [APPLY_SCALE, "2.00", "--touch=1"]) + + stale_env = dict(env) + stale_env["ANODE_SCALE"] = "2.00" + stale_env["ANODE_TOUCH"] = "1" + run_env(stale_env, [APPLY_SCALE, "1.25", "--touch=0"]) + + with open(os.path.join(tmp, ".config", "anode", "scale.conf"), "r", encoding="utf-8") as f: + sconf = f.read() + assert "SCALE=1.25" in sconf and "TOUCH=0" in sconf, sconf + + with open(os.path.join(tmp, ".config", "anode", "scale.env"), "r", encoding="utf-8") as f: + senv = f.read() + assert 'export ANODE_SCALE="1.25"' in senv and 'export ANODE_TOUCH="0"' in senv, senv + + xres = parse_xres(os.path.join(tmp, ".Xresources")) + assert xres["theme.scale"] == "1.25", xres["theme.scale"] + assert xres["Xft.dpi"] == "120", xres["Xft.dpi"] + assert xres["theme.touchMode"] == "0", xres["theme.touchMode"] + + with open(os.path.join(tmp, ".config", "dunst", "dunstrc"), "r", encoding="utf-8") as f: + assert "font = Fira Code 19px" in f.read() + with open(os.path.join(tmp, ".config", "gtk-3.0", "settings.ini"), "r", encoding="utf-8") as f: + assert "gtk-cursor-theme-size=24" in f.read() + + # Re-applying theme with stale ANODE_SCALE/ANODE_TOUCH still honors scale.conf + run_env(stale_env, [APPLY_THEME, "AnodeDefault"]) + xres2 = parse_xres(os.path.join(tmp, ".Xresources")) + assert xres2["theme.scale"] == "1.25" and xres2["Xft.dpi"] == "120" and xres2["theme.touchMode"] == "0" + + +def test_gtk_theme_light_dark_detection_and_css_parse(): + with tempfile.TemporaryDirectory() as tmp: + env = dict(os.environ) + env.pop("DISPLAY", None) + env["HOME"] = tmp + env["XDG_CONFIG_HOME"] = os.path.join(tmp, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + run_env(env, [APPLY_SCALE, "1.25", "--touch=0", "--no-apply"]) + + for light_th in ("CatppuccinLatte", "GruvboxLight", "SolarizedLight"): + run_env(env, [APPLY_THEME, light_th]) + with open(os.path.join(tmp, ".config", "gtk-3.0", "settings.ini"), "r", encoding="utf-8") as f: + assert "gtk-application-prefer-dark-theme=0" in f.read() + t3 = os.path.join(tmp, ".themes", f"ANODE-{light_th}", "gtk-3.0", "gtk.css") + t4 = os.path.join(tmp, ".themes", f"ANODE-{light_th}", "gtk-4.0", "gtk.css") + with open(t3, "r", encoding="utf-8") as f: + txt3 = f.read() + with open(t4, "r", encoding="utf-8") as f: + txt4 = f.read() + assert txt3.splitlines()[0] == '@import url("resource:///org/gtk/libgtk/theme/Adwaita/gtk-contained.css");' + assert txt4.splitlines()[0] == '@import url("resource:///org/gtk/libgtk/theme/Default/Default-light.css");' + + run_env(env, [APPLY_THEME, "AnodeDefault"]) + t3_dark = os.path.join(tmp, ".themes", "ANODE-AnodeDefault", "gtk-3.0", "gtk.css") + try: + import gi + gi.require_version("Gtk", "3.0") + from gi.repository import Gtk + prov = Gtk.CssProvider() + errs = [] + prov.connect("parsing-error", lambda p, s, e: errs.append(str(e))) + prov.load_from_path(t3_dark) + assert not errs, f"GTK3 CSS parse errors: {errs}" + except ImportError: + pass + + if __name__ == "__main__": test_fractional_scales() test_all_22_themes_and_legacy_192dpi_import() - print("test_theme_scale: ALL PASSED (7 fractional scales, 22 themes, legacy 192-DPI import)") + test_st_overrides_and_xresources_local() + test_auto_scale_honors_explicit_server_dpi() + test_stale_env_does_not_override_scale_conf() + test_gtk_theme_light_dark_detection_and_css_parse() + print("test_theme_scale: ALL PASSED (7 fractional scales, 22 themes, legacy 192-DPI import, St overrides, auto DPI, scale.conf precedence, GTK light/dark)") diff --git a/tests/test_units.c b/tests/test_units.c index 6ccf727..adeafda 100644 --- a/tests/test_units.c +++ b/tests/test_units.c @@ -13,6 +13,7 @@ #include "anode_bt_list.h" #include "anode_power_policy.h" #include "anode_xkb_parse.h" +#include "anode_sys_parse.h" #include "anode-touch-gesture.h" static void test_scale_math(void) { @@ -152,16 +153,20 @@ static void test_power_policy_and_gestures(void) { anode_power_policy_step(&cfg, &st, 10000, false, 80, true, false, &act); assert(st == ANODE_PWR_ACTIVE && !act.dim_now); - anode_power_policy_step(&cfg, &st, 65000, false, 80, true, false, &act); + anode_power_policy_step(&cfg, &st, 305000, false, 80, true, false, &act); assert(st == ANODE_PWR_DIMMED && act.dim_now); anode_power_policy_step(&cfg, &st, 1000, false, 80, true, false, &act); assert(st == ANODE_PWR_ACTIVE && act.restore_brightness); - anode_power_policy_step(&cfg, &st, 190000, false, 80, true, false, &act); + anode_power_policy_step(&cfg, &st, 610000, false, 80, true, false, &act); assert(st == ANODE_PWR_LOCKED && act.lock_now); - anode_power_policy_step(&cfg, &st, 610000, false, 80, true, true, &act); + /* Waking from ANODE_PWR_LOCKED must also restore dimmed brightness */ + anode_power_policy_step(&cfg, &st, 1000, false, 80, true, false, &act); + assert(st == ANODE_PWR_ACTIVE && act.restore_brightness); + + anode_power_policy_step(&cfg, &st, 1810000, false, 80, true, true, &act); assert(st == ANODE_PWR_SUSPENDED && act.suspend_now); /* Critical low battery override on battery */ @@ -225,6 +230,45 @@ static void test_xkb_layout_parser(void) { assert(!anode_xkb_layout_from_group_name("!!!", buf, sizeof(buf))); } +static void test_sys_parsers(void) { + anode_cpu_sample_t prev = {0, 0}, cur = {0, 0}; + const char *stat1 = + "cpu 100 0 50 850 0 0 0 0 0 0\n" + "cpu0 50 0 25 425 0 0 0 0 0 0\n"; + const char *stat_25 = + "cpu 300 0 100 1550 50 0 0 0 0 0\n" + "cpu0 150 0 50 775 25 0 0 0 0 0\n"; + const char *stat_idle = "cpu 300 0 100 2550 50 0 0 0 0 0\n"; + const char *stat_full = "cpu 1300 0 100 2550 50 0 0 0 0 0\n"; + + assert(anode_parse_proc_stat_cpu(stat1, &prev)); + assert(prev.total == 1000 && prev.idle == 850); + assert(anode_parse_proc_stat_cpu(stat_25, &cur)); + assert(cur.total == 2000 && cur.idle == 1600); + assert(anode_cpu_usage_pct(&prev, &cur) == 25); + assert(anode_cpu_usage_pct(&cur, &cur) == 0); + assert(anode_cpu_usage_pct(&cur, &prev) == 0); + + anode_cpu_sample_t idle_s = {0, 0}, full_s = {0, 0}; + assert(anode_parse_proc_stat_cpu(stat_idle, &idle_s)); + assert(anode_cpu_usage_pct(&cur, &idle_s) == 0); + assert(anode_parse_proc_stat_cpu(stat_full, &full_s)); + assert(anode_cpu_usage_pct(&idle_s, &full_s) == 100); + assert(!anode_parse_proc_stat_cpu("intr 1 2 3\n", &cur)); + assert(!anode_parse_proc_stat_cpu("cpu 10 20\n", &cur)); + + int ram = -1; + assert(anode_parse_proc_meminfo_pct( + "MemTotal: 1000000 kB\nMemFree: 100000 kB\nMemAvailable: 250000 kB\n", &ram)); + assert(ram == 75); + assert(anode_parse_proc_meminfo_pct( + "MemTotal: 1000000 kB\nMemFree: 100000 kB\nBuffers: 100000 kB\n" + "Cached: 300000 kB\nSReclaimable: 100000 kB\n", &ram)); + assert(ram == 40); + assert(!anode_parse_proc_meminfo_pct("MemFree: 100 kB\n", &ram)); + assert(!anode_parse_proc_meminfo_pct("MemTotal: 0 kB\nMemFree: 0 kB\n", &ram)); +} + static void test_platform_probe(void) { anode_net_iface_t ifs[ANODE_MAX_IFACES]; int n = anode_list_net_ifaces(ifs, ANODE_MAX_IFACES); @@ -232,6 +276,15 @@ static void test_platform_probe(void) { anode_battery_info_t bat; anode_read_battery(&bat); (void)anode_detect_audio_backend(); + anode_cpu_sample_t cpu = {0, 0}; + int ram_pct = -1; +#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) + assert(anode_read_cpu_sample(&cpu) && cpu.total > 0); + assert(anode_read_mem_usage_pct(&ram_pct) && ram_pct >= 0 && ram_pct <= 100); +#else + (void)anode_read_cpu_sample(&cpu); + (void)anode_read_mem_usage_pct(&ram_pct); +#endif char buf[256]; anode_runtime_dir(buf, sizeof(buf)); assert(buf[0] == '/'); @@ -247,6 +300,7 @@ int main(void) { test_wifi_and_bt_parsers(); test_power_policy_and_gestures(); test_xkb_layout_parser(); + test_sys_parsers(); 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 dd91d6e..b805bd5 100755 --- a/tests/test_x11_xvfb.py +++ b/tests/test_x11_xvfb.py @@ -253,6 +253,20 @@ def test_resolution(res_str, scale_str, width, height): time.sleep(0.25) X11.XGetWindowAttributes(dpy, tray_win, ctypes.byref(tray_attr)) assert tray_attr.height >= pre_h, f"Tray height did not preserve/scale after SIGUSR1: {tray_attr.height} vs {pre_h}" + + # Stale exported ANODE_SCALE must not block live scale updates + SIGUSR1 reload + stale_env = dict(env) + stale_env["ANODE_SCALE"] = "2.00" + stale_env["ANODE_TOUCH"] = "1" + stale_env["ANODE_NO_DBUS"] = "1" + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), "1.25", "--touch=0"], env=stale_env, check=True) + if shutil.which("xrdb"): + xq = subprocess.check_output(["xrdb", "-query"], env=env, text=True) + assert "theme.scale:\t1.25" in xq or "theme.scale: 1.25" in xq, xq + dwm.send_signal(signal.SIGUSR1) + time.sleep(0.2) + assert dwm.poll() is None, "dwm exited after SIGUSR1 live scale update" + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), scale_str, "--touch=1"], env=env, check=True) dwm.send_signal(signal.SIGUSR1) time.sleep(0.2) @@ -273,7 +287,7 @@ 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 and tracks XKB layout left of datetime + # Test anode-statusd publishes CPU/RAM (never net/docker0) and lowercase XKB left of datetime sd = subprocess.Popen([os.path.join(BUILD, "daemons", "anode-statusd")], env=env) procs.append(sd) @@ -290,9 +304,14 @@ def test_resolution(res_str, scale_str, width, height): s = get_status() if not s: return None + assert "NET " not in s and "docker" not in s.lower(), f"Unexpected network segment in status: {s!r}" parts = [p.strip() for p in s.split("|")] if len(parts) < 4: return None + if not any(re.fullmatch(r"CPU \d+%", p) for p in parts): + return None + if not any(re.fullmatch(r"RAM \d+%", p) for p in parts): + return None if not re.fullmatch(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}", parts[-1]): return None kbd = parts[-2] @@ -319,6 +338,43 @@ def test_resolution(res_str, scale_str, width, height): assert wait_until(lambda: get_kbd_left_of_dt() == "us"), f"Expected 'us' restore: {get_status()!r}" terminate(sd) + # Test dmenu -l 0 (fills full screen height) vs dmenu -l 5 (exact list height) + dm_full = subprocess.Popen( + [os.path.join(BUILD, "dmenu", "dmenu"), "-l", "0"], + env=env, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + procs.append(dm_full) + dm_full.stdin.write(b"\n".join(f"item{i}".encode() for i in range(60)) + b"\n") + dm_full.stdin.close() + def find_win_with_height(target_min_w, check_fn): + for w in query_children(dpy, root): + a = XWindowAttributes() + if X11.XGetWindowAttributes(dpy, w, ctypes.byref(a)) and a.map_state == 2 and a.width >= target_min_w: + if check_fn(a.height): + return a.height + return None + h_full = wait_until(lambda: find_win_with_height(width - 10, lambda hh: hh == height)) + assert h_full == height, f"dmenu -l 0 did not fill screen height {height}: got {h_full}" + terminate(dm_full) + + dm_five = subprocess.Popen( + [os.path.join(BUILD, "dmenu", "dmenu"), "-l", "5"], + env=env, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + procs.append(dm_five) + dm_five.stdin.write(b"\n".join(f"item{i}".encode() for i in range(60)) + b"\n") + dm_five.stdin.close() + h_five = wait_until(lambda: find_win_with_height(width - 10, lambda hh: 100 <= hh < height)) + assert h_five and h_five < height, f"dmenu -l 5 height invalid: {h_five} vs {height}" + terminate(dm_five) + + # Test anode-checkpw rejects wrong password cleanly + chk = subprocess.run( + [os.path.join(BUILD, "daemons", "anode-checkpw")], + input="definitely_wrong_pw_12345\n", env=env, capture_output=True, text=True, timeout=3, + ) + assert chk.returncode != 0 + # Test core + GemUI utilities launch, map cleanly inside screen, and exit cleanly for bin_path, extra_stdin in [ (os.path.join(BUILD, "st", "st"), None), @@ -350,6 +406,99 @@ def test_resolution(res_str, scale_str, width, height): terminate(xvfb) +def test_st_font_override_and_dunst(): + disp = pick_display() + with tempfile.TemporaryDirectory() as home: + env = dict(os.environ) + env["DISPLAY"] = disp + env["HOME"] = home + env["XDG_CONFIG_HOME"] = os.path.join(home, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["LD_LIBRARY_PATH"] = os.path.join(BUILD, "libgemui") + (":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "") + env["PATH"] = ( + os.path.join(BUILD, "dwm") + ":" + + os.path.join(BUILD, "st") + ":" + + os.path.join(ROOT, "scripts") + ":" + + env.get("PATH", "") + ) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1920x1200x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dpy = None + procs = [] + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode())) + assert dpy, f"Failed to open Xvfb {disp}" + root = X11.XDefaultRootWindow(dpy) + + def launch_st_and_get_height_inc(xres_text): + xr_path = os.path.join(home, ".Xresources") + with open(xr_path, "w", encoding="utf-8") as f: + f.write(xres_text) + if shutil.which("xrdb"): + subprocess.run(["xrdb", "-load", xr_path], env=env, check=True) + before = set(query_children(dpy, root)) + stp = subprocess.Popen( + [os.path.join(BUILD, "st", "st"), "-e", "sh", "-c", "sleep 4"], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + procs.append(stp) + + def get_inc(): + for w in query_children(dpy, root): + if w in before: + continue + a = XWindowAttributes() + if X11.XGetWindowAttributes(dpy, w, ctypes.byref(a)) and a.map_state == 2: + out = subprocess.check_output(["xprop", "-id", hex(w), "WM_NORMAL_HINTS"], env=env, text=True) + m = re.search(r"resize increment:\s*\d+\s+by\s+(\d+)", out) + if m: + return int(m.group(1)) + return None + + inc = wait_until(get_inc) + terminate(stp) + procs.remove(stp) + return inc + + if shutil.which("xprop"): + inc_small = launch_st_and_get_height_inc( + "Xft.dpi: 144\nst.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true\n" + ) + assert inc_small and inc_small <= 22, f"Expected pixelsize=15 height_inc <= 22, got {inc_small}" + + inc_override = launch_st_and_get_height_inc( + "Xft.dpi: 144\nst.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true\n" + "St.font: Fira Code:size=14:antialias=true:autohint=true\n" + ) + assert inc_override and inc_override >= 32, f"Expected St.font size=14 @ 144 DPI height_inc >= 32, got {inc_override}" + + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), "1.50", "--touch=0"], env=env, check=True) + dunstrc = os.path.join(home, ".config", "dunst", "dunstrc") + if shutil.which("dunst"): + denv = dict(env) + denv.pop("DBUS_SESSION_BUS_ADDRESS", None) + dp = subprocess.Popen( + ["dunst", "-conf", dunstrc, "-verbosity", "debug"], + env=denv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + time.sleep(0.4) + terminate(dp) + dout, derr = dp.communicate(timeout=3) + combined = dout + "\n" + derr + assert "Trying to set scale to 1" in combined, combined + assert "Fira Code 23px" in combined, combined + finally: + for p in reversed(procs): + terminate(p) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + def main(): if not shutil.which("Xvfb"): print("test_x11_xvfb: Xvfb not installed (skipping)") @@ -362,6 +511,8 @@ def main(): for res, sc, w, h in cases: test_resolution(res, sc, w, h) print(f"test_x11_xvfb: {res} @ {sc}x OK") + test_st_font_override_and_dunst() + print("test_x11_xvfb: St.font override & Dunst scale=1 OK") return 0