diff --git a/Makefile b/Makefile index 41e976a..00c6757 100644 --- a/Makefile +++ b/Makefile @@ -297,6 +297,7 @@ install: all "$(DESTDIR)$(PREFIX)/lib/pkgconfig" \ "$(DESTDIR)$(PREFIX)/include" \ "$(DESTDIR)$(PREFIX)/share/anode/themes" \ + "$(DESTDIR)$(PREFIX)/share/anode/autostart.d" \ "$(DESTDIR)$(PREFIX)/share/xsessions" \ "$(DESTDIR)$(MANPREFIX)/man1" cp -f build/dwm/dwm "$(DESTDIR)$(PREFIX)/bin/dwm" @@ -309,7 +310,7 @@ install: all cp -f build/daemons/anode-statusd build/daemons/anode-touchd build/daemons/anode-powerd \ build/daemons/anode-power-ctl build/daemons/anode-dnsctl build/daemons/anode-tzctl \ build/daemons/anode-checkpw "$(DESTDIR)$(PREFIX)/bin/" - cp -f scripts/anode-session scripts/anode-launcher scripts/anode-apply-theme \ + cp -f scripts/anode-session scripts/anode-autostart scripts/anode-launcher scripts/anode-apply-theme \ scripts/anode-apply-scale scripts/anode-sync-gtk-theme scripts/anode-sync-dunst-theme \ "$(DESTDIR)$(PREFIX)/bin/" chmod 755 \ @@ -324,7 +325,8 @@ install: all "$(DESTDIR)$(PREFIX)/bin/anode-touchd" "$(DESTDIR)$(PREFIX)/bin/anode-powerd" \ "$(DESTDIR)$(PREFIX)/bin/anode-power-ctl" "$(DESTDIR)$(PREFIX)/bin/anode-dnsctl" \ "$(DESTDIR)$(PREFIX)/bin/anode-tzctl" "$(DESTDIR)$(PREFIX)/bin/anode-checkpw" \ - "$(DESTDIR)$(PREFIX)/bin/anode-session" "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ + "$(DESTDIR)$(PREFIX)/bin/anode-session" "$(DESTDIR)$(PREFIX)/bin/anode-autostart" \ + "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ "$(DESTDIR)$(PREFIX)/bin/anode-apply-theme" "$(DESTDIR)$(PREFIX)/bin/anode-apply-scale" \ "$(DESTDIR)$(PREFIX)/bin/anode-sync-gtk-theme" "$(DESTDIR)$(PREFIX)/bin/anode-sync-dunst-theme" cp -f build/libgemui/libgemui.so "$(DESTDIR)$(PREFIX)/lib/libgemui.so" @@ -337,6 +339,8 @@ install: all chmod 644 "$(DESTDIR)$(PREFIX)/share/anode/themes/"*.xth cp -f data/env.sh "$(DESTDIR)$(PREFIX)/share/anode/env.sh" chmod 644 "$(DESTDIR)$(PREFIX)/share/anode/env.sh" + cp -f data/autostart "$(DESTDIR)$(PREFIX)/share/anode/autostart" + 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" @@ -380,6 +384,7 @@ uninstall: "$(DESTDIR)$(PREFIX)/bin/anode-tzctl" \ "$(DESTDIR)$(PREFIX)/bin/anode-checkpw" \ "$(DESTDIR)$(PREFIX)/bin/anode-session" \ + "$(DESTDIR)$(PREFIX)/bin/anode-autostart" \ "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ "$(DESTDIR)$(PREFIX)/bin/anode-apply-theme" \ "$(DESTDIR)$(PREFIX)/bin/anode-apply-scale" \ @@ -406,6 +411,7 @@ test: all build/tests/test_units python3 tests/test_posix_make.py ./build/tests/test_units python3 tests/test_theme_scale.py + python3 tests/test_autostart.py python3 tests/test_x11_xvfb.py .PHONY: all dwm dmenu st libgemui apps vkbd daemons gtkttk gtkttk-auto install uninstall clean test diff --git a/README.md b/README.md index e77d10a..f5902ef 100644 --- a/README.md +++ b/README.md @@ -27,11 +27,13 @@ ANODE is a lightweight, keyboard-first, cross-Unix X11 desktop environment for * - `anode-powerd`: Idle dim / lock / suspend policy daemon (`XScreenSaverQueryInfo` when available). - **gtkTtk 0.9 port**: - Native GTK2-backed Ttk/Tkinter widget theme with full `[0.5, 4.0]` fractional DPI scaling and BSD library paths. +- **Session-specific autostart**: + - `anode-autostart`: i3-style `exec`, `exec_once`, `exec_always`, `--no-startup-id`, and `include` directives, per-profile `autostart.` files, `autostart.d/` drop-ins, and `ANODE`-filtered XDG `.desktop` entries wired into `anode-session` and DWM reload/restart. ## Dependencies - **Build-time**: POSIX `make`, C11/C99 compiler (`cc`), `pkg-config`, X11 development headers (`x11`, `xext`, `xft`, `xinerama`, `xrandr`, `xfixes`, `xi`, `xtst`, optionally `xscrnsaver`), `fontconfig`, `freetype2`, `harfbuzz`, `cairo`, `pango`, `pangoxft`, `pangocairo`, and `libcrypt` (`-lcrypt` where separate). Optional for `gtkTtk`: C++ compiler, `gtk+-2.0`, `tcl`, `tk`, and Tk private `ttkTheme.h`. -- **Runtime (optional tools auto-detected)**: `xrdb`, `xrandr`, `xsettingsd`, `dunst`, `notify-send`, `scrot`/`import`/`maim`, `wpctl`/`pactl`/`amixer`/`sndioctl`, `nmcli`/`wpa_cli`, `bluetoothctl`, `playerctl`/`mpc`, `chronyc`, `doas`/`sudo`/`pkexec`, and **Fira Code** + **DejaVuSansM Nerd Font**. +- **Runtime (optional tools auto-detected)**: `xrdb`, `xprop`, `xrandr`, `xsettingsd`, `dunst`, `notify-send`, `scrot`/`import`/`maim`, `wpctl`/`pactl`/`amixer`/`sndioctl`, `nmcli`/`wpa_cli`, `bluetoothctl`, `playerctl`/`mpc`, `chronyc`, `doas`/`sudo`/`pkexec`, and **Fira Code** + **DejaVuSansM Nerd Font**. ## Build & install @@ -44,10 +46,15 @@ make PREFIX=/opt/anode CC=clang WITH_GTKTTK=1 make DESTDIR=/tmp/stage PREFIX=/usr/local install ``` -Start ANODE from `.xinitrc` (`exec /usr/local/bin/anode-session`) or via a display manager selecting the installed `ANODE` XSession (`PREFIX/share/xsessions/anode.desktop`). +Start ANODE from `.xinitrc` (`exec /usr/local/bin/anode-session`) or via a display manager selecting the installed `ANODE` XSession (`PREFIX/share/xsessions/anode.desktop`). Passing `--profile NAME` (or setting `ANODE_SESSION_PROFILE`) selects a session profile for autostart. + +## Session autostart + +`anode-session` invokes `anode-autostart start` once DWM advertises `_NET_SUPPORTING_WM_CHECK`, seeding `~/.config/anode/autostart` from `PREFIX/share/anode/autostart` on first launch. Supported directives follow i3 conventions (`exec`, `exec_once`, `exec_always`, `--no-startup-id`, `include`), alongside per-profile files (`~/.config/anode/autostart.`), drop-in scripts or `.desktop` entries in `~/.config/anode/autostart.d/`, and `ANODE`-filtered XDG autostart entries. Pressing `Mod4 + Shift + r` or sending `SIGHUP` to DWM reloads `.Xresources`/theme/DPI and triggers `anode-autostart reload` (re-running `exec_always` entries). See [docs/AUTOSTART.md](docs/AUTOSTART.md) for full directive, profile, and XDG precedence details. ## Documentation & tests +- [Session autostart](docs/AUTOSTART.md) - [Architecture](docs/ARCHITECTURE.md) - [Keybindings](docs/KEYBINDINGS.md) diff --git a/data/autostart b/data/autostart new file mode 100644 index 0000000..c651839 --- /dev/null +++ b/data/autostart @@ -0,0 +1,24 @@ +# ANODE session autostart configuration (~/.config/anode/autostart) +# +# Supported i3-style directives: +# exec [--no-startup-id] Run once at session start +# exec_once [--no-startup-id] Run at start only if not already running +# exec_always [--no-startup-id] Run at start AND on DWM reload/restart (Mod4+Shift+r / SIGHUP) +# include Include another autostart file (e.g. ~/.config/anode/local.conf) +# +# Additional session autostart layers: +# - Per-profile file: ~/.config/anode/autostart. (set via ANODE_SESSION_PROFILE or --profile) +# - Executable scripts or .desktop entries in ~/.config/anode/autostart.d/ +# - XDG ~/.config/autostart/ and /etc/xdg/autostart/ (filtered by OnlyShowIn / NotShowIn for ANODE) + +# Example keyboard / X11 input configuration on reload and startup: +# exec_always --no-startup-id xset r rate 260 35 +# exec_always --no-startup-id setxkbmap us + +# Example wallpaper restore on startup and reload: +# exec_always --no-startup-id sh -c '[ -r ~/.wallpaper ] && feh --bg-fill ~/.wallpaper' + +# Example systray applets & compositor (started once per session): +# exec_once --no-startup-id nm-applet +# exec_once --no-startup-id blueman-applet +# exec_once --no-startup-id picom diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7e67527..086cec9 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -9,7 +9,7 @@ - `src/apps/`: Desktop control panels and optional dock virtual keyboard (`anode-vkbd`) + multimedia dispatcher (`anode-media-key`). - `src/daemons/`: Zero-poll `poll()` + signal self-pipe daemons (`anode-statusd`, `anode-touchd`, `anode-powerd`) and narrowly-scoped privilege helpers (`anode-power-ctl`, `anode-dnsctl`, `anode-tzctl`, `anode-checkpw`). - `src/gtkTtk/`: Tk/Ttk native GTK-2 bridge (`libgtkTtk0.9.so` + `gtkTtk.tcl`) supporting full `[0.5, 4.0]` fractional scaling. -- `data/` & `scripts/`: 22 96-DPI `.xth` themes and strict POSIX `/bin/sh` synchronization scripts. +- `data/` & `scripts/`: 22 96-DPI `.xth` themes, strict POSIX `/bin/sh` synchronization scripts, and i3-style session autostart management (`anode-autostart` + `data/autostart` template). ## Fractional DPI multi-toolkit contract @@ -27,3 +27,9 @@ In `src/dwm/dwm.c`: 1. Acquires screen-specific `_NET_SYSTEM_TRAY_S` using a 32-bit ARGB `TrueColor` visual (when available, falling back cleanly to screen default visual) and publishes `_NET_SYSTEM_TRAY_VISUAL` and `_NET_SYSTEM_TRAY_ORIENTATION = 0`. 2. Tracks XEmbed `_XEMBED_INFO` flags bit `data[1]` (`XEMBED_MAPPED`), preserves `SubstructureNotifyMask`, emits `XEMBED_WINDOW_ACTIVATE` / `XEMBED_WINDOW_DEACTIVATE (2)`, unmaps the tray window when empty (`0` mapped icons), undocks cleanly on `ReparentNotify`/`UnmapNotify`/`DestroyNotify`, centers & re-scales icons on `SIGUSR1` / `XA_RESOURCE_MANAGER`, and relocates cleanly across monitors. 3. Monitors `_NET_WM_WINDOW_TYPE_DOCK` windows (`_NET_WM_STRUT_PARTIAL` / `_NET_WM_STRUT`), including `override_redirect` docks such as `anode-vkbd`, adjusting monitor workarea bounds (`wx, wy, ww, wh`) and publishing root `_NET_WORKAREA`. + +## Session autostart pipeline + +1. `anode-session` exports `XDG_CURRENT_DESKTOP=ANODE`, `XDG_SESSION_DESKTOP=anode`, `DESKTOP_SESSION=anode`, and optional `ANODE_SESSION_PROFILE`, seeds `~/.config/anode/autostart` and `~/.config/anode/autostart.d/`, and starts a background waiter polling `_NET_SUPPORTING_WM_CHECK` before invoking `anode-autostart start`. +2. `anode-autostart` evaluates declarative files (`autostart` + optional `autostart.` + `include` graph via POSIX `awk`), then on `start` evaluates `autostart.d/` drop-ins and `ANODE`-filtered XDG `.desktop` entries with user-over-system basename masking. +3. `src/dwm/dwm.c` triggers `anode-autostart reload` (running only `exec_always`) from interactive `reloadxres` (`Mod4 + Shift + r`, `arg->i = 1`) and post-`SIGHUP` `execvp` restart (`ANODE_DWM_RESTARTED=1`), while `SIGUSR1` and `XA_RESOURCE_MANAGER` pass `NULL` so live theme/DPI reloads never cause autostart loops. diff --git a/docs/AUTOSTART.md b/docs/AUTOSTART.md new file mode 100644 index 0000000..83c6575 --- /dev/null +++ b/docs/AUTOSTART.md @@ -0,0 +1,74 @@ +# ANODE session autostart + +ANODE supports i3-style session-specific autostart directives paired with per-profile overrides, `autostart.d/` drop-ins, and `ANODE`-filtered XDG `.desktop` entries. + +## Startup lifecycle + +- `anode-session` exports `XDG_CURRENT_DESKTOP=ANODE`, `XDG_SESSION_DESKTOP=anode`, `DESKTOP_SESSION=anode`, and `ANODE_SESSION_PROFILE` when `--profile NAME` or `--profile=NAME` is passed. +- On first session launch, `anode-session` creates `~/.config/anode/autostart.d/` and copies `PREFIX/share/anode/autostart` (falling back to `data/autostart` in source checkouts) to `~/.config/anode/autostart` if absent. +- Once `dwm` advertises `_NET_SUPPORTING_WM_CHECK` on the root window (polled with `xprop` for up to 2 s, falling back to `sleep 1`), `anode-session` launches `anode-autostart start` in the background. +- Pressing `Mod4 + Shift + r` (`reloadxres` with `arg->i = 1`) or sending `SIGHUP` to `dwm` (live `execvp` restart carrying `ANODE_DWM_RESTARTED=1`) triggers `anode-autostart reload`, re-running only `exec_always` entries. Background theme/DPI reloads via `SIGUSR1` or `XA_RESOURCE_MANAGER` pass `NULL` and do not re-trigger `anode-autostart reload`. + +## Declarative directives + +Declarative rules live in `~/.config/anode/autostart` (or the file passed via `--config FILE`). Blank lines and lines starting with `#` are ignored, and `--no-startup-id` is accepted for i3 compatibility. + +| Directive | Behavior | +|---|---| +| `exec [--no-startup-id] ` | Run `` once during `anode-autostart start` | +| `exec_once [--no-startup-id] ` | Run `` during `start` only when no process matching its executable basename is already running (checked via POSIX `ps`) | +| `exec_always [--no-startup-id] ` | Run `` during `start` and re-run on `anode-autostart reload` (`Mod4 + Shift + r` or `SIGHUP` restart) | +| `include ` | Load directives from another file (absolute path, `~/...`, or relative to the current file; duplicate/cyclic includes are skipped, and nesting deeper than 8 levels fails `check`) | + +## Session profiles + +Passing `--profile NAME` or `--profile=NAME` to `anode-session` or `anode-autostart` (or exporting `ANODE_SESSION_PROFILE=NAME`) loads `~/.config/anode/autostart.` (or `PREFIX/share/anode/autostart.` if no user file exists) immediately after the base `autostart` file: + +```sh +# ~/.xinitrc +exec /usr/local/bin/anode-session --profile work +``` + +## Drop-ins & XDG autostart + +During `start` (never during `reload`), `anode-autostart` also evaluates drop-in scripts/desktop files and XDG autostart directories: + +- **Drop-in directories**: `$XDG_CONFIG_HOME/anode/autostart.d/` followed by `$ANODE_PREFIX/share/anode/autostart.d/`. Earlier basenames shadow later ones; regular executable files are executed directly, and `*.desktop` files follow desktop-entry filtering. +- **XDG autostart directories**: `$XDG_CONFIG_HOME/autostart/*.desktop` followed by each directory in `$XDG_CONFIG_DIRS` (default `/etc/xdg/autostart/*.desktop`). Earlier basenames shadow later ones, so placing a `.desktop` file with `Hidden=true` in `~/.config/autostart/` masks the corresponding system entry. +- **Desktop-entry filtering**: Honors `Hidden=true`, case-insensitive `OnlyShowIn` / `NotShowIn` matching against `$XDG_CURRENT_DESKTOP`, `TryExec` binary lookup, `Terminal=true` execution via `st -e `, and stripping of `%f`/`%F`/`%u`/`%U`/`%d`/`%D`/`%n`/`%N`/`%i`/`%c`/`%k`/`%v`/`%m` field codes (`%%` is unescaped to `%`). +- **Disabling XDG autostart**: Pass `--no-xdg` or set `ANODE_XDG_AUTOSTART=0` to skip XDG `.desktop` discovery while keeping declarative configs and `autostart.d/` drop-ins active. + +## Command-line usage + +Syntax: `anode-autostart [start|reload|list|check] [OPTIONS]` + +| Argument / flag | Behavior | +|---|---| +| `start` | Default subcommand; run `exec`, `exec_once`, `exec_always`, `autostart.d/`, and XDG entries | +| `reload` | Run only `exec_always` directives (invoked by `dwm` on `Mod4 + Shift + r` and `SIGHUP` restart) | +| `list` | Print resolved commands and drop-ins without executing them | +| `check` | Validate declarative configs and `include` chains (exits `0` on valid, non-zero on error) | +| `--config FILE` / `--config=FILE` | Use `FILE` instead of `~/.config/anode/autostart` | +| `--profile NAME` / `--profile=NAME` | Load profile overrides from `autostart.NAME` | +| `--no-xdg` | Skip `$XDG_CONFIG_HOME/autostart` and `$XDG_CONFIG_DIRS/autostart` entries | +| `--dry-run` | Print `[exec]`, `[exec_once]`, `[exec_always]`, `[script]`, and `[desktop]` actions without launching | + +```sh +anode-autostart check +anode-autostart list --profile work +anode-autostart reload --dry-run +``` + +## Example configuration + +```sh +# ~/.config/anode/autostart +include ~/.config/anode/local.conf + +exec_always --no-startup-id xset r rate 260 35 +exec_always --no-startup-id sh -c '[ -r ~/.wallpaper ] && feh --bg-fill ~/.wallpaper' + +exec_once --no-startup-id nm-applet +exec_once --no-startup-id picom +exec notify-send "ANODE" "Session ready" +``` diff --git a/docs/KEYBINDINGS.md b/docs/KEYBINDINGS.md index 62ff823..ee4bce5 100644 --- a/docs/KEYBINDINGS.md +++ b/docs/KEYBINDINGS.md @@ -24,7 +24,7 @@ Default `MODKEY` is `Mod4` (`Super` / `Win`). | `Mod4 + Tab` | Toggle previous tag | | `Mod4 + ,` / `.` | Focus previous / next monitor | | `Mod4 + Shift + ,` / `.` | Send window to previous / next monitor | -| `Mod4 + Shift + r` | Reload `.Xresources` / theme / DPI scale | +| `Mod4 + Shift + r` | Reload `.Xresources` / theme / DPI scale and `exec_always` autostart entries | | `Mod4 + Ctrl + Shift + q` | Quit DWM | ## Utilities & multimedia keys diff --git a/scripts/anode-autostart b/scripts/anode-autostart new file mode 100755 index 0000000..3b1b20b --- /dev/null +++ b/scripts/anode-autostart @@ -0,0 +1,478 @@ +#!/bin/sh +# ANODE session autostart runner (i3-style directives + drop-ins + XDG autostart, strict POSIX sh) +set -eu + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +: "${XDG_CONFIG_DIRS:=/etc/xdg}" +: "${XDG_CURRENT_DESKTOP:=ANODE}" +: "${ANODE_PREFIX:=/usr/local}" +: "${ANODE_XDG_AUTOSTART:=1}" + +SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +CONF_DIR="$XDG_CONFIG_HOME/anode" + +MODE="start" +EXPLICIT_CFG="" +PROFILE="${ANODE_SESSION_PROFILE:-}" +ENABLE_XDG="$ANODE_XDG_AUTOSTART" +DRY_RUN=0 + +usage() { + cat <<'EOF' +Usage: anode-autostart [start|reload|list|check] [OPTIONS] + +Commands: + start Run exec, exec_once, exec_always, autostart.d/, and XDG entries (default) + reload Run only exec_always directives (used on WM reload/restart) + list Print resolved autostart entries without executing them + check Validate declarative autostart files and includes (exit 0 on valid) + +Options: + --config FILE Use FILE instead of ~/.config/anode/autostart + --profile NAME Load session profile overrides from autostart.NAME + --no-xdg Skip XDG /etc/xdg/autostart and ~/.config/autostart/*.desktop + --dry-run Print actions that would run without executing them + -h, --help Show this help +EOF +} + +while [ $# -gt 0 ]; do + case "$1" in + start|reload|list|check) + MODE="$1" + shift + ;; + --config) + [ $# -ge 2 ] || { printf 'anode-autostart: --config requires a path\n' >&2; exit 2; } + EXPLICIT_CFG="$2" + shift 2 + ;; + --config=*) + EXPLICIT_CFG="${1#--config=}" + shift + ;; + --profile) + [ $# -ge 2 ] || { printf 'anode-autostart: --profile requires a name\n' >&2; exit 2; } + PROFILE="$2" + shift 2 + ;; + --profile=*) + PROFILE="${1#--profile=}" + shift + ;; + --no-xdg) + ENABLE_XDG=0 + shift + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + *) + printf 'anode-autostart: unknown argument: %s\n' "$1" >&2 + exit 2 + ;; + esac +done + +if [ "$MODE" = "list" ]; then + DRY_RUN=1 +fi + +find_sys_file() { + _rel="$1" + for _base in \ + "$ANODE_PREFIX/share/anode" \ + "$SCRIPT_DIR/../share/anode" \ + "$SCRIPT_DIR/../data" + do + if [ -r "$_base/$_rel" ]; then + printf '%s\n' "$_base/$_rel" + return 0 + fi + done + return 1 +} + +PRIMARY_CFG="" +if [ -n "$EXPLICIT_CFG" ]; then + if [ ! -r "$EXPLICIT_CFG" ]; then + printf 'anode-autostart: config file not readable: %s\n' "$EXPLICIT_CFG" >&2 + exit 1 + fi + PRIMARY_CFG="$EXPLICIT_CFG" +elif [ -r "$CONF_DIR/autostart" ]; then + PRIMARY_CFG="$CONF_DIR/autostart" +else + PRIMARY_CFG="$(find_sys_file autostart || true)" +fi + +PROFILE_CFG="" +if [ -n "$PROFILE" ]; then + if [ -r "$CONF_DIR/autostart.$PROFILE" ]; then + PROFILE_CFG="$CONF_DIR/autostart.$PROFILE" + else + PROFILE_CFG="$(find_sys_file "autostart.$PROFILE" || true)" + fi +fi + +# Extract executable basename from a shell command line for exec_once tracking +cmd_exec_base() { + awk -v raw="$1" 'BEGIN { + n = split(raw, a, /[ \t]+/) + tok = "" + for (i = 1; i <= n; i++) { + if (a[i] == "") continue + if (a[i] == "exec" || a[i] == "nohup" || a[i] == "env") continue + if (a[i] ~ /^[A-Za-z_][A-Za-z0-9_]*=/) continue + tok = a[i] + break + } + gsub(/^["'\'']|["'\'']$/, "", tok) + sub(/^.*\//, "", tok) + print tok + }' +} + +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" ' + { + pid = $1; comm = $2; arg1 = $3 + if (pid == self) next + sub(/^.*\//, "", comm) + sub(/^.*\//, "", arg1) + if (comm == tgt || arg1 == tgt) { + found = 1 + exit 0 + } + } + END { exit found ? 0 : 1 } + ' +} + +launch_cmd() { + _cmd="$1" + (sh -c "$_cmd" /dev/null 2>&1 &) +} + +run_declarative_files() { + _strict=0 + [ "$MODE" = "check" ] && _strict=1 + + if [ -z "$PRIMARY_CFG" ] && [ -z "$PROFILE_CFG" ]; then + return 0 + fi + + _awk_err=0 + _parsed="$(awk -v conf_dir="$CONF_DIR" -v home_dir="$HOME" -v strict="$_strict" ' + function trim(s) { + gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s) + return s + } + function resolve_inc(p, base_dir, out) { + gsub(/^["'\'']|["'\'']$/, "", p) + if (p ~ /^~\//) { + out = home_dir "/" substr(p, 3) + } else if (p ~ /^\//) { + out = p + } else { + out = base_dir "/" p + } + return out + } + function parse_file(fpath, base_dir, depth, nlines, i, raw, s, verb, rest, inc_p, inc_dir, rc) { + if (depth > 8) { + printf "anode-autostart: include depth exceeded at %s\n", fpath > "/dev/stderr" + had_err = 1 + return + } + if (fpath in visited) { + printf "anode-autostart: skipping cyclic/duplicate include: %s\n", fpath > "/dev/stderr" + return + } + visited[fpath] = 1 + nlines = 0 + while ((rc = (getline raw < fpath)) > 0) { + file_lines[fpath, ++nlines] = raw + } + close(fpath) + if (rc < 0 && nlines == 0) { + printf "anode-autostart: cannot read include file: %s\n", fpath > "/dev/stderr" + if (strict) had_err = 1 + return + } + for (i = 1; i <= nlines; i++) { + s = trim(file_lines[fpath, i]) + if (s == "" || substr(s, 1, 1) == "#") continue + + if (s ~ /^[A-Za-z0-9_]+[ \t]+/) { + match(s, /^[A-Za-z0-9_]+/) + verb = substr(s, 1, RLENGTH) + rest = trim(substr(s, RLENGTH + 1)) + } else { + verb = s + rest = "" + } + + if (verb == "exec" || verb == "exec_once" || verb == "exec_always") { + if (rest ~ /^--no-startup-id([ \t]|$)/) { + rest = trim(substr(rest, 16)) + } + if (rest == "") { + printf "anode-autostart: %s:%d: missing command for %s\n", fpath, i, verb > "/dev/stderr" + had_err = 1 + continue + } + printf "%s\t%s\n", verb, rest + } else if (verb == "include") { + if (rest == "") { + printf "anode-autostart: %s:%d: missing path for include\n", fpath, i > "/dev/stderr" + had_err = 1 + continue + } + inc_p = resolve_inc(rest, base_dir) + inc_dir = inc_p + if (inc_dir ~ /\//) { + sub(/\/[^\/]*$/, "", inc_dir) + if (inc_dir == "") inc_dir = "/" + } else { + inc_dir = base_dir + } + parse_file(inc_p, inc_dir, depth + 1) + } else { + printf "anode-autostart: %s:%d: unknown directive: %s\n", fpath, i, verb > "/dev/stderr" + had_err = 1 + } + } + } + BEGIN { + had_err = 0 + for (fi = 1; fi < ARGC; fi++) { + fp = ARGV[fi] + ARGV[fi] = "" + if (fp != "") { + bdir = fp + if (bdir ~ /\//) { + sub(/\/[^\/]*$/, "", bdir) + if (bdir == "") bdir = "/" + } else { + bdir = conf_dir + } + parse_file(fp, bdir, 0) + } + } + if (strict && had_err) exit 1 + exit 0 + } + ' "$PRIMARY_CFG" "$PROFILE_CFG")" || _awk_err=1 + + if [ "$_awk_err" != "0" ] && [ "$MODE" = "check" ]; then + return 1 + fi + if [ "$MODE" = "check" ]; then + return 0 + fi + + _tab="$(printf '\t')" + printf '%s\n' "$_parsed" | while IFS="$_tab" read -r _kind _cmd; do + [ -n "${_kind:-}" ] || continue + case "$MODE:$_kind" in + reload:exec|reload:exec_once) + continue + ;; + esac + if [ "$_kind" = "exec_once" ] && [ "$DRY_RUN" != "1" ]; then + _base="$(cmd_exec_base "$_cmd")" + if is_proc_running "$_base"; then + continue + fi + fi + if [ "$DRY_RUN" = "1" ]; then + printf '[%s] %s\n' "$_kind" "$_cmd" + else + launch_cmd "$_cmd" + fi + done +} + +# Parse a .desktop autostart file and print: +# HIDDEN if Hidden=true +# EXEC\t\t if runnable for XDG_CURRENT_DESKTOP +# SKIP otherwise +parse_desktop_entry() { + _df="$1" + awk -v cur_desk="$XDG_CURRENT_DESKTOP" ' + function trim(s) { + gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s) + return 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 + } + BEGIN { in_de = 0; hidden = ""; only_in = ""; not_in = ""; try_exec = ""; exec_cmd = ""; term = "" } + { + s = trim($0) + if (s == "" || substr(s, 1, 1) == "#") next + if (substr(s, 1, 1) == "[") { + in_de = (s == "[Desktop Entry]") ? 1 : 0 + next + } + if (!in_de) next + eq = index(s, "=") + if (eq <= 0) next + k = trim(substr(s, 1, eq - 1)) + v = trim(substr(s, eq + 1)) + if (k == "Hidden") hidden = v + else if (k == "OnlyShowIn") only_in = v + else if (k == "NotShowIn") not_in = v + else if (k == "TryExec") try_exec = v + else if (k == "Exec") exec_cmd = v + else if (k == "Terminal") term = v + } + END { + if (tolower(hidden) == "true") { + print "HIDDEN" + exit + } + if (only_in != "" && !list_matches(only_in, cur_desk)) { + print "SKIP" + exit + } + if (not_in != "" && list_matches(not_in, cur_desk)) { + print "SKIP" + exit + } + if (exec_cmd == "") { + print "SKIP" + exit + } + gsub(/%%/, "\001", exec_cmd) + gsub(/%[fFuUdDnNickvm]/, "", exec_cmd) + gsub(/\001/, "%", exec_cmd) + exec_cmd = trim(exec_cmd) + if (exec_cmd == "") { + print "SKIP" + exit + } + if (tolower(term) == "true") { + exec_cmd = "st -e " exec_cmd + } + printf "EXEC\t%s\t%s\n", try_exec, exec_cmd + } + ' "$_df" +} + +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 +} + +run_dir_dropins_and_xdg() { + if [ "$MODE" = "reload" ] || [ "$MODE" = "check" ]; then + return 0 + fi + + _seen_dropins=":" + for _ddir in \ + "$CONF_DIR/autostart.d" \ + "$ANODE_PREFIX/share/anode/autostart.d" \ + "$SCRIPT_DIR/../share/anode/autostart.d" \ + "$SCRIPT_DIR/../data/autostart.d" + do + [ -d "$_ddir" ] || continue + for _item in "$_ddir"/*; do + [ -e "$_item" ] || continue + _bn="$(basename "$_item")" + case "$_seen_dropins" in + *":$_bn:"*) continue ;; + esac + _seen_dropins="${_seen_dropins}${_bn}:" + + case "$_bn" in + *.desktop) + [ -r "$_item" ] || continue + _res="$(parse_desktop_entry "$_item")" + case "$_res" in + EXEC*) + _te="$(printf '%s\n' "$_res" | cut -f2)" + _ecmd="$(printf '%s\n' "$_res" | cut -f3-)" + if check_try_exec "$_te"; then + if [ "$DRY_RUN" = "1" ]; then + printf '[desktop] %s\n' "$_ecmd" + else + launch_cmd "$_ecmd" + fi + fi + ;; + esac + ;; + *) + if [ -f "$_item" ] && [ -x "$_item" ]; then + if [ "$DRY_RUN" = "1" ]; then + printf '[script] %s\n' "$_item" + else + launch_cmd "$_item" + fi + fi + ;; + esac + done + done + + if [ "$ENABLE_XDG" = "1" ]; then + _seen_xdg=":" + _old_ifs="$IFS" + IFS=: + for _xbase in "$XDG_CONFIG_HOME" $XDG_CONFIG_DIRS; do + [ -n "$_xbase" ] || continue + _xdir="$_xbase/autostart" + [ -d "$_xdir" ] || continue + for _df in "$_xdir"/*.desktop; do + [ -r "$_df" ] || continue + _bn="$(basename "$_df")" + case "$_seen_xdg" in + *":$_bn:"*) continue ;; + esac + _seen_xdg="${_seen_xdg}${_bn}:" + + _res="$(parse_desktop_entry "$_df")" + case "$_res" in + EXEC*) + _te="$(printf '%s\n' "$_res" | cut -f2)" + _ecmd="$(printf '%s\n' "$_res" | cut -f3-)" + if check_try_exec "$_te"; then + if [ "$DRY_RUN" = "1" ]; then + printf '[desktop] %s\n' "$_ecmd" + else + launch_cmd "$_ecmd" + fi + fi + ;; + esac + done + done + IFS="$_old_ifs" + fi +} + +run_declarative_files || exit 1 +run_dir_dropins_and_xdg diff --git a/scripts/anode-session b/scripts/anode-session index f06393d..95d3a1f 100755 --- a/scripts/anode-session +++ b/scripts/anode-session @@ -4,8 +4,36 @@ set -u : "${XDG_CONFIG_HOME:=$HOME/.config}" : "${ANODE_PREFIX:=/usr/local}" +: "${XDG_CURRENT_DESKTOP:=ANODE}" +: "${XDG_SESSION_DESKTOP:=anode}" +: "${DESKTOP_SESSION:=anode}" SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +while [ $# -gt 0 ]; do + case "$1" in + --profile) + if [ $# -ge 2 ]; then + ANODE_SESSION_PROFILE="$2" + shift 2 + else + shift + fi + ;; + --profile=*) + ANODE_SESSION_PROFILE="${1#--profile=}" + shift + ;; + *) + shift + ;; + esac +done + +export XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP DESKTOP_SESSION +if [ -n "${ANODE_SESSION_PROFILE:-}" ]; then + export ANODE_SESSION_PROFILE +fi + # Ensure ANODE prefix binaries are on PATH case ":$PATH:" in *":$SCRIPT_DIR:"*) ;; @@ -67,6 +95,38 @@ if [ "${ANODE_TOUCH:-0}" = "1" ]; then spawn_bg anode-vkbd fi +# Seed default user autostart files on first session launch +mkdir -p "$XDG_CONFIG_HOME/anode/autostart.d" +if [ ! -e "$XDG_CONFIG_HOME/anode/autostart" ]; then + for _tpl in "$ANODE_PREFIX/share/anode/autostart" "$SCRIPT_DIR/../share/anode/autostart" "$SCRIPT_DIR/../data/autostart"; do + if [ -r "$_tpl" ]; then + cp "$_tpl" "$XDG_CONFIG_HOME/anode/autostart" 2>/dev/null || true + break + fi + done + unset _tpl +fi + +# Launch i3-style and XDG session autostart entries once DWM is ready +if command -v anode-autostart >/dev/null 2>&1; then + ( + _i=0 + if command -v xprop >/dev/null 2>&1; then + while [ "$_i" -lt 20 ]; do + if xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | grep -q "window id"; then + break + fi + _i=$(( _i + 1 )) + sleep 0.1 + done + else + sleep 1 + fi + anode-autostart start + ) >/dev/null 2>&1 & + BG_PIDS="$BG_PIDS $!" +fi + if command -v dwm >/dev/null 2>&1; then dwm else diff --git a/src/dwm/config.def.h b/src/dwm/config.def.h index a384de1..8cb0695 100644 --- a/src/dwm/config.def.h +++ b/src/dwm/config.def.h @@ -93,6 +93,7 @@ static const char *mednextcmd[] = { "anode-media-key", "next", NULL }; static const char *medstopcmd[] = { "anode-media-key", "stop", NULL }; static const char *airplanecmd[] = { "anode-media-key", "airplane", NULL }; static const char *suspendcmd[] = { "anode-media-key", "suspend", NULL }; +static const char *autostartreloadcmd[] = { "anode-autostart", "reload", NULL }; static const Key keys[] = { /* modifier key function argument */ @@ -168,7 +169,7 @@ static const Key keys[] = { { MODKEY, XK_period, focusmon, {.i = +1} }, { MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1} }, { MODKEY|ShiftMask, XK_period, tagmon, {.i = +1} }, - { MODKEY|ShiftMask, XK_r, reloadxres, {0} }, + { MODKEY|ShiftMask, XK_r, reloadxres, {.i = 1} }, TAGKEYS( XK_1, 0) TAGKEYS( XK_2, 1) TAGKEYS( XK_3, 2) diff --git a/src/dwm/config.h b/src/dwm/config.h index a384de1..8cb0695 100644 --- a/src/dwm/config.h +++ b/src/dwm/config.h @@ -93,6 +93,7 @@ static const char *mednextcmd[] = { "anode-media-key", "next", NULL }; static const char *medstopcmd[] = { "anode-media-key", "stop", NULL }; static const char *airplanecmd[] = { "anode-media-key", "airplane", NULL }; static const char *suspendcmd[] = { "anode-media-key", "suspend", NULL }; +static const char *autostartreloadcmd[] = { "anode-autostart", "reload", NULL }; static const Key keys[] = { /* modifier key function argument */ @@ -168,7 +169,7 @@ static const Key keys[] = { { MODKEY, XK_period, focusmon, {.i = +1} }, { MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1} }, { MODKEY|ShiftMask, XK_period, tagmon, {.i = +1} }, - { MODKEY|ShiftMask, XK_r, reloadxres, {0} }, + { MODKEY|ShiftMask, XK_r, reloadxres, {.i = 1} }, TAGKEYS( XK_1, 0) TAGKEYS( XK_2, 1) TAGKEYS( XK_3, 2) diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c index 9cb1fe7..c252524 100644 --- a/src/dwm/dwm.c +++ b/src/dwm/dwm.c @@ -1295,6 +1295,10 @@ static void reloadxres(const Arg *arg) { arrange(NULL); drawbars(); XSync(dpy, False); + if (arg && arg->i) { + Arg a = {.v = autostartreloadcmd}; + spawn(&a); + } } static void manage(Window w, XWindowAttributes *wa) { @@ -2750,10 +2754,19 @@ int main(int argc, char *argv[]) { checkotherwm(); setup(); scan(); + { + const char *rs = getenv("ANODE_DWM_RESTARTED"); + if (rs && rs[0] == '1') { + unsetenv("ANODE_DWM_RESTARTED"); + Arg a = {.v = autostartreloadcmd}; + spawn(&a); + } + } run(); cleanup(); XCloseDisplay(dpy); if (restart_dwm) { + setenv("ANODE_DWM_RESTARTED", "1", 1); execvp(argv[0], argv); } return EXIT_SUCCESS; diff --git a/tests/test_autostart.py b/tests/test_autostart.py new file mode 100755 index 0000000..de29d5c --- /dev/null +++ b/tests/test_autostart.py @@ -0,0 +1,477 @@ +#!/usr/bin/env python3 +"""Integration and headless Xvfb tests for ANODE i3-style session autostart.""" + +import ctypes +import ctypes.util +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import time + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +AUTOSTART = os.path.join(ROOT, "scripts", "anode-autostart") +DWM_BIN = os.path.join(ROOT, "build", "dwm", "dwm") + + +def wait_until(pred, timeout=5.0, interval=0.05): + end = time.monotonic() + timeout + while time.monotonic() < end: + res = pred() + if res: + return res + time.sleep(interval) + return None + + +def make_base_env(tmp): + home = os.path.join(tmp, "home") + xdg_home = os.path.join(tmp, "xdg_home") + xdg_sys = os.path.join(tmp, "xdg_sys") + sys_prefix = os.path.join(tmp, "sys_prefix") + bin_dir = os.path.join(tmp, "bin") + for d in ( + home, + os.path.join(xdg_home, "anode", "autostart.d"), + os.path.join(xdg_home, "autostart"), + os.path.join(xdg_sys, "autostart"), + os.path.join(sys_prefix, "share", "anode", "autostart.d"), + bin_dir, + ): + os.makedirs(d, exist_ok=True) + + env = dict(os.environ) + env["HOME"] = home + env["XDG_CONFIG_HOME"] = xdg_home + env["XDG_CONFIG_DIRS"] = xdg_sys + env["ANODE_PREFIX"] = sys_prefix + env["XDG_CURRENT_DESKTOP"] = "ANODE" + env["ANODE_XDG_AUTOSTART"] = "1" + env.pop("ANODE_SESSION_PROFILE", None) + env["PATH"] = bin_dir + ":" + os.path.join(ROOT, "scripts") + ":" + env.get("PATH", "/usr/bin:/bin") + return env, home, xdg_home, xdg_sys, sys_prefix, bin_dir + + +def run_autostart(args, env): + return subprocess.run([AUTOSTART] + args, env=env, capture_output=True, text=True) + + +def write_text(path, content, mode=0o644): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(content) + os.chmod(path, mode) + + +def compile_sleep_dummy(out_path): + cc = os.environ.get("CC", "cc") + c_src = out_path + ".c" + write_text( + c_src, + "#include \n" + "#include \n" + "int main(int argc, char **argv) {\n" + " if (argc > 1) {\n" + " FILE *f = fopen(argv[1], \"a\");\n" + " if (f) { fprintf(f, \"%ld\\n\", (long)getpid()); fclose(f); }\n" + " }\n" + " sleep(30);\n" + " return 0;\n" + "}\n", + ) + subprocess.run([cc, "-O2", c_src, "-o", out_path], check=True) + os.remove(c_src) + + +def kill_pids_from_file(path): + if not os.path.exists(path): + return + with open(path, "r", encoding="utf-8") as f: + for line in f: + s = line.strip() + if s.isdigit(): + try: + os.kill(int(s), signal.SIGTERM) + except ProcessLookupError: + pass + + +def test_directives_includes_once_and_reload(): + with tempfile.TemporaryDirectory() as tmp: + env, home, 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) + + once_bin1 = os.path.join(bin_dir, "anode_once1") + once_bin2 = os.path.join(bin_dir, "anode_once2") + compile_sleep_dummy(once_bin1) + shutil.copy2(once_bin1, once_bin2) + + pre_pid_file = os.path.join(markers, "pre_once1.pid") + m_exec = os.path.join(markers, "exec.txt") + m_nosid = os.path.join(markers, "nosid.txt") + m_once_skip = os.path.join(markers, "once_skip.pid") + m_once_run = os.path.join(markers, "once_run.pid") + m_always = os.path.join(markers, "always.txt") + m_rel = os.path.join(markers, "rel.txt") + m_home = os.path.join(markers, "home.txt") + m_cyc = os.path.join(markers, "cyc.txt") + m_dropin = os.path.join(markers, "dropin.txt") + m_xdg = os.path.join(markers, "xdg.txt") + + pre_proc = subprocess.Popen([once_bin1, pre_pid_file]) + try: + assert wait_until(lambda: os.path.exists(pre_pid_file), timeout=3.0), "once_bin1 failed to start" + + write_text(os.path.join(conf_dir, "sub", "rel.conf"), f"exec printf 'rel\\n' >> '{m_rel}'\n") + write_text(os.path.join(home, "inc_home.conf"), f"exec printf 'home\\n' >> '{m_home}'\n") + write_text( + os.path.join(conf_dir, "cyc_a.conf"), + f"include cyc_b.conf\nexec printf 'cyc\\n' >> '{m_cyc}'\n", + ) + write_text(os.path.join(conf_dir, "cyc_b.conf"), "include cyc_a.conf\n") + write_text( + os.path.join(conf_dir, "autostart"), + "# Leading comment\n\n" + f"exec printf 'e1\\n' >> '{m_exec}'\n" + f"exec --no-startup-id printf 'e2\\n' >> '{m_nosid}'\n" + f"exec_once anode_once1 '{m_once_skip}'\n" + f"exec_once anode_once2 '{m_once_run}'\n" + f"exec_always printf 'al\\n' >> '{m_always}'\n" + "include sub/rel.conf\n" + "include ~/inc_home.conf\n" + "include cyc_a.conf\n", + ) + write_text(os.path.join(conf_dir, "autostart.d", "10-mark.sh"), f"#!/bin/sh\nprintf 'd\\n' >> '{m_dropin}'\n", 0o755) + write_text( + os.path.join(xdg_sys, "autostart", "xtest.desktop"), + f"[Desktop Entry]\nType=Application\nOnlyShowIn=ANODE;\nExec=sh -c \"printf 'x\\n' >> '{m_xdg}'\"\n", + ) + + chk = run_autostart(["check"], env) + assert chk.returncode == 0, f"check failed: {chk.stderr}" + + lst = run_autostart(["list"], env) + assert lst.returncode == 0, f"list failed: {lst.stderr}" + for expected in ("[exec]", "[exec_once]", "[exec_always]", "[script]", "[desktop]"): + assert expected in lst.stdout, f"missing {expected} in list output:\n{lst.stdout}" + assert not os.path.exists(m_exec), "list must not execute commands" + + dry = run_autostart(["start", "--dry-run"], env) + assert dry.returncode == 0 + assert "[exec_always]" in dry.stdout + assert not os.path.exists(m_exec), "--dry-run must not execute commands" + + st = run_autostart(["start"], env) + assert st.returncode == 0, f"start failed: {st.stderr}" + + for p in (m_exec, m_nosid, m_once_run, m_always, m_rel, m_home, m_cyc, m_dropin, m_xdg): + assert wait_until(lambda path=p: os.path.exists(path), timeout=4.0), f"expected marker {p}" + time.sleep(0.35) + assert not os.path.exists(m_once_skip), "exec_once ran even though anode_once1 was already running" + + # Verify reload runs ONLY exec_always + for p in (m_exec, m_nosid, m_always, m_rel, m_home, m_cyc, m_dropin, m_xdg): + os.remove(p) + + rl = run_autostart(["reload"], env) + assert rl.returncode == 0, f"reload failed: {rl.stderr}" + assert wait_until(lambda: os.path.exists(m_always), timeout=4.0), "reload did not run exec_always" + time.sleep(0.35) + for p in (m_exec, m_nosid, m_rel, m_home, m_cyc, m_dropin, m_xdg): + assert not os.path.exists(p), f"reload must not execute {p}" + finally: + if pre_proc.poll() is None: + pre_proc.terminate() + pre_proc.wait(timeout=2) + kill_pids_from_file(m_once_run) + kill_pids_from_file(m_once_skip) + + +def test_profiles(): + with tempfile.TemporaryDirectory() as tmp: + env, _, xdg_home, _, _, _ = make_base_env(tmp) + conf_dir = os.path.join(xdg_home, "anode") + m_base = os.path.join(tmp, "base.txt") + m_work = os.path.join(tmp, "work.txt") + + write_text(os.path.join(conf_dir, "autostart"), f"exec printf 'b\\n' >> '{m_base}'\n") + write_text(os.path.join(conf_dir, "autostart.work"), f"exec printf 'w\\n' >> '{m_work}'\n") + + for args, extra_env in ( + (["--profile", "work"], {}), + (["--profile=work"], {}), + ([], {"ANODE_SESSION_PROFILE": "work"}), + ): + for p in (m_base, m_work): + if os.path.exists(p): + os.remove(p) + cur_env = dict(env) + cur_env.update(extra_env) + res = run_autostart(args, cur_env) + assert res.returncode == 0, f"profile run failed: {res.stderr}" + assert wait_until(lambda: os.path.exists(m_base) and os.path.exists(m_work), timeout=4.0), ( + f"profile markers missing for args={args}, extra_env={extra_env}" + ) + + +def test_dropins_desktop_filters_and_xdg_masking(): + with tempfile.TemporaryDirectory() as tmp: + env, _, xdg_home, xdg_sys, sys_prefix, 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) + + m_override = os.path.join(markers, "override.txt") + m_nonexec = os.path.join(markers, "nonexec.txt") + m_bad = os.path.join(markers, "bad.txt") + m_term = os.path.join(markers, "term.txt") + m_clean = os.path.join(markers, "clean.txt") + m_xdg_sys = os.path.join(markers, "xdg_sys.txt") + m_masked = os.path.join(markers, "masked.txt") + + # Stub st to verify Terminal=true delegation + write_text(os.path.join(bin_dir, "st"), f"#!/bin/sh\nprintf '%s\\n' \"$*\" >> '{m_term}'\n", 0o755) + write_text(os.path.join(conf_dir, "autostart"), "# empty\n") + + # User drop-in overrides system drop-in of same basename + write_text( + os.path.join(sys_prefix, "share", "anode", "autostart.d", "10-ovr.sh"), + f"#!/bin/sh\nprintf 'sys\\n' >> '{m_override}'\n", + 0o755, + ) + write_text( + os.path.join(conf_dir, "autostart.d", "10-ovr.sh"), + f"#!/bin/sh\nprintf 'user\\n' >> '{m_override}'\n", + 0o755, + ) + # Non-executable file must be ignored + write_text( + os.path.join(conf_dir, "autostart.d", "20-nonexec.sh"), + f"#!/bin/sh\nprintf 'bad\\n' >> '{m_nonexec}'\n", + 0o644, + ) + + # .desktop filter cases in autostart.d/ + write_text( + os.path.join(conf_dir, "autostart.d", "hidden.desktop"), + f"[Desktop Entry]\nHidden=true\nExec=sh -c \"printf 'bad\\n' >> '{m_bad}'\"\n", + ) + write_text( + os.path.join(conf_dir, "autostart.d", "badtry.desktop"), + f"[Desktop Entry]\nTryExec=definitely_missing_binary_999\nExec=sh -c \"printf 'bad\\n' >> '{m_bad}'\"\n", + ) + write_text( + os.path.join(conf_dir, "autostart.d", "onlyother.desktop"), + f"[Desktop Entry]\nOnlyShowIn=GNOME;KDE;\nExec=sh -c \"printf 'bad\\n' >> '{m_bad}'\"\n", + ) + write_text( + os.path.join(conf_dir, "autostart.d", "notanode.desktop"), + f"[Desktop Entry]\nNotShowIn=ANODE;XFCE;\nExec=sh -c \"printf 'bad\\n' >> '{m_bad}'\"\n", + ) + write_text( + os.path.join(conf_dir, "autostart.d", "term.desktop"), + "[Desktop Entry]\nTryExec=sh\nTerminal=true\nOnlyShowIn=ANODE;\nExec=echo ok 100%%\n", + ) + write_text( + os.path.join(conf_dir, "autostart.d", "fieldcodes.desktop"), + f"[Desktop Entry]\nNotShowIn=KDE;\nExec=sh -c \"printf 'pc:%%s\\n' 100%% >> '{m_clean}'\" %f %U\n", + ) + + # XDG autostart masking + write_text( + os.path.join(xdg_sys, "autostart", "sysok.desktop"), + f"[Desktop Entry]\nExec=sh -c \"printf 'sysok\\n' >> '{m_xdg_sys}'\"\n", + ) + write_text( + os.path.join(xdg_sys, "autostart", "masked.desktop"), + f"[Desktop Entry]\nExec=sh -c \"printf 'bad\\n' >> '{m_masked}'\"\n", + ) + write_text( + os.path.join(xdg_home, "autostart", "masked.desktop"), + f"[Desktop Entry]\nHidden=true\nExec=sh -c \"printf 'bad\\n' >> '{m_masked}'\"\n", + ) + + st = run_autostart(["start"], env) + assert st.returncode == 0, f"start failed: {st.stderr}" + + assert wait_until(lambda: os.path.exists(m_override), timeout=4.0) + assert wait_until(lambda: os.path.exists(m_term), timeout=4.0) + assert wait_until(lambda: os.path.exists(m_clean), timeout=4.0) + assert wait_until(lambda: os.path.exists(m_xdg_sys), timeout=4.0) + time.sleep(0.35) + + with open(m_override, "r", encoding="utf-8") as f: + assert f.read().strip() == "user", "user drop-in must shadow system drop-in" + with open(m_term, "r", encoding="utf-8") as f: + term_out = f.read().strip() + assert term_out == "-e echo ok 100%", f"unexpected Terminal=true args: {term_out!r}" + with open(m_clean, "r", encoding="utf-8") as f: + assert f.read().strip() == "pc:100%", "percent unescaping / %f %U stripping failed" + assert not os.path.exists(m_nonexec), "non-executable drop-in ran" + assert not os.path.exists(m_bad), "filtered .desktop ran" + assert not os.path.exists(m_masked), "XDG Hidden=true override failed to mask system .desktop" + + # --no-xdg and ANODE_XDG_AUTOSTART=0 + for args, xenv in ((["start", "--no-xdg"], {}), (["start"], {"ANODE_XDG_AUTOSTART": "0"})): + for p in (m_xdg_sys, m_override): + if os.path.exists(p): + os.remove(p) + cur = dict(env) + cur.update(xenv) + res = run_autostart(args, cur) + assert res.returncode == 0 + assert wait_until(lambda: os.path.exists(m_override), timeout=4.0) + time.sleep(0.3) + assert not os.path.exists(m_xdg_sys), f"XDG ran despite {args} / {xenv}" + + +def test_check_errors(): + with tempfile.TemporaryDirectory() as tmp: + env, _, xdg_home, _, _, _ = make_base_env(tmp) + cfg = os.path.join(xdg_home, "anode", "autostart") + + for bad_name, content in ( + ("unknown directive", "frobnicate foo\n"), + ("missing exec cmd", "exec\n"), + ("missing --no-startup-id cmd", "exec_once --no-startup-id\n"), + ("missing include arg", "include\n"), + ("missing include target", "include does_not_exist.conf\n"), + ): + write_text(cfg, content) + res = run_autostart(["check"], env) + assert res.returncode != 0, f"expected check failure for {bad_name}" + + # Unreadable --config path + bad_cfg = run_autostart(["--config", os.path.join(tmp, "missing.conf"), "check"], env) + assert bad_cfg.returncode != 0 + + # Depth > 8 include chain + for idx in range(11): + nxt = f"include chain_{idx + 1}.conf\n" if idx < 10 else "exec true\n" + write_text(os.path.join(xdg_home, "anode", f"chain_{idx}.conf"), nxt) + res = run_autostart(["--config", os.path.join(xdg_home, "anode", "chain_0.conf"), "check"], env) + assert res.returncode != 0, "expected include depth > 8 to fail check" + + +def pick_display(): + for d in range(70, 120): + if not os.path.exists(f"/tmp/.X{d}-lock") and not os.path.exists(f"/tmp/.X11-unix/X{d}"): + return f":{d}" + return ":98" + + +def terminate(proc): + if proc and proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=3) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=2) + + +def test_dwm_sighup_reload_xvfb(): + assert shutil.which("Xvfb"), "Xvfb is required for test_dwm_sighup_reload_xvfb" + assert os.path.isfile(DWM_BIN), f"missing {DWM_BIN}" + + libx11_name = ctypes.util.find_library("X11") or "libX11.so.6" + X11 = ctypes.CDLL(libx11_name) + X11.XOpenDisplay.argtypes = [ctypes.c_char_p] + X11.XOpenDisplay.restype = ctypes.c_void_p + X11.XCloseDisplay.argtypes = [ctypes.c_void_p] + X11.XDefaultRootWindow.argtypes = [ctypes.c_void_p] + X11.XDefaultRootWindow.restype = ctypes.c_ulong + X11.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] + X11.XInternAtom.restype = ctypes.c_ulong + X11.XGetWindowProperty.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_long, ctypes.c_long, + ctypes.c_int, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_int), + ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), + ] + X11.XGetWindowProperty.restype = ctypes.c_int + X11.XFree.argtypes = [ctypes.c_void_p] + + disp = pick_display() + with tempfile.TemporaryDirectory() as tmp: + env, _, xdg_home, _, _, _ = make_base_env(tmp) + env["DISPLAY"] = disp + m_exec = os.path.join(tmp, "dwm_exec.txt") + m_always = os.path.join(tmp, "dwm_always.txt") + write_text( + os.path.join(xdg_home, "anode", "autostart"), + f"exec sh -c \"printf 'e\\n' >> '{m_exec}'\"\n" + f"exec_always sh -c \"printf 'a\\n' >> '{m_always}'\"\n", + ) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + dwm = None + dpy = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy, f"Xvfb failed to open on {disp}" + + dwm = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + wm_atom = X11.XInternAtom(dpy, b"_NET_SUPPORTING_WM_CHECK", 0) + root = X11.XDefaultRootWindow(dpy) + + def has_wm_check(): + da = ctypes.c_ulong() + di = ctypes.c_int() + n = ctypes.c_ulong() + dl = ctypes.c_ulong() + prop = ctypes.POINTER(ctypes.c_ubyte)() + rc = X11.XGetWindowProperty( + dpy, root, wm_atom, 0, 1, 0, 0, + ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop), + ) + ok = (rc == 0 and bool(prop) and n.value > 0) + if prop: + X11.XFree(prop) + return ok + + assert wait_until(has_wm_check, timeout=5.0), "dwm did not advertise _NET_SUPPORTING_WM_CHECK" + time.sleep(0.3) + assert not os.path.exists(m_exec), "dwm initial start must not run anode-autostart reload" + assert not os.path.exists(m_always), "dwm initial start must not run anode-autostart reload" + + # Trigger SIGHUP live restart twice and verify only exec_always runs each time + os.kill(dwm.pid, signal.SIGHUP) + assert wait_until( + lambda: os.path.exists(m_always) and len(open(m_always, encoding="utf-8").read().splitlines()) >= 1, + timeout=5.0, + ), "dwm SIGHUP restart did not invoke anode-autostart reload" + assert wait_until(has_wm_check, timeout=3.0) and dwm.poll() is None, "dwm died after SIGHUP restart" + + os.kill(dwm.pid, signal.SIGHUP) + assert wait_until( + lambda: os.path.exists(m_always) and len(open(m_always, encoding="utf-8").read().splitlines()) >= 2, + timeout=5.0, + ), "second dwm SIGHUP restart did not invoke anode-autostart reload" + + time.sleep(0.25) + assert not os.path.exists(m_exec), "dwm SIGHUP reload must not run exec directives" + with open(m_always, "r", encoding="utf-8") as f: + assert len(f.read().splitlines()) == 2 + finally: + if dpy: + X11.XCloseDisplay(dpy) + terminate(dwm) + terminate(xvfb) + + +if __name__ == "__main__": + test_directives_includes_once_and_reload() + test_profiles() + test_dropins_desktop_filters_and_xdg_masking() + test_check_errors() + test_dwm_sighup_reload_xvfb() + print("test_autostart: OK") diff --git a/tests/test_posix_make.py b/tests/test_posix_make.py index 4fe4fb5..a0a19c3 100755 --- a/tests/test_posix_make.py +++ b/tests/test_posix_make.py @@ -55,6 +55,7 @@ def check_scripts() -> None: "scripts/anode-sync-gtk-theme", "scripts/anode-sync-dunst-theme", "scripts/anode-session", + "scripts/anode-autostart", "scripts/anode-launcher", "data/env.sh", "src/dmenu/dmenu_path",