fix(replace,wm,autostart): preserve workspaces across slow/3rd-party replace and guard polkit agent startup

This commit is contained in:
Luxferre committed 2026-11-27 09:06:02 +02:00
1 parent 4ec3f59e02
commit c5ce065c33
6 files changed
+759 -53

No files matched your search

+164 -8
View File
@@ -120,6 +120,143 @@ if [ -n "$PROFILE" ]; then
fi fi
fi fi
MY_UID="$(id -u)"
SELF_PID="$$"
LAUNCHED_BASES=":"
norm_display() {
case "${1:-}" in
*.0) printf '%s\n' "${1%.0}" ;;
*) printf '%s\n' "${1:-}" ;;
esac
}
is_polkit_agent_base() {
case "${1:-}" in
lxpolkit|polkit-gnome-authentication-agent-1|polkit-mate-authentication-agent-1|polkit-kde-authentication-agent-1|xfce-polkit|lxqt-policykit-agent|mate-polkit)
return 0
;;
esac
return 1
}
is_generic_wrapper_base() {
case "${1:-}" in
sh|bash|dash|ksh|zsh|ash|env|nohup|setsid|st|xterm|urxvt|alacritty|kitty|python|python3|perl|ruby|true|false|echo|printf)
return 0
;;
esac
return 1
}
polkit_agent_running_on_display() {
_cands="$( (ps -eo uid=,pid=,comm= 2>/dev/null || ps -ax -o uid=,pid=,comm= 2>/dev/null || true) | awk -v myuid="$MY_UID" -v self="$SELF_PID" '
$1 == myuid && $2 > 1 && $2 != self {
c = $3
sub(/^.*\//, "", c)
if (c == "lxpolkit" ||
c == "polkit-gnome-authentication-agent-1" ||
c == "polkit-mate-authentication-agent-1" ||
c == "polkit-kde-authentication-agent-1" ||
c == "xfce-polkit" ||
c == "lxqt-policykit-agent" ||
c == "mate-polkit") {
print $2
}
}
' )"
[ -n "${_cands:-}" ] || return 1
if [ -n "${DISPLAY:-}" ] && [ -d "/proc/$SELF_PID" ]; then
_cur_disp="$(norm_display "$DISPLAY")"
for _cpid in $_cands; do
[ -r "/proc/$_cpid/environ" ] || continue
_pdisp="$(tr '\0' '\n' < "/proc/$_cpid/environ" 2>/dev/null | awk 'substr($0, 1, 8) == "DISPLAY=" { print substr($0, 9); exit }' || true)"
[ -n "${_pdisp:-}" ] || continue
if [ "$(norm_display "$_pdisp")" = "$_cur_disp" ]; then
return 0
fi
done
return 1
fi
return 0
}
polkit_session_is_invalid() {
[ "${ANODE_FORCE_POLKIT_AGENT:-0}" = "1" ] && return 1
command -v loginctl >/dev/null 2>&1 || return 1
_has_sess="$(loginctl list-sessions 2>/dev/null | awk '
NF >= 2 && $1 != "SESSION" && $1 !~ /listed\.$/ && $2 ~ /^[0-9]+$/ { print $1; exit }
' || true)"
[ -n "${_has_sess:-}" ] || return 1
_sid=""
if [ -r "/proc/$SELF_PID/cgroup" ]; then
_sid="$(awk -F/ '
{
s = $NF
if (s ~ /^session-.*\.scope$/) {
sub(/^session-/, "", s)
sub(/\.scope$/, "", s)
if (s != "") { print s; exit }
} else if ($1 ~ /^0:/ && s != "" && s !~ /\.(slice|service|scope)$/) {
print s
exit
}
}
' "/proc/$SELF_PID/cgroup" 2>/dev/null || true)"
fi
if [ -z "${_sid:-}" ]; then
_sid="${XDG_SESSION_ID:-}"
fi
[ -n "${_sid:-}" ] || return 1
if ! loginctl show-session "$_sid" >/dev/null 2>&1; then
return 0
fi
return 1
}
should_skip_launch() {
_kind="$1"
_base="$2"
[ -n "${_base:-}" ] || return 1
if is_polkit_agent_base "$_base"; then
case "$LAUNCHED_BASES" in
*":$_base:"*) return 0 ;;
esac
if polkit_agent_running_on_display; then
return 0
fi
if polkit_session_is_invalid; then
return 0
fi
return 1
fi
case "$_kind" in
exec_once)
case "$LAUNCHED_BASES" in
*":$_base:"*) return 0 ;;
esac
if is_proc_running "$_base"; then
return 0
fi
;;
desktop)
if ! is_generic_wrapper_base "$_base"; then
case "$LAUNCHED_BASES" in
*":$_base:"*) return 0 ;;
esac
if is_proc_running "$_base"; then
return 0
fi
fi
;;
esac
return 1
}
# Extract executable basename from a shell command line for exec_once tracking # Extract executable basename from a shell command line for exec_once tracking
cmd_exec_base() { cmd_exec_base() {
awk -v raw="$1" 'BEGIN { awk -v raw="$1" 'BEGIN {
@@ -300,16 +437,17 @@ run_declarative_files() {
fi fi
_tab="$(printf '\t')" _tab="$(printf '\t')"
printf '%s\n' "$_parsed" | while IFS="$_tab" read -r _kind _cmd; do while IFS="$_tab" read -r _kind _cmd; do
[ -n "${_kind:-}" ] || continue [ -n "${_kind:-}" ] || continue
case "$MODE:$_kind" in case "$MODE:$_kind" in
reload:exec|reload:exec_once) reload:exec|reload:exec_once)
continue continue
;; ;;
esac esac
if [ "$_kind" = "exec_once" ] && [ "$DRY_RUN" != "1" ]; then _base=""
if [ "$DRY_RUN" != "1" ]; then
_base="$(cmd_exec_base "$_cmd")" _base="$(cmd_exec_base "$_cmd")"
if is_proc_running "$_base"; then if should_skip_launch "$_kind" "$_base"; then
continue continue
fi fi
fi fi
@@ -317,8 +455,13 @@ run_declarative_files() {
printf '[%s] %s\n' "$_kind" "$_cmd" printf '[%s] %s\n' "$_kind" "$_cmd"
else else
launch_cmd "$_cmd" launch_cmd "$_cmd"
if [ -n "$_base" ] && ! is_generic_wrapper_base "$_base"; then
LAUNCHED_BASES="${LAUNCHED_BASES}${_base}:"
fi
fi fi
done done <<EOF
$_parsed
EOF
} }
# Parse a .desktop autostart file and print: # Parse a .desktop autostart file and print:
@@ -438,7 +581,13 @@ run_dir_dropins_and_xdg() {
if [ "$DRY_RUN" = "1" ]; then if [ "$DRY_RUN" = "1" ]; then
printf '[desktop] %s\n' "$_ecmd" printf '[desktop] %s\n' "$_ecmd"
else else
launch_cmd "$_ecmd" _base="$(cmd_exec_base "$_ecmd")"
if ! should_skip_launch desktop "$_base"; then
launch_cmd "$_ecmd"
if [ -n "$_base" ]; then
LAUNCHED_BASES="${LAUNCHED_BASES}${_base}:"
fi
fi
fi fi
fi fi
;; ;;
@@ -461,7 +610,9 @@ run_dir_dropins_and_xdg() {
_seen_xdg=":" _seen_xdg=":"
_old_ifs="$IFS" _old_ifs="$IFS"
IFS=: IFS=:
for _xbase in "$XDG_CONFIG_HOME" $XDG_CONFIG_DIRS; do set -- "$XDG_CONFIG_HOME" $XDG_CONFIG_DIRS
IFS="$_old_ifs"
for _xbase in "$@"; do
[ -n "$_xbase" ] || continue [ -n "$_xbase" ] || continue
_xdir="$_xbase/autostart" _xdir="$_xbase/autostart"
[ -d "$_xdir" ] || continue [ -d "$_xdir" ] || continue
@@ -482,14 +633,19 @@ run_dir_dropins_and_xdg() {
if [ "$DRY_RUN" = "1" ]; then if [ "$DRY_RUN" = "1" ]; then
printf '[desktop] %s\n' "$_ecmd" printf '[desktop] %s\n' "$_ecmd"
else else
launch_cmd "$_ecmd" _base="$(cmd_exec_base "$_ecmd")"
if ! should_skip_launch desktop "$_base"; then
launch_cmd "$_ecmd"
if [ -n "$_base" ]; then
LAUNCHED_BASES="${LAUNCHED_BASES}${_base}:"
fi
fi
fi fi
fi fi
;; ;;
esac esac
done done
done done
IFS="$_old_ifs"
fi fi
} }
+40 -7
View File
@@ -11,6 +11,7 @@ PROFILE="${ANODE_SESSION_PROFILE:-}"
KEEP_PANELS=0 KEEP_PANELS=0
FOREGROUND=0 FOREGROUND=0
NO_AUTOSTART=0 NO_AUTOSTART=0
FORCE_AUTOSTART=0
FORCE=0 FORCE=0
SWITCH_SESSION=0 SWITCH_SESSION=0
DRY_RUN=0 DRY_RUN=0
@@ -26,7 +27,8 @@ Options:
--profile NAME Pass session autostart profile NAME to anode-session --profile NAME Pass session autostart profile NAME to anode-session
--keep-panels Do not stop existing panel, notification, or xsettings daemons --keep-panels Do not stop existing panel, notification, or xsettings daemons
--foreground Exec anode-session in the foreground instead of detaching --foreground Exec anode-session in the foreground instead of detaching
--no-autostart Skip anode-autostart start during replacement --no-autostart Skip anode-autostart completely during replacement
--autostart Run full anode-autostart start even during replacement
--force Proceed with in-place replacement even if WM is DM session leader --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) --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 --dry-run Print detected WM and planned actions without replacing
@@ -55,6 +57,12 @@ while [ $# -gt 0 ]; do
;; ;;
--no-autostart) --no-autostart)
NO_AUTOSTART=1 NO_AUTOSTART=1
FORCE_AUTOSTART=0
shift
;;
--autostart)
FORCE_AUTOSTART=1
NO_AUTOSTART=0
shift shift
;; ;;
--force) --force)
@@ -474,6 +482,8 @@ if [ -n "$PROFILE" ]; then
fi fi
if [ "$NO_AUTOSTART" = "1" ]; then if [ "$NO_AUTOSTART" = "1" ]; then
set -- "$@" --no-autostart set -- "$@" --no-autostart
elif [ "$FORCE_AUTOSTART" = "1" ]; then
set -- "$@" --autostart
fi fi
if [ "$DRY_RUN" = "1" ]; then if [ "$DRY_RUN" = "1" ]; then
@@ -525,19 +535,35 @@ if [ "$KEEP_PANELS" != "1" ]; then
dunst xfce4-notifyd xsettingsd xfsettingsd dunst xfce4-notifyd xsettingsd xfsettingsd
fi fi
_snap_dir="${XDG_RUNTIME_DIR:-${TMPDIR:-/tmp}}"
[ -d "$_snap_dir" ] && [ -w "$_snap_dir" ] || _snap_dir="/tmp"
SNAP_READY_FILE="$_snap_dir/anode-replace-snap.$$"
rm -f "$SNAP_READY_FILE"
ANODE_REPLACE_SNAP_FILE="$SNAP_READY_FILE"
ANODE_REPLACE_PREV_WM_WIN="${PREV_WM_WIN:-}"
export ANODE_REPLACE_SNAP_FILE ANODE_REPLACE_PREV_WM_WIN
if [ "$FOREGROUND" = "1" ]; then if [ "$FOREGROUND" = "1" ]; then
if [ -n "${PREV_WM_PID:-}" ] && is_my_pid "$PREV_WM_PID"; then if [ -n "${PREV_WM_PID:-}" ] && is_my_pid "$PREV_WM_PID"; then
( (
_w=0
while [ "$_w" -lt 40 ] && [ ! -e "$SNAP_READY_FILE" ]; do
_w=$(( _w + 1 ))
sleep 0.1
done
sleep 1.5 sleep 1.5
_cur_win="$(get_root_wm_win || true)" _cur_win="$(get_root_wm_win || true)"
if [ -n "${PREV_WM_WIN:-}" ] && [ "$_cur_win" = "$PREV_WM_WIN" ] && kill -0 "$PREV_WM_PID" 2>/dev/null; then if [ -n "${PREV_WM_WIN:-}" ] && [ "$_cur_win" = "$PREV_WM_WIN" ] && kill -0 "$PREV_WM_PID" 2>/dev/null; then
kill -TERM "$PREV_WM_PID" 2>/dev/null || true kill -TERM "$PREV_WM_PID" 2>/dev/null || true
fi fi
rm -f "$SNAP_READY_FILE"
) </dev/null >/dev/null 2>&1 & ) </dev/null >/dev/null 2>&1 &
fi fi
exec "$ANODE_SESSION_BIN" "$@" exec "$ANODE_SESSION_BIN" "$@"
fi fi
trap 'rm -f "$SNAP_READY_FILE"' EXIT INT TERM
( (
trap '' HUP trap '' HUP
exec "$ANODE_SESSION_BIN" "$@" exec "$ANODE_SESSION_BIN" "$@"
@@ -545,19 +571,26 @@ fi
SESSION_PID=$! SESSION_PID=$!
_tick=0 _tick=0
_snap_tick=""
_fallback_sent=0 _fallback_sent=0
_replaced=0 _replaced=0
while [ "$_tick" -lt 50 ]; do while [ "$_tick" -lt 80 ]; do
if ! kill -0 "$SESSION_PID" 2>/dev/null; then if ! kill -0 "$SESSION_PID" 2>/dev/null; then
printf 'anode-replace: error: anode-session exited prematurely\n' >&2 printf 'anode-replace: error: anode-session exited prematurely\n' >&2
exit 1 exit 1
fi fi
if [ "$_tick" -ge 15 ] && [ "$_fallback_sent" = "0" ] && [ -n "${PREV_WM_PID:-}" ]; then if [ -z "$_snap_tick" ] && [ -e "$SNAP_READY_FILE" ]; then
_cur_win="$(get_root_wm_win || true)" _snap_tick="$_tick"
if [ -n "${PREV_WM_WIN:-}" ] && [ "$_cur_win" = "$PREV_WM_WIN" ] && is_my_pid "$PREV_WM_PID"; then fi
kill -TERM "$PREV_WM_PID" 2>/dev/null || true
_fallback_sent=1 if [ "$_fallback_sent" = "0" ] && [ -n "${PREV_WM_PID:-}" ]; then
if { [ -n "$_snap_tick" ] && [ $(( _tick - _snap_tick )) -ge 15 ]; } || [ "$_tick" -ge 45 ]; then
_cur_win="$(get_root_wm_win || true)"
if [ -n "${PREV_WM_WIN:-}" ] && [ "$_cur_win" = "$PREV_WM_WIN" ] && is_my_pid "$PREV_WM_PID"; then
kill -TERM "$PREV_WM_PID" 2>/dev/null || true
_fallback_sent=1
fi
fi fi
fi fi
+61 -14
View File
@@ -7,6 +7,7 @@ set -u
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
REPLACE_WM=0 REPLACE_WM=0
NO_AUTOSTART=0 NO_AUTOSTART=0
FORCE_AUTOSTART=0
while [ $# -gt 0 ]; do while [ $# -gt 0 ]; do
case "$1" in case "$1" in
@@ -28,6 +29,12 @@ while [ $# -gt 0 ]; do
;; ;;
--no-autostart) --no-autostart)
NO_AUTOSTART=1 NO_AUTOSTART=1
FORCE_AUTOSTART=0
shift
;;
--autostart)
FORCE_AUTOSTART=1
NO_AUTOSTART=0
shift shift
;; ;;
*) *)
@@ -94,7 +101,7 @@ for _envfile in "$ANODE_PREFIX/share/anode/env.sh" "$SCRIPT_DIR/../data/env.sh";
done done
unset _envfile unset _envfile
if [ -n "${DISPLAY:-}" ] && command -v anode-apply-display >/dev/null 2>&1; then if [ "$REPLACE_WM" != "1" ] && [ -n "${DISPLAY:-}" ] && command -v anode-apply-display >/dev/null 2>&1; then
anode-apply-display >/dev/null 2>&1 || true anode-apply-display >/dev/null 2>&1 || true
fi fi
if [ ! -f "$XDG_CONFIG_HOME/anode/scale.conf" ] && command -v anode-apply-scale >/dev/null 2>&1; then if [ ! -f "$XDG_CONFIG_HOME/anode/scale.conf" ] && command -v anode-apply-scale >/dev/null 2>&1; then
@@ -116,17 +123,22 @@ if [ "${ANODE_NO_DBUS:-0}" != "1" ]; then
fi fi
fi fi
DEFER_THEME_SYNC=0
if [ ! -f "$HOME/.Xresources" ] && command -v anode-apply-theme >/dev/null 2>&1; then if [ ! -f "$HOME/.Xresources" ] && command -v anode-apply-theme >/dev/null 2>&1; then
anode-apply-theme Anodized >/dev/null 2>&1 || true anode-apply-theme Anodized >/dev/null 2>&1 || true
elif [ -f "$HOME/.Xresources" ]; then elif [ -f "$HOME/.Xresources" ]; then
if command -v xrdb >/dev/null 2>&1; then if command -v xrdb >/dev/null 2>&1; then
xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true
fi fi
if command -v anode-sync-gtk-theme >/dev/null 2>&1; then if [ "$REPLACE_WM" = "1" ]; then
ANODE_NO_SIGNAL=1 anode-sync-gtk-theme "$HOME/.Xresources" >/dev/null 2>&1 || true DEFER_THEME_SYNC=1
fi else
if command -v anode-sync-dunst-theme >/dev/null 2>&1; then if command -v anode-sync-gtk-theme >/dev/null 2>&1; then
ANODE_NO_SIGNAL=1 anode-sync-dunst-theme "$HOME/.Xresources" >/dev/null 2>&1 || true ANODE_NO_SIGNAL=1 anode-sync-gtk-theme "$HOME/.Xresources" >/dev/null 2>&1 || true
fi
if command -v anode-sync-dunst-theme >/dev/null 2>&1; then
ANODE_NO_SIGNAL=1 anode-sync-dunst-theme "$HOME/.Xresources" >/dev/null 2>&1 || true
fi
fi fi
fi fi
@@ -137,7 +149,10 @@ fi
BG_PIDS="" BG_PIDS=""
spawn_bg() { spawn_bg() {
if command -v "$1" >/dev/null 2>&1; then if command -v "$1" >/dev/null 2>&1; then
"$@" >/dev/null 2>&1 & (
unset ANODE_REPLACE_SNAP_FILE ANODE_REPLACE_PREV_WM_WIN || true
exec "$@"
) </dev/null >/dev/null 2>&1 &
BG_PIDS="$BG_PIDS $!" BG_PIDS="$BG_PIDS $!"
fi fi
} }
@@ -161,6 +176,19 @@ if [ "${ANODE_TOUCH:-0}" = "1" ]; then
spawn_bg anode-vkbd spawn_bg anode-vkbd
fi fi
if [ "$DEFER_THEME_SYNC" = "1" ]; then
(
unset ANODE_REPLACE_SNAP_FILE ANODE_REPLACE_PREV_WM_WIN || true
if command -v anode-sync-gtk-theme >/dev/null 2>&1; then
anode-sync-gtk-theme "$HOME/.Xresources" >/dev/null 2>&1 || true
fi
if command -v anode-sync-dunst-theme >/dev/null 2>&1; then
anode-sync-dunst-theme "$HOME/.Xresources" >/dev/null 2>&1 || true
fi
) </dev/null >/dev/null 2>&1 &
BG_PIDS="$BG_PIDS $!"
fi
# Seed default user autostart files on first session launch # Seed default user autostart files on first session launch
mkdir -p "$XDG_CONFIG_HOME/anode/autostart.d" mkdir -p "$XDG_CONFIG_HOME/anode/autostart.d"
if [ ! -e "$XDG_CONFIG_HOME/anode/autostart" ]; then if [ ! -e "$XDG_CONFIG_HOME/anode/autostart" ]; then
@@ -173,12 +201,24 @@ if [ ! -e "$XDG_CONFIG_HOME/anode/autostart" ]; then
unset _tpl unset _tpl
fi fi
_prev_wm_id="${ANODE_REPLACE_PREV_WM_WIN:-}"
if [ "$REPLACE_WM" = "1" ] && [ -z "$_prev_wm_id" ] && [ -n "${DISPLAY:-}" ] && command -v xprop >/dev/null 2>&1; then
_prev_wm_id="$(xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | awk '
/window id/ {
for (i = 1; i <= NF; i++) {
if ($i ~ /^0x[0-9a-fA-F]+/) { sub(/,$/, "", $i); print $i; exit }
}
}
')"
fi
# Launch i3-style and XDG session autostart entries once ANODE DWM is ready # Launch i3-style and XDG session autostart entries once ANODE DWM is ready
if [ "$NO_AUTOSTART" != "1" ] && command -v anode-autostart >/dev/null 2>&1; then if [ "$NO_AUTOSTART" != "1" ] && command -v anode-autostart >/dev/null 2>&1; then
( (
unset ANODE_REPLACE_SNAP_FILE ANODE_REPLACE_PREV_WM_WIN || true
_i=0 _i=0
if command -v xprop >/dev/null 2>&1; then if command -v xprop >/dev/null 2>&1; then
while [ "$_i" -lt 50 ]; do while [ "$_i" -lt 80 ]; do
_wm_id="$(xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | awk ' _wm_id="$(xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | awk '
/window id/ { /window id/ {
for (i = 1; i <= NF; i++) { for (i = 1; i <= NF; i++) {
@@ -187,10 +227,12 @@ if [ "$NO_AUTOSTART" != "1" ] && command -v anode-autostart >/dev/null 2>&1; the
} }
')" ')"
if [ -n "${_wm_id:-}" ]; then if [ -n "${_wm_id:-}" ]; then
_wm_name="$(xprop -id "$_wm_id" _NET_WM_NAME 2>/dev/null || true)" if [ "$REPLACE_WM" != "1" ] || [ -z "${_prev_wm_id:-}" ] || [ "$_wm_id" != "$_prev_wm_id" ]; then
case "$_wm_name" in _wm_name="$(xprop -id "$_wm_id" _NET_WM_NAME 2>/dev/null || true)"
*ANODE*) break ;; case "$_wm_name" in
esac *ANODE*) break ;;
esac
fi
fi fi
_i=$(( _i + 1 )) _i=$(( _i + 1 ))
sleep 0.1 sleep 0.1
@@ -198,8 +240,12 @@ if [ "$NO_AUTOSTART" != "1" ] && command -v anode-autostart >/dev/null 2>&1; the
else else
sleep 1 sleep 1
fi fi
anode-autostart start if [ "$REPLACE_WM" = "1" ] && [ "$FORCE_AUTOSTART" != "1" ]; then
) >/dev/null 2>&1 & anode-autostart reload
else
anode-autostart start
fi
) </dev/null >/dev/null 2>&1 &
BG_PIDS="$BG_PIDS $!" BG_PIDS="$BG_PIDS $!"
fi fi
@@ -210,6 +256,7 @@ if command -v dwm >/dev/null 2>&1; then
else else
dwm || _dwm_rc=$? dwm || _dwm_rc=$?
fi fi
unset ANODE_REPLACE_SNAP_FILE ANODE_REPLACE_PREV_WM_WIN || true
if [ "$_dwm_rc" = "75" ]; then if [ "$_dwm_rc" = "75" ]; then
# Replaced by another ICCCM WM: stop old background daemons and hold the # Replaced by another ICCCM WM: stop old background daemons and hold the
# session open until the replacement WM exits so display managers stay up. # session open until the replacement WM exits so display managers stay up.
+151 -24
View File
@@ -1,6 +1,7 @@
/* See LICENSE file for copyright and license details. */ /* See LICENSE file for copyright and license details. */
/* ANODE DWM - Pango/HarfBuzz + First-class Systray + EWMH Struts + Fractional DPI */ /* ANODE DWM - Pango/HarfBuzz + First-class Systray + EWMH Struts + Fractional DPI */
#include <errno.h> #include <errno.h>
#include <fcntl.h>
#include <locale.h> #include <locale.h>
#include <math.h> #include <math.h>
#include <poll.h> #include <poll.h>
@@ -251,11 +252,13 @@ static void seturgent(Client *c, int urg);
static void showhide(Client *c); static void showhide(Client *c);
static void sigchld_handler(int sig); static void sigchld_handler(int sig);
static void sighup_handler(int sig); static void sighup_handler(int sig);
static void sigterm_handler(int sig);
static void sigusr1_handler(int sig); static void sigusr1_handler(int sig);
static void snapshot_pre_replace_state(void); static void snapshot_pre_replace_state(void);
static void spawn(const Arg *arg); static void spawn(const Arg *arg);
static void sync_client_props(Client *c); static void sync_client_props(Client *c);
static void sync_root_desktop_props(void); static void sync_root_desktop_props(void);
static unsigned int snap_desktop_to_tags(unsigned long d);
static Monitor *systraytomon(Monitor *m); static Monitor *systraytomon(Monitor *m);
static void tag(const Arg *arg); static void tag(const Arg *arg);
static void tagmon(const Arg *arg); static void tagmon(const Arg *arg);
@@ -358,6 +361,7 @@ static Atom utf8string = None, wmselatom = None;
#define MAX_SNAP_CLIENTS 256 #define MAX_SNAP_CLIENTS 256
#define MAX_SNAP_MONS 16 #define MAX_SNAP_MONS 16
#define MAX_SNAP_DESKS 32
typedef struct { typedef struct {
Window win; Window win;
@@ -371,6 +375,7 @@ typedef struct {
int is_above; int is_above;
int has_geom; int has_geom;
int rx, ry, rw, rh; int rx, ry, rw, rh;
int consumed;
} SnapClient; } SnapClient;
static SnapClient snap_clients[MAX_SNAP_CLIENTS]; static SnapClient snap_clients[MAX_SNAP_CLIENTS];
@@ -381,9 +386,12 @@ static Window snap_active_win = None;
static int snap_has_mon_state = 0; static int snap_has_mon_state = 0;
static unsigned long snap_mon_nvals = 0; static unsigned long snap_mon_nvals = 0;
static unsigned long snap_mon_vals[3 + MAX_SNAP_MONS * 7]; static unsigned long snap_mon_vals[3 + MAX_SNAP_MONS * 7];
static unsigned int snap_desk_tags[MAX_SNAP_DESKS];
static int snap_ndesk_tags = 0;
static unsigned long long snap_grace_until = 0;
static int in_scan = 0; static int in_scan = 0;
static int handoff_exit = 0; static int handoff_exit = 0;
static int running = 1; static volatile sig_atomic_t running = 1;
static Cur *cursor[CurLast]; static Cur *cursor[CurLast];
static Clr **scheme; static Clr **scheme;
static Display *dpy; static Display *dpy;
@@ -564,6 +572,7 @@ static void buttonpress(XEvent *e) {
if ((m = wintomon(ev->window)) && m != selmon) { if ((m = wintomon(ev->window)) && m != selmon) {
unfocus(selmon->sel, 1); unfocus(selmon->sel, 1);
selmon = m; selmon = m;
sync_root_desktop_props();
focus(NULL); focus(NULL);
} }
if (ev->window == selmon->barwin) { if (ev->window == selmon->barwin) {
@@ -647,6 +656,7 @@ static void acquirewm(void) {
prev_owner = XGetSelectionOwner(dpy, wmselatom); prev_owner = XGetSelectionOwner(dpy, wmselatom);
if (!replace_wm) { if (!replace_wm) {
unsetenv("ANODE_REPLACE_SNAP_FILE");
if (prev_owner != None) if (prev_owner != None)
die("dwm: another window manager is already running"); die("dwm: another window manager is already running");
xerrorxlib = XSetErrorHandler(xerrorstart); xerrorxlib = XSetErrorHandler(xerrorstart);
@@ -678,6 +688,15 @@ static void acquirewm(void) {
XSendEvent(dpy, root, False, StructureNotifyMask, (XEvent *)&cm); XSendEvent(dpy, root, False, StructureNotifyMask, (XEvent *)&cm);
XSync(dpy, False); XSync(dpy, False);
{
const char *snapf = getenv("ANODE_REPLACE_SNAP_FILE");
if (snapf && snapf[0]) {
int fd = open(snapf, O_CREAT | O_WRONLY | O_TRUNC, 0600);
if (fd >= 0) close(fd);
unsetenv("ANODE_REPLACE_SNAP_FILE");
}
}
unsigned long long deadline = now_ms() + 5000ULL; unsigned long long deadline = now_ms() + 5000ULL;
for (;;) { for (;;) {
while (XPending(dpy) > 0) { while (XPending(dpy) > 0) {
@@ -760,11 +779,18 @@ static unsigned long tags_to_desktop(unsigned int t) {
} }
static unsigned int desktop_to_tags(unsigned long d) { static unsigned int desktop_to_tags(unsigned long d) {
if (d == 0xFFFFFFFFUL) return TAGMASK; if ((uint32_t)d == 0xFFFFFFFFU) return TAGMASK;
if (d >= LENGTH(tags)) d = LENGTH(tags) - 1; if (d >= LENGTH(tags)) d = LENGTH(tags) - 1;
return 1U << d; return 1U << d;
} }
static unsigned int snap_desktop_to_tags(unsigned long d) {
if ((uint32_t)d == 0xFFFFFFFFU) return TAGMASK;
if (d < (unsigned long)snap_ndesk_tags && snap_desk_tags[d])
return snap_desk_tags[d];
return desktop_to_tags(d);
}
static unsigned long layout_to_index(const Layout *lt) { static unsigned long layout_to_index(const Layout *lt) {
for (unsigned int i = 0; i < LENGTH(layouts); i++) { for (unsigned int i = 0; i < LENGTH(layouts); i++) {
if (lt == &layouts[i]) return (unsigned long)i; if (lt == &layouts[i]) return (unsigned long)i;
@@ -780,8 +806,15 @@ static Monitor *mon_by_num(int num) {
} }
static SnapClient *find_snap_client(Window w) { static SnapClient *find_snap_client(Window w) {
if (!in_scan && snap_nclients > 0 && snap_grace_until > 0 && now_ms() > snap_grace_until) {
snap_nclients = 0;
snap_ndesk_tags = 0;
snap_grace_until = 0;
return NULL;
}
for (int i = 0; i < snap_nclients; i++) { for (int i = 0; i < snap_nclients; i++) {
if (snap_clients[i].win == w) return &snap_clients[i]; if (!snap_clients[i].consumed && snap_clients[i].win == w)
return &snap_clients[i];
} }
return NULL; return NULL;
} }
@@ -826,7 +859,7 @@ static void sync_root_desktop_props(void) {
} }
if (netatom[NetCurrentDesktop] != None) { if (netatom[NetCurrentDesktop] != None) {
unsigned long cur = tags_to_desktop(selmon->tagset[selmon->seltags] & TAGMASK); unsigned long cur = tags_to_desktop(selmon->tagset[selmon->seltags] & TAGMASK);
if (cur == 0xFFFFFFFFUL) cur = 0UL; if ((uint32_t)cur == 0xFFFFFFFFU) cur = 0UL;
XChangeProperty(dpy, root, netatom[NetCurrentDesktop], XA_CARDINAL, 32, XChangeProperty(dpy, root, netatom[NetCurrentDesktop], XA_CARDINAL, 32,
PropModeReplace, (unsigned char *)&cur, 1); PropModeReplace, (unsigned char *)&cur, 1);
} }
@@ -891,6 +924,7 @@ static void snapshot_pre_replace_state(void) {
Atom a_fs = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); Atom a_fs = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
Atom a_sticky = XInternAtom(dpy, "_NET_WM_STATE_STICKY", False); Atom a_sticky = XInternAtom(dpy, "_NET_WM_STATE_STICKY", False);
Atom a_above = XInternAtom(dpy, "_NET_WM_STATE_ABOVE", False); Atom a_above = XInternAtom(dpy, "_NET_WM_STATE_ABOVE", False);
Atom a_dnames = XInternAtom(dpy, "_NET_DESKTOP_NAMES", False);
Atom a_ast = XInternAtom(dpy, "_ANODE_WM_STATE", False); Atom a_ast = XInternAtom(dpy, "_ANODE_WM_STATE", False);
Atom a_mon = XInternAtom(dpy, "_ANODE_MON_STATE", False); Atom a_mon = XInternAtom(dpy, "_ANODE_MON_STATE", False);
@@ -900,6 +934,60 @@ static void snapshot_pre_replace_state(void) {
snap_active_win = None; snap_active_win = None;
snap_has_mon_state = 0; snap_has_mon_state = 0;
snap_mon_nvals = 0; snap_mon_nvals = 0;
snap_ndesk_tags = 0;
memset(snap_desk_tags, 0, sizeof(snap_desk_tags));
snap_grace_until = 0;
if (a_dnames != None) {
int di;
unsigned long dl, n = 0;
unsigned char *p = NULL;
Atom da = None;
if (XGetWindowProperty(dpy, sroot, a_dnames, 0L, 256L, False, AnyPropertyType,
&da, &di, &n, &dl, &p) == Success && p) {
if (di == 8 && n > 0) {
unsigned int parsed[MAX_SNAP_DESKS];
unsigned int used_mask = 0;
int nnames = 0, collision = 0, mapped = 0;
unsigned long pos = 0;
memset(parsed, 0, sizeof(parsed));
while (pos < n && nnames < MAX_SNAP_DESKS) {
const char *name = (const char *)(p + pos);
unsigned long avail = n - pos;
unsigned long len = 0;
while (len < avail && name[len] != '\0')
len++;
if (len > 0 && name[0] >= '0' && name[0] <= '9') {
unsigned long num = 0;
unsigned long j = 0;
while (j < len && name[j] >= '0' && name[j] <= '9') {
num = num * 10UL + (unsigned long)(name[j] - '0');
if (num > LENGTH(tags)) break;
j++;
}
if (num >= 1 && num <= LENGTH(tags) &&
(j == len || name[j] == ':' || name[j] == '-' || name[j] == ' ')) {
unsigned int bit = 1U << (num - 1);
if (used_mask & bit) {
collision = 1;
} else {
parsed[nnames] = bit;
used_mask |= bit;
mapped++;
}
}
}
nnames++;
pos += len + 1;
}
if (!collision && mapped > 0) {
memcpy(snap_desk_tags, parsed, sizeof(parsed));
snap_ndesk_tags = nnames;
}
}
XFree(p);
}
}
unsigned long tmp = 0; unsigned long tmp = 0;
if (read_cardinal_prop(sroot, a_cur, &tmp, 1) >= 1) { if (read_cardinal_prop(sroot, a_cur, &tmp, 1) >= 1) {
@@ -2110,13 +2198,15 @@ static void manage(Window w, XWindowAttributes *wa) {
Client *c, *t = NULL; Client *c, *t = NULL;
Window trans = None; Window trans = None;
XWindowChanges wc; XWindowChanges wc;
SnapClient *sc = in_scan ? find_snap_client(w) : NULL; SnapClient *sc = find_snap_client(w);
int restoring = in_scan || (sc != NULL);
unsigned long astate[12] = {0}; unsigned long astate[12] = {0};
int has_astate = 0; int has_astate = 0;
unsigned long desk = 0; unsigned long desk = 0;
int has_desk = 0; int has_desk = 0;
int desk_from_snap = 0;
if (in_scan) { if (restoring) {
if (read_cardinal_prop(w, anodeatom[AnodeWMState], astate, 12) == 12 && if (read_cardinal_prop(w, anodeatom[AnodeWMState], astate, 12) == 12 &&
astate[0] == 0x414E4431UL) { astate[0] == 0x414E4431UL) {
has_astate = 1; has_astate = 1;
@@ -2125,11 +2215,12 @@ static void manage(Window w, XWindowAttributes *wa) {
has_astate = 1; has_astate = 1;
} }
} }
if (read_cardinal_prop(w, netatom[NetWMDesktop], &desk, 1) >= 1) { if (sc && sc->has_desktop) {
has_desk = 1;
} else if (sc && sc->has_desktop) {
desk = sc->desktop; desk = sc->desktop;
has_desk = 1; has_desk = 1;
desk_from_snap = 1;
} else if (read_cardinal_prop(w, netatom[NetWMDesktop], &desk, 1) >= 1) {
has_desk = 1;
} }
c = ecalloc(1, sizeof(Client)); c = ecalloc(1, sizeof(Client));
@@ -2184,18 +2275,18 @@ static void manage(Window w, XWindowAttributes *wa) {
c->mon = t->mon; c->mon = t->mon;
c->tags = t->tags; c->tags = t->tags;
} else { } else {
if (in_scan && sc && sc->has_geom && sc->rw > 0 && sc->rh > 0) if (restoring && sc && sc->has_geom && sc->rw > 0 && sc->rh > 0)
c->mon = recttomon(sc->rx, sc->ry, sc->rw, sc->rh); c->mon = recttomon(sc->rx, sc->ry, sc->rw, sc->rh);
else if (in_scan) else if (restoring)
c->mon = recttomon(wa->x, wa->y, wa->width, wa->height); c->mon = recttomon(wa->x, wa->y, wa->width, wa->height);
else else
c->mon = selmon; c->mon = selmon;
applyrules(c); applyrules(c);
} }
if (has_desk) { if (has_desk) {
c->tags = desktop_to_tags(desk); c->tags = desk_from_snap ? snap_desktop_to_tags(desk) : desktop_to_tags(desk);
} else if (in_scan && ((sc && sc->is_sticky) || } else if (restoring && ((sc && sc->is_sticky) ||
hasatomprop(c, netatom[NetWMState], netatom[NetWMStateSticky]))) { hasatomprop(c, netatom[NetWMState], netatom[NetWMStateSticky]))) {
c->tags = TAGMASK; c->tags = TAGMASK;
} }
c->bw = (int)borderpx; c->bw = (int)borderpx;
@@ -2216,11 +2307,11 @@ static void manage(Window w, XWindowAttributes *wa) {
configure(c); configure(c);
if (!has_astate) { if (!has_astate) {
updatewindowtype(c); updatewindowtype(c);
if (in_scan && ((sc && sc->is_above) || if (restoring && ((sc && sc->is_above) ||
hasatomprop(c, netatom[NetWMState], netatom[NetWMStateAbove]))) { hasatomprop(c, netatom[NetWMState], netatom[NetWMStateAbove]))) {
c->isfloating = 1; c->isfloating = 1;
} }
if (in_scan && c->isfloating && !c->isfullscreen && sc && sc->has_geom && if (restoring && c->isfloating && !c->isfullscreen && sc && sc->has_geom &&
sc->rw > 0 && sc->rh > 0) { sc->rw > 0 && sc->rh > 0) {
c->x = sc->rx; c->y = sc->ry; c->w = sc->rw; c->h = sc->rh; c->x = sc->rx; c->y = sc->ry; c->w = sc->rw; c->h = sc->rh;
if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww)
@@ -2230,7 +2321,7 @@ static void manage(Window w, XWindowAttributes *wa) {
c->x = MAX(c->x, c->mon->wx); c->x = MAX(c->x, c->mon->wx);
c->y = MAX(c->y, c->mon->wy); c->y = MAX(c->y, c->mon->wy);
} }
if (in_scan && !c->isfullscreen && sc && sc->is_fullscreen) { if (restoring && !c->isfullscreen && sc && sc->is_fullscreen) {
setfullscreen(c, 1); setfullscreen(c, 1);
} }
} }
@@ -2240,7 +2331,7 @@ static void manage(Window w, XWindowAttributes *wa) {
grabbuttons(c, 0); grabbuttons(c, 0);
if (!has_astate && !c->isfloating) if (!has_astate && !c->isfloating)
c->isfloating = c->oldstate = (trans != None || c->isfixed); c->isfloating = c->oldstate = (trans != None || c->isfixed);
if (!has_astate && !in_scan && c->isfloating && !c->isfullscreen && wa->x == 0 && wa->y == 0) { if (!has_astate && !restoring && c->isfloating && !c->isfullscreen && wa->x == 0 && wa->y == 0) {
c->x = c->mon->wx + (c->mon->ww - WIDTH(c)) / 2; c->x = c->mon->wx + (c->mon->ww - WIDTH(c)) / 2;
c->y = c->mon->wy + (c->mon->wh - HEIGHT(c)) / 2; c->y = c->mon->wy + (c->mon->wh - HEIGHT(c)) / 2;
if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww)
@@ -2254,6 +2345,8 @@ static void manage(Window w, XWindowAttributes *wa) {
XRaiseWindow(dpy, c->win); XRaiseWindow(dpy, c->win);
attach(c); attach(c);
attachstack(c); attachstack(c);
if (sc)
sc->consumed = 1;
sync_client_props(c); sync_client_props(c);
if (in_scan) { if (in_scan) {
int tx = ISVISIBLE(c) ? c->x : (WIDTH(c) * -2); int tx = ISVISIBLE(c) ? c->x : (WIDTH(c) * -2);
@@ -2366,6 +2459,7 @@ static void motionnotify(XEvent *e) {
updatesystray(1); updatesystray(1);
} }
updateworkarea(); updateworkarea();
sync_root_desktop_props();
focus(NULL); focus(NULL);
} }
mon = m; mon = m;
@@ -2697,6 +2791,21 @@ static void scan(void) {
} }
if (wins) XFree(wins); if (wins) XFree(wins);
} }
for (int si = 0; si < snap_nclients; si++) {
SnapClient *sc = &snap_clients[si];
Window parent = None, *ch = NULL;
unsigned int nc = 0;
if (!sc->from_client_list || sc->consumed || wintoclient(sc->win))
continue;
if (XGetWindowAttributes(dpy, sc->win, &wa) && !wa.override_redirect &&
XQueryTree(dpy, sc->win, &d1, &parent, &ch, &nc)) {
if (ch) XFree(ch);
if (parent == root && !isdockwin(sc->win))
manage(sc->win, &wa);
} else if (ch) {
XFree(ch);
}
}
in_scan = 0; in_scan = 0;
updateclientlist(); updateclientlist();
arrange(NULL); arrange(NULL);
@@ -2716,7 +2825,7 @@ static void scan(void) {
} }
sync_root_desktop_props(); sync_root_desktop_props();
drawbars(); drawbars();
snap_nclients = 0; snap_grace_until = (snap_nclients > 0) ? (now_ms() + 2000ULL) : 0ULL;
snap_has_cur_desk = 0; snap_has_cur_desk = 0;
snap_has_mon_state = 0; snap_has_mon_state = 0;
snap_active_win = None; snap_active_win = None;
@@ -2890,6 +2999,12 @@ static void setup(void) {
sa.sa_handler = sighup_handler; sa.sa_handler = sighup_handler;
sigaction(SIGHUP, &sa, NULL); sigaction(SIGHUP, &sa, NULL);
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = sigterm_handler;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
loadxres(); loadxres();
screen = DefaultScreen(dpy); screen = DefaultScreen(dpy);
@@ -2962,20 +3077,26 @@ static void setup(void) {
updatebars(); updatebars();
{ {
int has_live_anode_mon = 0;
unsigned long live_mon[3 + MAX_SNAP_MONS * 7]; unsigned long live_mon[3 + MAX_SNAP_MONS * 7];
unsigned long mn = read_cardinal_prop(root, anodeatom[AnodeMonState], live_mon, LENGTH(live_mon)); unsigned long mn = read_cardinal_prop(root, anodeatom[AnodeMonState], live_mon, LENGTH(live_mon));
if (mn >= 3 && live_mon[0] == 0x414E4D31UL) { if (mn >= 3 && live_mon[0] == 0x414E4D31UL) {
has_live_anode_mon = 1;
snap_has_mon_state = 1; snap_has_mon_state = 1;
snap_mon_nvals = mn; snap_mon_nvals = mn;
memcpy(snap_mon_vals, live_mon, (size_t)mn * sizeof(unsigned long)); memcpy(snap_mon_vals, live_mon, (size_t)mn * sizeof(unsigned long));
} }
unsigned long tmp = 0; unsigned long tmp = 0;
if (read_cardinal_prop(root, netatom[NetCurrentDesktop], &tmp, 1) >= 1) { if (read_cardinal_prop(root, netatom[NetCurrentDesktop], &tmp, 1) >= 1) {
snap_has_cur_desk = 1; if (has_live_anode_mon || !snap_has_cur_desk) {
snap_cur_desk = tmp; snap_has_cur_desk = 1;
snap_cur_desk = tmp;
}
} }
if (read_cardinal_prop(root, netatom[NetActiveWindow], &tmp, 1) >= 1 && (Window)tmp != None) { if (read_cardinal_prop(root, netatom[NetActiveWindow], &tmp, 1) >= 1 && (Window)tmp != None) {
snap_active_win = (Window)tmp; if (has_live_anode_mon || snap_active_win == None) {
snap_active_win = (Window)tmp;
}
} }
} }
if (snap_has_mon_state && snap_mon_nvals >= 3) { if (snap_has_mon_state && snap_mon_nvals >= 3) {
@@ -3012,7 +3133,7 @@ static void setup(void) {
updatesystray(1); updatesystray(1);
} }
} else if (snap_has_cur_desk && selmon) { } else if (snap_has_cur_desk && selmon) {
unsigned int ts = desktop_to_tags(snap_cur_desk); unsigned int ts = snap_desktop_to_tags(snap_cur_desk);
if (ts) selmon->tagset[selmon->seltags] = ts; if (ts) selmon->tagset[selmon->seltags] = ts;
} }
@@ -3110,6 +3231,11 @@ static void sighup_handler(int sig) {
running = 0; running = 0;
} }
static void sigterm_handler(int sig) {
(void)sig;
running = 0;
}
static void spawn(const Arg *arg) { static void spawn(const Arg *arg) {
struct sigaction sa; struct sigaction sa;
if (fork() == 0) { if (fork() == 0) {
@@ -3453,6 +3579,7 @@ static int updategeom(void) {
c->mon = mons; c->mon = mons;
attach(c); attach(c);
attachstack(c); attachstack(c);
sync_client_props(c);
} }
if (m == selmon) selmon = mons; if (m == selmon) selmon = mons;
cleanupmon(m); cleanupmon(m);
+120
View File
@@ -512,6 +512,125 @@ def test_dwm_sighup_reload_xvfb():
terminate(xvfb) terminate(xvfb)
def test_xdg_desktop_dedup_and_polkit_guard():
with tempfile.TemporaryDirectory() as tmp:
env, _, xdg_home, xdg_sys, _, bin_dir = make_base_env(tmp)
conf_dir = os.path.join(xdg_home, "anode")
markers = os.path.join(tmp, "markers")
os.makedirs(markers, exist_ok=True)
app_bin = os.path.join(bin_dir, "anode_xdg_app")
compile_sleep_dummy(app_bin)
lxpolkit_bin = os.path.join(bin_dir, "lxpolkit")
shutil.copy2(app_bin, lxpolkit_bin)
m_app = os.path.join(markers, "app.pid")
m_pre_app = os.path.join(markers, "pre_app.pid")
m_xdg_dup = os.path.join(markers, "xdg_dup.pid")
m_polkit_pre = os.path.join(markers, "polkit_pre.pid")
m_polkit_new = os.path.join(markers, "polkit_new.pid")
m_polkit_bad_sess = os.path.join(markers, "polkit_bad_sess.pid")
# 1) exec_once + XDG .desktop of the same app in a single start must only launch once
write_text(os.path.join(conf_dir, "autostart"), f"exec_once anode_xdg_app '{m_app}'\n")
write_text(
os.path.join(xdg_sys, "autostart", "app.desktop"),
f"[Desktop Entry]\nType=Application\nTryExec=anode_xdg_app\nExec=anode_xdg_app '{m_app}'\n",
)
res = run_autostart(["start"], env)
assert res.returncode == 0, f"start failed: {res.stderr}"
assert wait_until(lambda: os.path.exists(m_app), timeout=4.0), "anode_xdg_app did not launch"
time.sleep(0.35)
try:
with open(m_app, "r", encoding="utf-8") as f:
pids = [line.strip() for line in f if line.strip()]
assert len(pids) == 1, f"expected 1 launch for exec_once + XDG .desktop, got {pids}"
finally:
kill_pids_from_file(m_app)
# Wait briefly for previous process cleanup before testing pre-running XDG dedup
time.sleep(0.15)
# 2) Already-running process referenced by XDG .desktop must be skipped
write_text(os.path.join(conf_dir, "autostart"), "# empty\n")
write_text(
os.path.join(xdg_sys, "autostart", "app.desktop"),
f"[Desktop Entry]\nType=Application\nTryExec=anode_xdg_app\nExec=anode_xdg_app '{m_xdg_dup}'\n",
)
pre_app = subprocess.Popen([app_bin, m_pre_app], env=env)
try:
assert wait_until(lambda: os.path.exists(m_pre_app), timeout=3.0)
res2 = run_autostart(["start"], env)
assert res2.returncode == 0, f"start failed: {res2.stderr}"
time.sleep(0.35)
assert not os.path.exists(m_xdg_dup), "XDG .desktop launched duplicate of already-running app"
finally:
terminate(pre_app)
kill_pids_from_file(m_xdg_dup)
# 3) Polkit agent running on DISPLAY=:97 in sess-active must block duplicate on :97 even from stale XDG_SESSION_ID
os.remove(os.path.join(xdg_sys, "autostart", "app.desktop"))
write_text(os.path.join(conf_dir, "autostart"), f"exec_once lxpolkit '{m_polkit_new}'\n")
write_text(
os.path.join(xdg_sys, "autostart", "lxpolkit.desktop"),
f"[Desktop Entry]\nType=Application\nTryExec=lxpolkit\nExec=lxpolkit '{m_polkit_new}'\n",
)
active_env = dict(env)
active_env["DISPLAY"] = ":97"
active_env["XDG_SESSION_ID"] = "sess-active"
active_env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/tmp/anode-active-dbus"
stale_env = dict(env)
stale_env["DISPLAY"] = ":97"
stale_env["XDG_SESSION_ID"] = "sess-stale"
stale_env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/tmp/anode-stale-dbus"
stale_env["ANODE_FORCE_POLKIT_AGENT"] = "1"
pre_pk = subprocess.Popen([lxpolkit_bin, m_polkit_pre], env=active_env)
try:
assert wait_until(lambda: os.path.exists(m_polkit_pre), timeout=3.0)
res3 = run_autostart(["start"], stale_env)
assert res3.returncode == 0, f"polkit dedup run failed: {res3.stderr}"
time.sleep(0.35)
assert not os.path.exists(m_polkit_new), (
"duplicate polkit agent was started on same DISPLAY across different XDG_SESSION_ID"
)
finally:
terminate(pre_pk)
kill_pids_from_file(m_polkit_new)
# 4) Dead/invalid loginctl session must skip launching polkit agent
loginctl_stub = os.path.join(bin_dir, "loginctl")
write_text(
loginctl_stub,
"#!/bin/sh\n"
"if [ \"${1:-}\" = \"list-sessions\" ]; then\n"
" printf 'SESSION UID USER SEAT\\n c11 1000 lux seat0\\n'\n"
" exit 0\n"
"fi\n"
"exit 1\n",
0o755,
)
write_text(os.path.join(conf_dir, "autostart"), f"exec_once lxpolkit '{m_polkit_bad_sess}'\n")
write_text(
os.path.join(xdg_sys, "autostart", "lxpolkit.desktop"),
f"[Desktop Entry]\nType=Application\nTryExec=lxpolkit\nExec=lxpolkit '{m_polkit_bad_sess}'\n",
)
bad_sess_env = dict(env)
bad_sess_env["DISPLAY"] = ":98"
bad_sess_env["XDG_SESSION_ID"] = "sess-dead"
bad_sess_env.pop("ANODE_FORCE_POLKIT_AGENT", None)
res4 = run_autostart(["start"], bad_sess_env)
assert res4.returncode == 0, f"dead-session guard run failed: {res4.stderr}"
time.sleep(0.35)
try:
assert not os.path.exists(m_polkit_bad_sess), (
"polkit agent launched despite invalid loginctl session"
)
finally:
kill_pids_from_file(m_polkit_bad_sess)
if __name__ == "__main__": if __name__ == "__main__":
test_directives_includes_once_and_reload() test_directives_includes_once_and_reload()
test_exec_once_session_isolation() test_exec_once_session_isolation()
@@ -519,4 +638,5 @@ if __name__ == "__main__":
test_dropins_desktop_filters_and_xdg_masking() test_dropins_desktop_filters_and_xdg_masking()
test_check_errors() test_check_errors()
test_dwm_sighup_reload_xvfb() test_dwm_sighup_reload_xvfb()
test_xdg_desktop_dedup_and_polkit_guard()
print("test_autostart: OK") print("test_autostart: OK")
+223
View File
@@ -1197,6 +1197,228 @@ def test_replace_preserves_workspaces_and_states():
terminate(xvfb) terminate(xvfb)
def test_replace_autostart_reload_default_and_slow_snapshot_guard():
# Part 1: Default anode-replace runs anode-autostart reload (not start / not XDG .desktop),
# while anode-replace --autostart explicitly runs full anode-autostart start.
disp1 = pick_display()
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp1)
os.symlink(os.path.join(ROOT, "scripts", "anode-autostart"), os.path.join(tmp, "bin", "anode-autostart"))
xdg_sys = os.path.join(tmp, "xdg_sys")
os.makedirs(os.path.join(xdg_sys, "autostart"), exist_ok=True)
os.makedirs(os.path.join(env["XDG_CONFIG_HOME"], "anode"), exist_ok=True)
env["XDG_CONFIG_DIRS"] = xdg_sys
env["ANODE_XDG_AUTOSTART"] = "1"
env["ANODE_FORCE_POLKIT_AGENT"] = "1"
m_exec = os.path.join(tmp, "exec.log")
m_once = os.path.join(tmp, "once.log")
m_always = os.path.join(tmp, "always.log")
m_polkit = os.path.join(tmp, "lxpolkit.log")
lx_stub = os.path.join(tmp, "bin", "lxpolkit")
with open(lx_stub, "w", encoding="utf-8") as f:
f.write(f"#!/bin/sh\nprintf 'pk\\n' >> '{m_polkit}'\n")
os.chmod(lx_stub, 0o755)
once_stub = os.path.join(tmp, "bin", "anode_once_stub")
with open(once_stub, "w", encoding="utf-8") as f:
f.write(f"#!/bin/sh\nprintf 'o\\n' >> '{m_once}'\n")
os.chmod(once_stub, 0o755)
with open(os.path.join(env["XDG_CONFIG_HOME"], "anode", "autostart"), "w", encoding="utf-8") as f:
f.write(
f"exec sh -c \"printf 'e\\n' >> '{m_exec}'\"\n"
"exec_once anode_once_stub\n"
f"exec_always sh -c \"printf 'a\\n' >> '{m_always}'\"\n"
)
with open(os.path.join(xdg_sys, "autostart", "lxpolkit.desktop"), "w", encoding="utf-8") as f:
f.write("[Desktop Entry]\nType=Application\nTryExec=lxpolkit\nExec=lxpolkit\n")
xvfb = subprocess.Popen(
["Xvfb", disp1, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
dwm1 = None
dpy = None
cur_pid = None
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp1.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
rep1 = subprocess.run([REPLACE_BIN, "--keep-panels"], env=env, capture_output=True, text=True)
assert rep1.returncode == 0, f"default replace failed: stdout={rep1.stdout} stderr={rep1.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
cur_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
assert wait_until(lambda: os.path.exists(m_always), timeout=4.0), "default replace did not run exec_always"
time.sleep(0.35)
assert not os.path.exists(m_exec), "default replace must not re-run exec"
assert not os.path.exists(m_once), "default replace must not re-run exec_once"
assert not os.path.exists(m_polkit), "default replace must not re-run XDG lxpolkit.desktop"
rep2 = subprocess.run([REPLACE_BIN, "--autostart", "--keep-panels"], env=env, capture_output=True, text=True)
assert rep2.returncode == 0, f"--autostart replace failed: stdout={rep2.stdout} stderr={rep2.stderr}"
wm3 = wait_until(
lambda: (lambda w: w if w and w != wm2 else None)(get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")),
timeout=5.0,
)
assert wm3
cur_pid = get_win_prop_ulong(dpy, wm3, "_NET_WM_PID")
assert wait_until(lambda: os.path.exists(m_exec), timeout=4.0), "--autostart did not run exec"
assert wait_until(lambda: os.path.exists(m_once), timeout=4.0), "--autostart did not run exec_once"
assert wait_until(lambda: os.path.exists(m_polkit), timeout=4.0), "--autostart did not run XDG desktop"
finally:
terminate(dwm1)
kill_pid_and_wait(cur_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
# Part 2: Slow pre-dwm setup (>1.5s) + third-party WM resetting _NET_WM_DESKTOP=0 / _NET_CURRENT_DESKTOP=0
# on SIGTERM + sparse _NET_DESKTOP_NAMES ("1", "3:code", "5").
disp2 = pick_display()
cc = os.environ.get("CC", "cc")
with tempfile.TemporaryDirectory() as tmp:
env = make_env(tmp, disp2)
with open(os.path.join(env["HOME"], ".Xresources"), "w", encoding="utf-8") as f:
f.write("theme.name: Anodized\n")
xrdb_shim = os.path.join(tmp, "bin", "xrdb")
with open(xrdb_shim, "w", encoding="utf-8") as f:
f.write("#!/bin/sh\nsleep 1.8\n")
os.chmod(xrdb_shim, 0o755)
ewmh_c = os.path.join(tmp, "mock_ewmh_reset.c")
ewmh_bin = os.path.join(tmp, "bin", "mock_ewmh_reset")
with open(ewmh_c, "w", encoding="utf-8") as f:
f.write(
"#define _POSIX_C_SOURCE 200809L\n"
"#include <signal.h>\n"
"#include <stdlib.h>\n"
"#include <time.h>\n"
"#include <unistd.h>\n"
"#include <X11/Xatom.h>\n"
"#include <X11/Xlib.h>\n"
"static volatile sig_atomic_t alive = 1;\n"
"static void on_sig(int s) { (void)s; alive = 0; }\n"
"int main(int argc, char **argv) {\n"
" signal(SIGTERM, on_sig);\n"
" Display *d = XOpenDisplay(NULL);\n"
" if (!d) return 1;\n"
" Window root = DefaultRootWindow(d);\n"
" XSelectInput(d, root, SubstructureRedirectMask);\n"
" Window wmc = 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"
" Atom acd = XInternAtom(d, \"_NET_CURRENT_DESKTOP\", False);\n"
" Atom awd = XInternAtom(d, \"_NET_WM_DESKTOP\", False);\n"
" Atom adn = XInternAtom(d, \"_NET_DESKTOP_NAMES\", False);\n"
" unsigned long pid = (unsigned long)getpid();\n"
" const char names[] = \"1\\0\" \"3:code\\0\" \"5\";\n"
" XChangeProperty(d, wmc, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n"
" XChangeProperty(d, wmc, an, au, 8, PropModeReplace, (unsigned char *)\"MockResetWM\", 11);\n"
" XChangeProperty(d, wmc, ap, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);\n"
" XChangeProperty(d, root, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n"
" XChangeProperty(d, root, adn, au, 8, PropModeReplace, (const unsigned char *)names, sizeof(names));\n"
" XSync(d, False);\n"
" while (alive) { struct timespec ts = {0, 50000000L}; nanosleep(&ts, NULL); }\n"
" unsigned long zero = 0;\n"
" XChangeProperty(d, root, acd, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&zero, 1);\n"
" for (int i = 1; i < argc; i++) {\n"
" Window cw = (Window)strtoul(argv[i], NULL, 0);\n"
" if (cw != None)\n"
" XChangeProperty(d, cw, awd, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&zero, 1);\n"
" }\n"
" XDestroyWindow(d, wmc);\n"
" XSync(d, False);\n"
" XCloseDisplay(d);\n"
" return 0;\n"
"}\n"
)
subprocess.run([cc, "-O2", ewmh_c, "-o", ewmh_bin] + compile_x11_flags(), check=True)
xvfb = subprocess.Popen(
["Xvfb", disp2, "-screen", "0", "1280x720x24", "-nolisten", "tcp"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
mwm = None
dpy = None
new_pid = None
app_wins = []
try:
dpy = wait_until(lambda: X11.XOpenDisplay(disp2.encode()), timeout=5.0)
assert dpy
root = X11.XDefaultRootWindow(dpy)
a_card = X11.XInternAtom(dpy, b"CARDINAL", 0)
a_win = X11.XInternAtom(dpy, b"WINDOW", 0)
a_cl = X11.XInternAtom(dpy, b"_NET_CLIENT_LIST", 0)
a_cd = X11.XInternAtom(dpy, b"_NET_CURRENT_DESKTOP", 0)
a_wd = X11.XInternAtom(dpy, b"_NET_WM_DESKTOP", 0)
a_act = X11.XInternAtom(dpy, b"_NET_ACTIVE_WINDOW", 0)
wa = X11.XCreateSimpleWindow(dpy, root, 10, 40, 280, 180, 0, 0, 0xffffff)
wb = X11.XCreateSimpleWindow(dpy, root, 40, 60, 300, 200, 0, 0, 0xffffff)
wc = X11.XCreateSimpleWindow(dpy, root, 70, 80, 320, 220, 0, 0, 0xffffff)
app_wins = [wa, wb, wc]
X11.XMapWindow(dpy, wb)
for w, desk in ((wa, 0), (wb, 1), (wc, 2)):
dv = ctypes.c_ulong(desk)
X11.XChangeProperty(dpy, w, a_wd, a_card, 32, 0, ctypes.byref(dv), 1)
cl_arr = (ctypes.c_ulong * 3)(wa, wb, wc)
X11.XChangeProperty(dpy, root, a_cl, a_win, 32, 0, cl_arr, 3)
cd_v = ctypes.c_ulong(1)
X11.XChangeProperty(dpy, root, a_cd, a_card, 32, 0, ctypes.byref(cd_v), 1)
act_v = ctypes.c_ulong(wb)
X11.XChangeProperty(dpy, root, a_act, a_win, 32, 0, ctypes.byref(act_v), 1)
X11.XSync(dpy, 0)
mwm = subprocess.Popen([ewmh_bin, hex(wa), hex(wb), hex(wc)], env=env)
wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0)
assert wm1
rep = subprocess.run(
[REPLACE_BIN, "--no-autostart", "--keep-panels"],
env=env, capture_output=True, text=True,
)
assert rep.returncode == 0, f"slow/sparse replace failed: stdout={rep.stdout} stderr={rep.stderr}"
wm2 = get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK")
assert wm2 and wm2 != wm1
new_pid = get_win_prop_ulong(dpy, wm2, "_NET_WM_PID")
def sparse_ok():
return (
get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") == 2
and get_win_prop_ulong(dpy, wa, "_NET_WM_DESKTOP") == 0
and get_win_prop_ulong(dpy, wb, "_NET_WM_DESKTOP") == 2
and get_win_prop_ulong(dpy, wc, "_NET_WM_DESKTOP") == 4
and get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") == wb
)
assert wait_until(sparse_ok, timeout=5.0), (
f"sparse/slow restore mismatch: cur={get_win_prop_ulong(dpy, root, '_NET_CURRENT_DESKTOP')} "
f"desks={[get_win_prop_ulong(dpy, w, '_NET_WM_DESKTOP') for w in app_wins]} "
f"act={get_win_prop_ulong(dpy, root, '_NET_ACTIVE_WINDOW')}"
)
finally:
if dpy:
for w in app_wins:
X11.XDestroyWindow(dpy, w)
terminate(mwm)
kill_pid_and_wait(new_pid)
if dpy:
X11.XCloseDisplay(dpy)
terminate(xvfb)
def main(): def main():
if not shutil.which("Xvfb"): if not shutil.which("Xvfb"):
print("test_replace: Xvfb not installed (skipping)") print("test_replace: Xvfb not installed (skipping)")
@@ -1211,6 +1433,7 @@ def main():
test_switch_session_stale_i3sock_fallback() test_switch_session_stale_i3sock_fallback()
test_replace_display_scoped_daemon_cleanup() test_replace_display_scoped_daemon_cleanup()
test_replace_preserves_workspaces_and_states() test_replace_preserves_workspaces_and_states()
test_replace_autostart_reload_default_and_slow_snapshot_guard()
print("test_replace: OK") print("test_replace: OK")
return 0 return 0