diff --git a/Makefile b/Makefile index e92ca36..7e92130 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,7 @@ CC = cc CXX = c++ PKG_CONFIG = pkg-config WITH_GTKTTK = auto +WITH_TOUCHD = 0 CFLAGS = -O2 CXXFLAGS = -O2 LDFLAGS = @@ -22,7 +23,34 @@ ST_VERSION = 0.9.2-anode COMMON_CFLAGS = -std=c99 -Wall -Wextra -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" -all: dwm dmenu st libgemui apps vkbd daemons gtkttk-auto +all: dwm dmenu st libgemui apps vkbd daemons touchd-opt gtkttk-auto + @_td="disabled (opt-in WITH_TOUCHD=1 or install-touch)"; \ + if [ "$(WITH_TOUCHD)" = "1" ]; then _td="enabled"; fi; \ + printf 'ANODE build ready (PREFIX=%s, touchd=%s). Run "make help" for options.\n' "$(PREFIX)" "$$_td" + +help: + @printf 'ANODE build & install targets:\n' + @printf ' make Build ANODE (without anode-touchd; anode-vkbd included)\n' + @printf ' make rebuild Clean and rebuild from scratch\n' + @printf ' make touchd Build opt-in touchscreen daemon (anode-touchd)\n' + @printf ' make test Build and run full test suite (needs Python 3 & Xvfb)\n' + @printf ' make clean Remove build/ directory\n' + @printf ' sudo make install Install to %s (for ~/.xinitrc, without anode-touchd)\n' "$(PREFIX)" + @printf ' sudo make install-system Install to %s + /usr/share/xsessions (LightDM/SDDM/GDM)\n' "$(PREFIX)" + @printf ' sudo make install-touch Install including opt-in touchscreen daemon (anode-touchd)\n' + @printf ' sudo make install-system-touch Display-manager install including anode-touchd\n' + @printf ' sudo make uninstall Remove installed files from PREFIX/XSESSIONSDIR\n' + @printf '\nOptions (override on command line, e.g. make rebuild WITH_TOUCHD=1):\n' + @printf ' PREFIX=%-25s Install prefix\n' "$(PREFIX)" + @printf ' XSESSIONSDIR=%-19s .desktop session file directory\n' "$(XSESSIONSDIR)" + @printf ' DESTDIR=%-24s Staging directory for packaging\n' "$(DESTDIR)" + @printf ' WITH_TOUCHD=%-20s 0=skip anode-touchd (default), 1=build/install anode-touchd\n' "$(WITH_TOUCHD)" + @printf ' WITH_GTKTTK=%-20s auto|1|0 for optional gtkTtk Tk theme library\n' "$(WITH_GTKTTK)" + @printf ' CC=%s CXX=%-18s Compilers (CFLAGS="%s", CXXFLAGS="%s")\n' "$(CC)" "$(CXX)" "$(CFLAGS)" "$(CXXFLAGS)" + +rebuild: + $(MAKE) clean + $(MAKE) WITH_TOUCHD="$(WITH_TOUCHD)" WITH_GTKTTK="$(WITH_GTKTTK)" PREFIX="$(PREFIX)" CC="$(CC)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" all build/flags.sh: scripts/detect-env.sh CC="$(CC)" CXX="$(CXX)" PKG_CONFIG="$(PKG_CONFIG)" WITH_GTKTTK="$(WITH_GTKTTK)" sh scripts/detect-env.sh build/flags.sh @@ -40,7 +68,7 @@ build/dwm/drw.o: src/dwm/drw.c src/dwm/drw.h src/dwm/util.h build/flags.sh build/dwm/util.o: src/dwm/util.c src/dwm/util.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L -c src/dwm/util.c -o build/dwm/util.o -build/dwm/dwm.o: src/dwm/dwm.c src/dwm/config.h src/dwm/drw.h src/dwm/util.h src/common/anode_scale.h build/flags.sh +build/dwm/dwm.o: src/dwm/dwm.c src/dwm/config.h src/dwm/drw.h src/dwm/util.h src/common/anode_scale.h src/common/anode_bar_fmt.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -Wno-deprecated-declarations -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L -DXINERAMA -DVERSION="\"$(DWM_VERSION)\"" -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$DWM_CFLAGS -c src/dwm/dwm.c -o build/dwm/dwm.o build/dwm/dwm: build/dwm/dwm.o build/dwm/drw.o build/dwm/util.o build/flags.sh @@ -111,7 +139,7 @@ build/apps/anode-audio.o: src/apps/anode-audio.c src/libgemui/gemui.h src/common build/apps/anode-audio: build/apps/anode-audio.o build/libgemui/libgemui.so build/common/anode_plat.o build/flags.sh . ./build/flags.sh && $(CC) -o build/apps/anode-audio build/apps/anode-audio.o build/common/anode_plat.o -Lbuild/libgemui -Wl,-rpath,$(PREFIX)/lib -lgemui $(LDFLAGS) $$APP_LIBS -build/apps/anode-display.o: src/apps/anode-display.c src/libgemui/gemui.h src/common/anode_plat.h src/common/anode_scale.h build/flags.sh +build/apps/anode-display.o: src/apps/anode-display.c src/libgemui/gemui.h src/common/anode_plat.h src/common/anode_scale.h src/common/anode_display_cfg.h src/common/anode_power_policy.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/libgemui -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$APP_CFLAGS -c src/apps/anode-display.c -o build/apps/anode-display.o build/apps/anode-display: build/apps/anode-display.o build/libgemui/libgemui.so build/common/anode_plat.o build/flags.sh @@ -123,13 +151,13 @@ build/apps/anode-datetime.o: src/apps/anode-datetime.c src/libgemui/gemui.h src/ build/apps/anode-datetime: build/apps/anode-datetime.o build/libgemui/libgemui.so build/common/anode_plat.o build/flags.sh . ./build/flags.sh && $(CC) -o build/apps/anode-datetime build/apps/anode-datetime.o build/common/anode_plat.o -Lbuild/libgemui -Wl,-rpath,$(PREFIX)/lib -lgemui $(LDFLAGS) $$APP_LIBS -build/apps/anode-power.o: src/apps/anode-power.c src/libgemui/gemui.h src/common/anode_plat.h build/flags.sh +build/apps/anode-power.o: src/apps/anode-power.c src/libgemui/gemui.h src/common/anode_plat.h src/common/anode_power_policy.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/libgemui -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$APP_CFLAGS -c src/apps/anode-power.c -o build/apps/anode-power.o build/apps/anode-power: build/apps/anode-power.o build/libgemui/libgemui.so build/common/anode_plat.o build/flags.sh . ./build/flags.sh && $(CC) -o build/apps/anode-power build/apps/anode-power.o build/common/anode_plat.o -Lbuild/libgemui -Wl,-rpath,$(PREFIX)/lib -lgemui $(LDFLAGS) $$APP_LIBS -build/apps/anode-themes.o: src/apps/anode-themes.c src/libgemui/gemui.h src/common/anode_plat.h build/flags.sh +build/apps/anode-themes.o: src/apps/anode-themes.c src/libgemui/gemui.h src/common/anode_plat.h src/common/anode_xth.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/libgemui -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$APP_CFLAGS -c src/apps/anode-themes.c -o build/apps/anode-themes.o build/apps/anode-themes: build/apps/anode-themes.o build/libgemui/libgemui.so build/common/anode_plat.o build/flags.sh @@ -154,7 +182,12 @@ build/apps/anode-vkbd: build/apps/anode-vkbd.o build/libgemui/libgemui.so build/ . ./build/flags.sh && $(CC) -o build/apps/anode-vkbd build/apps/anode-vkbd.o build/common/anode_plat.o -Lbuild/libgemui -Wl,-rpath,$(PREFIX)/lib -lgemui $(LDFLAGS) $$APP_LIBS # --- Zero-poll Daemons & Privilege Helpers --- -daemons: build/daemons/anode-statusd build/daemons/anode-touchd build/daemons/anode-powerd build/daemons/anode-power-ctl build/daemons/anode-dnsctl build/daemons/anode-tzctl build/daemons/anode-checkpw +daemons: build/daemons/anode-statusd build/daemons/anode-powerd build/daemons/anode-power-ctl build/daemons/anode-dnsctl build/daemons/anode-tzctl build/daemons/anode-checkpw + +touchd-opt: build/flags.sh + if [ "$(WITH_TOUCHD)" = "1" ]; then $(MAKE) touchd; fi + +touchd: build/daemons/anode-touchd build/daemons/anode-statusd.o: src/daemons/anode-statusd.c src/common/anode_plat.h src/common/anode_sys_parse.h src/common/anode_tz_valid.h src/common/anode_xkb_parse.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$STATUSD_CFLAGS -c src/daemons/anode-statusd.c -o build/daemons/anode-statusd.o @@ -171,7 +204,7 @@ build/daemons/anode-touchd.o: src/daemons/anode-touchd.c src/daemons/anode-touch build/daemons/anode-touchd: build/daemons/anode-touchd.o build/daemons/anode-touch-gesture.o build/flags.sh . ./build/flags.sh && $(CC) -o build/daemons/anode-touchd build/daemons/anode-touchd.o build/daemons/anode-touch-gesture.o $(LDFLAGS) $$TOUCHD_LIBS -build/daemons/anode-powerd.o: src/daemons/anode-powerd.c src/common/anode_plat.h build/flags.sh +build/daemons/anode-powerd.o: src/daemons/anode-powerd.c src/common/anode_plat.h src/common/anode_power_policy.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$POWERD_CFLAGS -c src/daemons/anode-powerd.c -o build/daemons/anode-powerd.o build/daemons/anode-powerd: build/daemons/anode-powerd.o build/common/anode_plat.o build/flags.sh @@ -308,11 +341,16 @@ install: all build/apps/anode-datetime build/apps/anode-power build/apps/anode-themes \ build/apps/anode-lock build/apps/anode-media-key build/apps/anode-vkbd \ "$(DESTDIR)$(PREFIX)/bin/" - cp -f build/daemons/anode-statusd build/daemons/anode-touchd build/daemons/anode-powerd \ + cp -f build/daemons/anode-statusd build/daemons/anode-powerd \ build/daemons/anode-power-ctl build/daemons/anode-dnsctl build/daemons/anode-tzctl \ build/daemons/anode-checkpw "$(DESTDIR)$(PREFIX)/bin/" + if [ "$(WITH_TOUCHD)" = "1" ]; then \ + if [ ! -f build/daemons/anode-touchd ]; then $(MAKE) touchd; fi; \ + cp -f build/daemons/anode-touchd "$(DESTDIR)$(PREFIX)/bin/anode-touchd"; \ + chmod 755 "$(DESTDIR)$(PREFIX)/bin/anode-touchd"; \ + fi cp -f scripts/anode-session scripts/anode-replace scripts/anode-autostart scripts/anode-launcher scripts/anode-apply-theme \ - scripts/anode-apply-scale scripts/anode-sync-gtk-theme scripts/anode-sync-dunst-theme \ + scripts/anode-apply-scale scripts/anode-apply-display scripts/anode-sync-gtk-theme scripts/anode-sync-dunst-theme \ "$(DESTDIR)$(PREFIX)/bin/" chmod 755 \ "$(DESTDIR)$(PREFIX)/bin/dwm" "$(DESTDIR)$(PREFIX)/bin/dmenu" \ @@ -323,13 +361,14 @@ install: all "$(DESTDIR)$(PREFIX)/bin/anode-power" "$(DESTDIR)$(PREFIX)/bin/anode-themes" \ "$(DESTDIR)$(PREFIX)/bin/anode-lock" "$(DESTDIR)$(PREFIX)/bin/anode-media-key" \ "$(DESTDIR)$(PREFIX)/bin/anode-vkbd" "$(DESTDIR)$(PREFIX)/bin/anode-statusd" \ - "$(DESTDIR)$(PREFIX)/bin/anode-touchd" "$(DESTDIR)$(PREFIX)/bin/anode-powerd" \ + "$(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-replace" \ "$(DESTDIR)$(PREFIX)/bin/anode-autostart" "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ "$(DESTDIR)$(PREFIX)/bin/anode-apply-theme" "$(DESTDIR)$(PREFIX)/bin/anode-apply-scale" \ - "$(DESTDIR)$(PREFIX)/bin/anode-sync-gtk-theme" "$(DESTDIR)$(PREFIX)/bin/anode-sync-dunst-theme" + "$(DESTDIR)$(PREFIX)/bin/anode-apply-display" "$(DESTDIR)$(PREFIX)/bin/anode-sync-gtk-theme" \ + "$(DESTDIR)$(PREFIX)/bin/anode-sync-dunst-theme" if [ "`id -u`" = "0" ] && [ -z "$(DESTDIR)" ]; then chmod 4755 "$(PREFIX)/bin/anode-checkpw" 2>/dev/null || true; fi cp -f build/libgemui/libgemui.so "$(DESTDIR)$(PREFIX)/lib/libgemui.so" chmod 755 "$(DESTDIR)$(PREFIX)/lib/libgemui.so" @@ -337,6 +376,7 @@ install: all chmod 644 "$(DESTDIR)$(PREFIX)/include/gemui.h" cp -f build/libgemui/gemui.pc "$(DESTDIR)$(PREFIX)/lib/pkgconfig/gemui.pc" chmod 644 "$(DESTDIR)$(PREFIX)/lib/pkgconfig/gemui.pc" + rm -f "$(DESTDIR)$(PREFIX)/share/anode/themes/AnodeDefault.xth" cp -f data/themes/*.xth "$(DESTDIR)$(PREFIX)/share/anode/themes/" chmod 644 "$(DESTDIR)$(PREFIX)/share/anode/themes/"*.xth cp -f data/env.sh "$(DESTDIR)$(PREFIX)/share/anode/env.sh" @@ -360,6 +400,20 @@ install: all chmod 755 "$(DESTDIR)$(PREFIX)/lib/gtkTtk0.9/libgtkTtk0.9.so"; \ chmod 644 "$(DESTDIR)$(PREFIX)/lib/gtkTtk0.9/gtkTtk.tcl" "$(DESTDIR)$(PREFIX)/lib/gtkTtk0.9/pkgIndex.tcl"; \ fi + @_td="disabled (opt-in WITH_TOUCHD=1 or install-touch)"; \ + _gtk="skipped"; \ + if [ "$(WITH_TOUCHD)" = "1" ]; then _td="installed"; fi; \ + if [ -f build/gtkTtk/libgtkTtk0.9.so ]; then _gtk="installed"; fi; \ + printf 'ANODE installed (PREFIX=%s, XSESSIONSDIR=%s, touchd=%s, gtkTtk=%s).\n' "$(DESTDIR)$(PREFIX)" "$(DESTDIR)$(XSESSIONSDIR)" "$$_td" "$$_gtk" + +install-touch: + $(MAKE) WITH_TOUCHD=1 WITH_GTKTTK="$(WITH_GTKTTK)" PREFIX="$(PREFIX)" MANPREFIX="$(MANPREFIX)" XSESSIONSDIR="$(XSESSIONSDIR)" DESTDIR="$(DESTDIR)" CC="$(CC)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" install + +install-system: + $(MAKE) WITH_TOUCHD="$(WITH_TOUCHD)" WITH_GTKTTK="$(WITH_GTKTTK)" PREFIX="$(PREFIX)" MANPREFIX="$(MANPREFIX)" XSESSIONSDIR=/usr/share/xsessions DESTDIR="$(DESTDIR)" CC="$(CC)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" install + +install-system-touch: + $(MAKE) WITH_TOUCHD=1 WITH_GTKTTK="$(WITH_GTKTTK)" PREFIX="$(PREFIX)" MANPREFIX="$(MANPREFIX)" XSESSIONSDIR=/usr/share/xsessions DESTDIR="$(DESTDIR)" CC="$(CC)" CXX="$(CXX)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" install uninstall: rm -f \ @@ -391,6 +445,7 @@ uninstall: "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ "$(DESTDIR)$(PREFIX)/bin/anode-apply-theme" \ "$(DESTDIR)$(PREFIX)/bin/anode-apply-scale" \ + "$(DESTDIR)$(PREFIX)/bin/anode-apply-display" \ "$(DESTDIR)$(PREFIX)/bin/anode-sync-gtk-theme" \ "$(DESTDIR)$(PREFIX)/bin/anode-sync-dunst-theme" \ "$(DESTDIR)$(PREFIX)/lib/libgemui.so" \ @@ -407,7 +462,7 @@ clean: rm -rf build # --- Tests --- -build/tests/test_units: tests/test_units.c src/daemons/anode-touch-gesture.c src/common/anode_plat.c src/common/anode_xkb_parse.h src/common/anode_sys_parse.h build/flags.sh +build/tests/test_units: tests/test_units.c src/daemons/anode-touch-gesture.c src/common/anode_plat.c src/common/anode_xkb_parse.h src/common/anode_sys_parse.h src/common/anode_xth.h src/common/anode_display_cfg.h src/common/anode_power_policy.h src/common/anode_bar_fmt.h build/flags.sh . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -Isrc/daemons -DANODE_PREFIX="\"$(PREFIX)\"" $$TOUCHD_CFLAGS -o build/tests/test_units tests/test_units.c src/daemons/anode-touch-gesture.c src/common/anode_plat.c -lm test: all build/tests/test_units @@ -419,4 +474,4 @@ test: all build/tests/test_units python3 tests/test_x11_xvfb.py python3 tests/test_replace.py -.PHONY: all dwm dmenu st libgemui apps vkbd daemons gtkttk gtkttk-auto install uninstall clean test +.PHONY: all help rebuild dwm dmenu st libgemui apps vkbd daemons touchd touchd-opt gtkttk gtkttk-auto install install-touch install-system install-system-touch uninstall clean test diff --git a/README.md b/README.md index 255f551..6d45a11 100644 --- a/README.md +++ b/README.md @@ -9,20 +9,21 @@ ANODE is a lightweight, keyboard-first X11 desktop environment for **Linux, Free ## What's included - **Window manager, launcher & terminal**: A customized `dwm` setup with workspace layouts, a clickable status bar, and an XEmbed system tray, paired with `dmenu`, the `anode-launcher` desktop/Flatpak app menu, and the `st` terminal featuring `Fira Code` ligatures. -- **Unified themes & fonts**: 22 built-in themes (`data/themes/*.xth`) synced across ANODE, GTK 2/3/4, Qt 5/6, Electron/Chromium apps, Tk (`gtkTtk`), and Dunst notifications — keeping ANODE tools and monospace slots on `Fira Code` while giving third-party apps `Roboto` (or `Noto Sans` when unavailable). -- **Fractional DPI scaling**: Scale cleanly from `0.50x` to `4.00x` (or `auto` from monitor EDID/DPI) across X11, fonts, cursors, GTK, Qt, and Electron/Chromium without double-scaling. -- **Built-in desktop utilities**: Fast native panels for power & control center (`anode-power`), Wi-Fi/Bluetooth/DNS (`anode-net`), audio (`anode-audio`), displays & scaling (`anode-display`), date & timezone (`anode-datetime`), themes (`anode-themes`), screen locking (`anode-lock`), multimedia keys (`anode-media-key`), and an optional touch keyboard (`anode-vkbd`) with edge-swipe gestures (`anode-touchd`). +- **Unified themes & fonts**: 22 built-in themes (`data/themes/*.xth`, defaulting to dark-silvery `Anodized`) synced across ANODE, GTK 2/3/4, Qt 5/6, Electron/Chromium apps, Tk (`gtkTtk`), and Dunst notifications — keeping ANODE tools and monospace slots on `Fira Code` while giving third-party apps `Roboto` (or `Noto Sans` when unavailable) — plus a built-in theme editor, duplicator, and `.xth` importer in `anode-themes`. +- **Fractional DPI scaling & multi-monitor arrangement**: Scale cleanly from `0.50x` to `4.00x` (or `auto` from primary monitor EDID/DPI) across X11, fonts, cursors, GTK, Qt, and Electron/Chromium without double-scaling, alongside an interactive monitor arrangement dialog with 15 s safety revert and persistent `$XDG_CONFIG_HOME/anode/displays.conf` layouts (`anode-apply-display`). +- **Built-in desktop utilities**: Fast native panels for power, idle/screen timeouts & control center (`anode-power`), Wi-Fi/Bluetooth/DNS (`anode-net`), audio (`anode-audio`), displays, arrangement, timeouts & scaling (`anode-display`), date & timezone (`anode-datetime`), themes & editor (`anode-themes`), screen locking (`anode-lock`), multimedia keys (`anode-media-key`), on-screen virtual keyboard (`anode-vkbd`), and opt-in touchscreen edge gestures (`anode-touchd`). - **Session autostart & live switching**: Familiar i3-style autostart config (`~/.config/anode/autostart`), session profiles, XDG autostart entries, and safe session switching via `anode-replace`. ## Build & install ```sh -make -sudo make XSESSIONSDIR=/usr/share/xsessions install +make # Build ANODE (or 'make rebuild' for a clean rebuild) +sudo make install-system # Install to /usr/local + /usr/share/xsessions (LightDM/SDDM/GDM) ``` -- Pass `PREFIX=/opt/anode`, `CC=clang`, or `WITH_GTKTTK=1` to customize the build (`WITH_GTKTTK=auto` is enabled by default). -- Omit `XSESSIONSDIR=...` if you launch from `~/.xinitrc` (`exec /usr/local/bin/anode-session`) instead of a system display manager like LightDM. +- **Minimal `~/.xinitrc` install** (`exec /usr/local/bin/anode-session`): use `sudo make install` instead of `install-system`. +- **Touchscreen hardware opt-in (`anode-touchd`)**: use `sudo make install-system-touch` or `sudo make install-touch` (or pass `WITH_TOUCHD=1` to `make` / `make rebuild` / `make install`; `anode-vkbd` is always installed). +- **Custom options & help**: run `make help` to see all targets and variables (`PREFIX=/opt/anode`, `XSESSIONSDIR=...`, `DESTDIR=...`, `CC=clang`, `WITH_TOUCHD=1`, `WITH_GTKTTK=0`). - To switch from an existing X11 session, run `anode-replace` (or `anode-replace --switch-session` under a display manager). Pass `--profile NAME` to `anode-session` or `anode-replace` to enable profile-specific autostart rules. ## Everyday shortcuts & commands @@ -34,18 +35,21 @@ Default modifier key is `Super` (`Mod4`). | `Super + Return` | Open terminal (`st`) | | `Super + p` / `Super + Space` | Open application & Flatpak launcher (`anode-launcher`) | | `Super + c` | Open control center & power (`anode-power`) | -| `Super + d` | Open display & scaling settings (`anode-display`) | -| `Super + t` | Open theme & font switcher (`anode-themes`) | +| `Super + d` | Open monitor arrangement, display & scaling settings (`anode-display`) | +| `Super + t` | Open theme selector, editor & `.xth` importer (`anode-themes`) | | `Super + n` | Open network, Wi-Fi & Bluetooth settings (`anode-net`) | | `Super + a` | Open audio mixer & profiles (`anode-audio`) | +| `Super + w` | Open date & timezone panel (`anode-datetime`) | | `Super + Shift + l` | Lock screen (`anode-lock`) | | `Super + Shift + r` | Reload `.Xresources`, theme, scale, and `exec_always` autostart entries | -Themes and display scaling can also be changed from the command line: +Themes, monitor layouts, and display scaling can also be managed from the command line: ```sh anode-apply-theme LynxLair +anode-apply-theme --install /path/to/CustomTheme.xth anode-apply-scale 1.50 +anode-display --arrange ``` See [docs/KEYBINDINGS.md](docs/KEYBINDINGS.md) for all window management bindings, media keys, and touchscreen edge gestures. diff --git a/data/themes/AnodeDefault.xth b/data/themes/AnodeDefault.xth deleted file mode 100644 index 152dc54..0000000 --- a/data/themes/AnodeDefault.xth +++ /dev/null @@ -1,87 +0,0 @@ -! ANODE unified .xth theme: AnodeDefault (Dark, crisp blue/cyan accents, Fira Code + Nerd Fonts) -theme.name: AnodeDefault -theme.isDark: 1 -theme.fontFace: Fira Code -theme.uiFontFace: Roboto -theme.iconFontFace: DejaVuSansM Nerd Font -theme.baseFontSize: 15 -theme.gtkTheme: Anode-AnodeDefault -theme.qtTheme: Fusion -theme.iconTheme: Adwaita -*TkTheme: gtkTtk - -Xft.dpi: 96 -Xft.antialias: 1 -Xft.hinting: 1 -Xft.hintstyle: hintslight -Xft.rgba: rgb -Xcursor.size: 24 - -theme.bgMain: #0b0e14 -theme.bgBar: #11161f -theme.bgHeader: #141a24 -theme.bgFooter: #0f141d -theme.bgOverlay: #192231 -theme.bgAltEven: #131923 -theme.bgAltOdd: #171f2b -theme.bgInput: #1a2330 -theme.bgInputFocus: #202c3d -theme.bgButton: #1e2838 -theme.bgSearch: #1b2433 -theme.bgBubbleIn: #1d2736 -theme.bgBubbleOut: #1c3a57 -theme.bgToast: #1d2a3d -theme.fgMain: #e6e1cf -theme.fgBright: #ffffff -theme.fgMuted: #8693a6 -theme.selBg: #2b5278 -theme.selFg: #ffffff -theme.accent: #59c2ff -theme.accentAlt: #73d0ff -theme.highlight: #ffd173 -theme.border: #283444 -theme.divider: #1e2736 -theme.success: #7fd962 -theme.info: #59c2ff -theme.warning: #ffb454 -theme.danger: #f07178 -theme.dangerBg: #471d24 - -dwm.borderpx: 2 -dwm.font: Fira Code, DejaVuSansM Nerd Font 15px -dwm.normbgcolor: #11161f -dwm.normfgcolor: #e6e1cf -dwm.normbordercolor: #283444 -dwm.selbgcolor: #2b5278 -dwm.selfgcolor: #ffffff -dwm.selbordercolor: #59c2ff - -dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px -dmenu.background: #141a24 -dmenu.foreground: #e6e1cf -dmenu.selbackground: #2b5278 -dmenu.selforeground: #ffffff -dmenu.outbackground: #1b2433 -dmenu.outforeground: #73d0ff - -st.font: Fira Code:size=13:style=Regular:antialias=true:autohint=true -st.background: #0b0e14 -st.foreground: #e6e1cf -st.cursorColor: #59c2ff -st.revCursorColor: #0b0e14 -st.color0: #0b0e14 -st.color1: #f07178 -st.color2: #7fd962 -st.color3: #ffb454 -st.color4: #59c2ff -st.color5: #d2a6ff -st.color6: #95e6cb -st.color7: #e6e1cf -st.color8: #5c6773 -st.color9: #ff8f96 -st.color10: #9be87e -st.color11: #ffd173 -st.color12: #73d0ff -st.color13: #dfbfff -st.color14: #b0f2de -st.color15: #ffffff diff --git a/data/themes/Anodized.xth b/data/themes/Anodized.xth new file mode 100644 index 0000000..1e65ca1 --- /dev/null +++ b/data/themes/Anodized.xth @@ -0,0 +1,87 @@ +! ANODE unified .xth theme: Anodized (Obsidian & brushed silver, brass-amber highlight, Fira Code + Nerd Fonts) +theme.name: Anodized +theme.isDark: 1 +theme.fontFace: Fira Code +theme.uiFontFace: Roboto +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 +theme.gtkTheme: Anode-Anodized +theme.qtTheme: Fusion +theme.iconTheme: Adwaita +*TkTheme: gtkTtk + +Xft.dpi: 96 +Xft.antialias: 1 +Xft.hinting: 1 +Xft.hintstyle: hintslight +Xft.rgba: rgb +Xcursor.size: 24 + +theme.bgMain: #08090b +theme.bgBar: #0e1014 +theme.bgHeader: #12151a +theme.bgFooter: #0b0d11 +theme.bgOverlay: #171b22 +theme.bgAltEven: #101318 +theme.bgAltOdd: #14181f +theme.bgInput: #161a21 +theme.bgInputFocus: #1e232c +theme.bgButton: #1c212a +theme.bgSearch: #191e27 +theme.bgBubbleIn: #181d25 +theme.bgBubbleOut: #252c38 +theme.bgToast: #1c222b +theme.fgMain: #e4e8ee +theme.fgBright: #f5f7fa +theme.fgMuted: #89929f +theme.selBg: #38414f +theme.selFg: #f5f7fa +theme.accent: #cfd6e0 +theme.accentAlt: #e5eaf0 +theme.highlight: #e2bc72 +theme.border: #2d3440 +theme.divider: #20252f +theme.success: #79cf9c +theme.info: #9eb3c8 +theme.warning: #e2bc72 +theme.danger: #e07a7a +theme.dangerBg: #3f1d20 + +dwm.borderpx: 2 +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.normbgcolor: #0e1014 +dwm.normfgcolor: #e4e8ee +dwm.normbordercolor: #2d3440 +dwm.selbgcolor: #38414f +dwm.selfgcolor: #f5f7fa +dwm.selbordercolor: #cfd6e0 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #12151a +dmenu.foreground: #e4e8ee +dmenu.selbackground: #38414f +dmenu.selforeground: #f5f7fa +dmenu.outbackground: #191e27 +dmenu.outforeground: #cfd6e0 + +st.font: Fira Code:size=13:style=Regular:antialias=true:autohint=true +st.background: #08090b +st.foreground: #e4e8ee +st.cursorColor: #cfd6e0 +st.revCursorColor: #08090b +st.color0: #08090b +st.color1: #d97878 +st.color2: #79cf9c +st.color3: #e2bc72 +st.color4: #8ba6c4 +st.color5: #b39bc8 +st.color6: #84b8be +st.color7: #d5dce4 +st.color8: #5b6370 +st.color9: #eb9494 +st.color10: #96deb3 +st.color11: #edd092 +st.color12: #a6bdd6 +st.color13: #cab5dc +st.color14: #a2cdd2 +st.color15: #f5f7fa diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cf9178d..2081b5a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -3,13 +3,13 @@ ## Component map - `Makefile` & `scripts/detect-env.sh`: Strict `.POSIX:` single build orchestration probing OS headers, `-lcrypt` vs ``, `-lrt`, `-lutil`, `XScrnSaver`, and optional `gtk+-2.0`/`tcl`/`tk` headers cleanly into `build/flags.sh`. -- `src/common/`: Cross-Unix platform layer (`anode_plat.c`, `anode_plat.h`), `.Xresources` / EDID fractional scale helpers (`anode_scale.h`), CPU/memory parsers (`anode_sys_parse.h`), input validators (`anode_dns_valid.h`, `anode_tz_valid.h`), XKB layout parser (`anode_xkb_parse.h`), CLI output parsers (`anode_audio_parse.h`, `anode_wifi_list.h`, `anode_bt_list.h`), and power policy (`anode_power_policy.h`). -- `src/dwm/`, `src/dmenu/`, `src/st/`: Patched suckless X11 core using Pango/HarfBuzz (`Fira Code` ligatures), vector 3-bar hamburger launcher button in `dwm`, full-height `-l 0` mode in `dmenu`, `St.font` + live `Xft.dpi` Fontconfig resolution in `st`, `.Xresources` + `SIGUSR1` live reload, `anode_scale.h`, ICCCM `WM_S` `--replace` handoff (`exit 75` when yielded so `anode-session` holds the session), and `ANODE WM` EWMH identity. -- `src/libgemui/`: Shared library `libgemui.so` + `gemui.pc` providing double-buffered Cairo + Pango rendering (`theme.fontFace` `Fira Code` + `theme.iconFontFace` Nerd Font fallback), workarea-clamped responsive window sizing, `fullscreen_override` stacking guard (`VisibilityNotify`/`MapNotify`/`ConfigureNotify`) keeping `anode-lock` above the systray/bar while permitting `anode-vkbd`, hit tracking, touch-mode sizing (`gemui_touch_row_px`), self-pipe `SIGUSR1` + root `XA_RESOURCE_MANAGER` live reload, and non-blocking `poll()` loops. -- `src/apps/`: Desktop control panels and optional dock virtual keyboard (`anode-vkbd`) + multimedia dispatcher (`anode-media-key`). -- `src/daemons/`: Event-driven `poll()` + signal self-pipe daemons (`anode-statusd`, `anode-touchd`, `anode-powerd` with `power.conf` idle overrides) and narrowly-scoped privilege helpers (`anode-power-ctl`, `anode-dnsctl`, `anode-tzctl`, `anode-checkpw` with `/sbin/unix_chkpwd` fallback). +- `src/common/`: Cross-Unix platform layer (`anode_plat.c`, `anode_plat.h`), `.Xresources` / EDID fractional scale helpers (`anode_scale.h`), unified `.xth` theme parser/editor model (`anode_xth.h`), multi-monitor arrangement/profile helpers (`anode_display_cfg.h`), CPU/memory parsers (`anode_sys_parse.h`), input validators (`anode_dns_valid.h`, `anode_tz_valid.h`), XKB layout parser (`anode_xkb_parse.h`), CLI output parsers (`anode_audio_parse.h`, `anode_wifi_list.h`, `anode_bt_list.h`), and power policy (`anode_power_policy.h`). +- `src/dwm/`, `src/dmenu/`, `src/st/`: Patched suckless X11 core using Pango/HarfBuzz (`Fira Code` ligatures), dark-silvery `Anodized` compile-time fallback palette, vector 3-bar hamburger launcher button in `dwm`, XRandR + Xinerama primary-first monitor ordering and unplug client rescue in `dwm`, full-height `-l 0` mode in `dmenu`, `St.font` + live `Xft.dpi` Fontconfig resolution in `st`, `.Xresources` + `SIGUSR1` live reload, `anode_scale.h`, ICCCM `WM_S` `--replace` handoff (`exit 75` when yielded so `anode-session` holds the session), and `ANODE WM` EWMH identity. +- `src/libgemui/`: Shared library `libgemui.so` + `gemui.pc` providing double-buffered Cairo + Pango rendering (`theme.fontFace` `Fira Code` + `theme.iconFontFace` Nerd Font fallback), automatic luminance-aware dark/light button text contrast, workarea-clamped responsive window sizing, full virtual-root spanning + primary monitor alignment (`gemui_primary_monitor_rect`) + RandR resize tracking and stacking guard (`VisibilityNotify`/`MapNotify`/`ConfigureNotify`) keeping `anode-lock` over all displays while permitting `anode-vkbd`, X11 clipboard paste (`gemui_clipboard_get`), hit tracking, touch-mode sizing (`gemui_touch_row_px`), self-pipe `SIGUSR1` + root `XA_RESOURCE_MANAGER` live reload, and non-blocking `poll()` loops. +- `src/apps/`: Desktop control panels (including the integrated `anode-themes` editor/`.xth` importer and `anode-display` multi-monitor 2D arrangement canvas with 15 s revert), monitor-scoped dock virtual keyboard (`anode-vkbd`), and multimedia dispatcher (`anode-media-key`). +- `src/daemons/`: Event-driven `poll()` + signal self-pipe daemons (`anode-statusd`, `anode-powerd` with `power.conf` idle overrides, plus opt-in `anode-touchd` built/installed only when `WITH_TOUCHD=1`) and narrowly-scoped privilege helpers (`anode-power-ctl`, `anode-dnsctl`, `anode-tzctl`, `anode-checkpw` with `/sbin/unix_chkpwd` fallback). - `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, `data/env.sh` XDG/Flatpak `XDG_DATA_DIRS` normalization, full-XDG `anode-launcher`, strict POSIX `/bin/sh` synchronization scripts, live session replacement (`anode-replace`), and i3-style session autostart management (`anode-autostart` + `data/autostart` template). +- `data/` & `scripts/`: 22 96-DPI `.xth` themes (defaulting to dark-silvery `Anodized.xth`, with deprecated `AnodeDefault` seamlessly falling back to `Anodized`), `data/env.sh` XDG/Flatpak `XDG_DATA_DIRS` normalization, full-XDG `anode-launcher`, strict POSIX `/bin/sh` synchronization scripts (including `anode-apply-display` for saved `$XDG_CONFIG_HOME/anode/displays.conf` layouts), live session replacement (`anode-replace`), and i3-style session autostart management (`anode-autostart` + `data/autostart` template). ## Fractional DPI multi-toolkit contract diff --git a/docs/KEYBINDINGS.md b/docs/KEYBINDINGS.md index 03ac7c7..a096f70 100644 --- a/docs/KEYBINDINGS.md +++ b/docs/KEYBINDINGS.md @@ -34,9 +34,9 @@ Default `MODKEY` is `Mod4` (`Super` / `Win`). | `Mod4 + c` / `XF86Tools` / `XF86PowerDown` | Control center & power (`anode-power`) | | `Mod4 + n` / `XF86WLAN` | Network, Wi-Fi, Bluetooth & DNS (`anode-net`) | | `Mod4 + a` / `XF86Option` | Audio mixer & profiles (`anode-audio`) | -| `Mod4 + d` | Display, XRandR & fractional scaling (`anode-display`) | +| `Mod4 + d` | Monitor arrangement, XRandR & fractional scaling (`anode-display`; `--arrange` opens Arrangement directly) | | `Mod4 + w` | Date & timezone (`anode-datetime`) | -| `Mod4 + t` | Themes & typography (`anode-themes`) | +| `Mod4 + t` | Theme selector, editor & `.xth` importer (`anode-themes`) | | `Mod4 + v` / `XF86Keyboard` | Toggle virtual keyboard (`anode-vkbd`) | | `Mod4 + Shift + l` / `XF86ScreenSaver` | Lock screen (`anode-lock`) | | `Print` / `Shift+Print` / `Ctrl+Print` | Root / focused window screenshot (`anode-media-key`) | @@ -49,6 +49,8 @@ Default `MODKEY` is `Mod4` (`Super` / `Win`). ## Edge touch gestures (`anode-touchd`) +Requires installing with `WITH_TOUCHD=1` (`make WITH_TOUCHD=1 && sudo make WITH_TOUCHD=1 install`). + | Swipe gesture | Action | |---|---| | Top edge swipe down | Launch `anode-launcher` | diff --git a/docs/SESSION.md b/docs/SESSION.md index e04e8db..620a95f 100644 --- a/docs/SESSION.md +++ b/docs/SESSION.md @@ -28,17 +28,17 @@ anode-replace --profile work --keep-panels - **Two-stage WM handoff**: 1. **ICCCM 2.0 `WM_S` takeover**: `dwm` claims `WM_S` on its check window and handles `SelectionClear` by cleanly unwinding (`replaced_by_other = 1; restart_dwm = 0; running = 0;`). When invoked with `--replace`, `dwm` acquires `WM_S`, broadcasts a root `MANAGER` `ClientMessage`, and polls `ConnectionNumber(dpy)` for up to 5 s until the previous owner destroys its selection window and releases `SubstructureRedirectMask`. 2. **Non-ICCCM fallback**: Before launching `anode-session --replace`, `anode-replace` records `_NET_WM_PID` (or UID-matched WM PID fallback) from `_NET_SUPPORTING_WM_CHECK`. If the previous window manager still holds `_NET_SUPPORTING_WM_CHECK` after 1.5 s and its PID belongs to the current UID (checked via POSIX `ps`), `anode-replace` sends `SIGTERM` so `dwm --replace` can take over `SubstructureRedirectMask`. -- **Process cleanup & detached readiness**: `anode-replace` terminates duplicate UID-owned ANODE daemons (`anode-statusd`, `anode-powerd`, `anode-touchd`, `anode-vkbd`) and, unless `--keep-panels` is given, stops conflicting third-party panels, notification daemons, and settings daemons (`xfce4-panel`, `mate-panel`, `lxpanel`, `i3bar`, `tint2`, `polybar`, `lemonbar`, `fbpanel`, `plank`, `wingpanel`, `dunst`, `xfce4-notifyd`, `xsettingsd`, `xfsettingsd`). By default it launches `anode-session --replace` immune to `SIGHUP` and waits up to 5 s for `ANODE WM` to advertise itself on `_NET_SUPPORTING_WM_CHECK`. +- **Process cleanup & detached readiness**: `anode-replace` terminates duplicate UID-owned ANODE daemons (`anode-statusd`, `anode-powerd`, `anode-touchd`, `anode-vkbd`) and, unless `--keep-panels` is given, stops conflicting third-party panels, notification daemons, and settings daemons (`xfce4-panel`, `mate-panel`, `lxpanel`, `i3bar`, `tint2`, `polybar`, `lemonbar`, `fbpanel`, `plank`, `wingpanel`, `dunst`, `xfce4-notifyd`, `xsettingsd`, `xfsettingsd`). By default it launches `anode-session --replace` immune to `SIGHUP` and waits up to 5 s for `ANODE WM` to advertise itself on `_NET_SUPPORTING_WM_CHECK`. `anode-touchd` is opt-in at build/install time (`WITH_TOUCHD=1`) and can also be skipped per session with `ANODE_NO_TOUCHD=1`. ## Desktop environment & window manager identity -- **EWMH & ICCCM properties**: `dwm` sets `_NET_WM_NAME = "ANODE WM"`, `XA_WM_NAME = "ANODE WM"`, `_NET_SUPPORTING_WM_CHECK`, and `_NET_WM_PID` on `wmcheckwin`, and sets `{"anode-wm", "ANODE"}` as the `XClassHint` on status bar windows. -- **Clean session environment**: Both `anode-session` and `anode-replace` unset stale third-party DE variables (`KDE_FULL_SESSION`, `KDE_SESSION_VERSION`, `KDE_SESSION_UID`, `GNOME_DESKTOP_SESSION_ID`, `MATE_DESKTOP_SESSION_ID`, `CINNAMON_VERSION`, `XFCE_SESSION`, `LXQT_SESSION_CONFIG`, `TDE_FULL_SESSION`, `HYPRLAND_INSTANCE_SIGNATURE`, `SWAYSOCK`, `I3SOCK`, `BSPWM_SOCKET`, `WINDOWMAKER`, `E_START`, `GDMSESSION`) as well as stale foreign `GTK_THEME` overrides unless `ANODE_KEEP_GTK_THEME=1`, export `XDG_CURRENT_DESKTOP=ANODE`, `XDG_SESSION_DESKTOP=anode`, `DESKTOP_SESSION=anode`, and `XDG_SESSION_TYPE=x11`, sync DE identity and `QT_QPA_PLATFORMTHEME=gtk3:qt6ct:qt5ct` to DBus/systemd user activation environments when available (unless `ANODE_NO_DBUS=1`), and `anode-session` refreshes generated GTK/Qt/Fontconfig/Dunst theme files via `anode-sync-gtk-theme` and `anode-sync-dunst-theme` on startup even when `~/.Xresources` already exists. +- **EWMH & ICCCM properties**: `dwm` sets `_NET_WM_NAME = "ANODE WM"`, `XA_WM_NAME = "ANODE WM"`, `_NET_SUPPORTING_WM_CHECK`, `_NET_WM_PID` on `wmcheckwin`, maintains workspace EWMH properties (`_NET_NUMBER_OF_DESKTOPS`, `_NET_CURRENT_DESKTOP`, `_NET_DESKTOP_NAMES`, `_NET_WM_DESKTOP`), and sets `{"anode-wm", "ANODE"}` as the `XClassHint` on status bar windows. Across `anode-replace` and in-place restarts, `dwm` snapshots and restores per-window workspaces, monitor assignments, floating/fullscreen states, monitor layouts, and focus for both ANODE sessions and third-party EWMH window managers. +- **Clean session environment**: Both `anode-session` and `anode-replace` unset stale third-party DE variables (`KDE_FULL_SESSION`, `KDE_SESSION_VERSION`, `KDE_SESSION_UID`, `GNOME_DESKTOP_SESSION_ID`, `MATE_DESKTOP_SESSION_ID`, `CINNAMON_VERSION`, `XFCE_SESSION`, `LXQT_SESSION_CONFIG`, `TDE_FULL_SESSION`, `HYPRLAND_INSTANCE_SIGNATURE`, `SWAYSOCK`, `I3SOCK`, `BSPWM_SOCKET`, `WINDOWMAKER`, `E_START`, `GDMSESSION`) as well as stale foreign `GTK_THEME` overrides unless `ANODE_KEEP_GTK_THEME=1`, export `XDG_CURRENT_DESKTOP=ANODE`, `XDG_SESSION_DESKTOP=anode`, `DESKTOP_SESSION=anode`, and `XDG_SESSION_TYPE=x11`, apply any saved per-output arrangement from `$XDG_CONFIG_HOME/anode/displays.conf` via `anode-apply-display`, sync DE identity and `QT_QPA_PLATFORMTHEME=gtk3:qt6ct:qt5ct` to DBus/systemd user activation environments when available (unless `ANODE_NO_DBUS=1`), and `anode-session` refreshes generated GTK/Qt/Fontconfig/Dunst theme files via `anode-sync-gtk-theme` and `anode-sync-dunst-theme` on startup (defaulting new installs to `Anodized`, with a deprecation fallback from removed `AnodeDefault`). - **System info reporting**: Tools such as `fastfetch` report `Desktop Environment: ANODE` and `Window Manager: ANODE WM (X11)` instead of `dwm`. Terminals that were already open before running `anode-replace` keep their earlier shell environment until a new terminal is launched or `export XDG_CURRENT_DESKTOP=ANODE` is run. ## Status bar & XKB layout indicator -- **Format**: `anode-statusd` publishes `VOL | CPU | RAM | | | YYYY-MM-DD HH:MM` (plus `VOL MUTE` when muted) to the X11 root `WM_NAME`. The `VOL` segment is omitted when no audio backend is detected, `CPU`/`RAM` use cross-Unix kernel telemetry (`/proc/stat` + `/proc/meminfo` on Linux, `sysctl` on FreeBSD/OpenBSD/NetBSD), and `` is omitted cleanly if XKB is unavailable. +- **Format**: `anode-statusd` publishes `VOL | CPU | RAM | | | YYYY-MM-DD HH:MM` (plus `VOL MUTE` when muted) to the X11 root `WM_NAME`. The `VOL` segment is omitted when no audio backend is detected, `CPU`/`RAM` use cross-Unix kernel telemetry (`/proc/stat` + `/meminfo` on Linux, `sysctl` on FreeBSD/OpenBSD/NetBSD), and `` is omitted cleanly if XKB is unavailable. When a narrow screen or busy systray constrains the top bar, `dwm` progressively compacts status segments (`src/common/anode_bar_fmt.h`) so the focused window title stays readable. - **Text-only layout indicator**: `` is a plain lowercase ASCII layout code (for example `us`, `de`, `ru`, `ua`, `latam`, `jp`) positioned immediately to the left of the datetime with no prefix labels, icons, or graphics. - **Event-driven status loop**: After `XkbQueryExtension()`, `anode-statusd` subscribes to `XkbNewKeyboardNotifyMask | XkbMapNotifyMask | XkbNamesNotifyMask` (`XkbSelectEvents`) and `XkbStateNotify` filtered solely to `XkbGroupStateMask` (`XkbSelectEventDetails`) so regular keystrokes and modifier presses never wake the loop, pairing XKB/signal events with a `<= 2000 ms` `poll()` refresh cadence for CPU/RAM telemetry and minute-aligned clock ticks without busy-polling. - **Layout code resolution (`src/common/anode_xkb_parse.h`)**: @@ -55,6 +55,6 @@ anode-replace --profile work --keep-panels ## Idle power policy & screen locking -- **Idle policy (`src/daemons/anode-powerd.c` & `src/common/anode_power_policy.h`)**: Defaults to `5 min` dim (`DIM_SEC=300`, dimming to `max(0.35, 45%)` of current brightness and polling every `500 ms` while dimmed for responsive wake), `10 min` lock (`LOCK_SEC=600`), `30 min` battery-only suspend (`SUSPEND_SEC=1800`, `SUSPEND_ON_AC=0`), and `5%` critical-battery warning/suspend (`CRIT_BATT_PCT=5`), configurable in `$XDG_CONFIG_HOME/anode/power.conf`. +- **Idle policy (`src/daemons/anode-powerd.c` & `src/common/anode_power_policy.h`)**: Defaults to `5 min` dim (`DIM_SEC=300`, dimming to `max(0.35, 45%)` of current brightness and polling every `500 ms` while dimmed for responsive wake), `10 min` lock (`LOCK_SEC=600`), `30 min` battery-only suspend (`SUSPEND_SEC=1800`, `SUSPEND_ON_AC=0`), and `5%` critical-battery warning/suspend (`CRIT_BATT_PCT=5`), configurable live from either `anode-power` or `anode-display` (and in `$XDG_CONFIG_HOME/anode/power.conf`, reloaded automatically by `anode-powerd` via `SIGUSR1`). - **Brightness restoration & backlight access**: Automatically restores saved brightness when waking from `ANODE_PWR_DIMMED` / `ANODE_PWR_LOCKED` / `ANODE_PWR_SUSPENDED` or on daemon exit. On Linux, `anode_backlight_get()` (`src/common/anode_plat.c`) verifies writable `/sys/class/backlight/*/brightness` (`access(..., W_OK) == 0`) before using sysfs, falling back to `brightnessctl` / `xrandr` when unprivileged. - **Screen-lock authentication & stacking (`src/daemons/anode-checkpw.c`, `src/apps/anode-lock.c`)**: Verifies against `/etc/shadow` / BSD `getpwnam` directly when permitted and falls back to the setuid PAM helper (`/sbin/unix_chkpwd` / `/usr/sbin/unix_chkpwd` / `/usr/libexec/unix_chkpwd`) when running non-root; `make install` applies `chmod 4755` to `anode-checkpw` when invoked as `root` with an empty `DESTDIR`. `anode-lock` (`fullscreen_override`) stays visually stacked above `dwm`'s systray (`systray->win` configured `Above` `m->barwin`) and status bar while still allowing `anode-vkbd` on top when toggled. diff --git a/scripts/anode-apply-display b/scripts/anode-apply-display new file mode 100755 index 0000000..1039128 --- /dev/null +++ b/scripts/anode-apply-display @@ -0,0 +1,125 @@ +#!/bin/sh +# ANODE multi-monitor saved layout restorer (strict POSIX sh) +set -eu + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +CONF_FILE="$XDG_CONFIG_HOME/anode/displays.conf" + +if [ -z "${DISPLAY:-}" ] || [ ! -r "$CONF_FILE" ] || ! command -v xrandr >/dev/null 2>&1; then + exit 0 +fi + +XR_OUT="$(xrandr --query 2>/dev/null || true)" +if [ -z "$XR_OUT" ]; then + exit 0 +fi + +SIG="$(printf '%s\n' "$XR_OUT" | awk '/ connected/ { print $1 }' | LC_ALL=C sort | awk ' + { s = (NR == 1) ? $0 : (s "," $0) } + END { print s } +')" +if [ -z "$SIG" ]; then + exit 0 +fi + +XR_SPEC="$(printf '%s\n' "$XR_OUT" | awk -v conf="$CONF_FILE" -v sig="$SIG" ' + BEGIN { + cur_out = "" + } + /^[A-Za-z0-9._-]+ (connected|disconnected)/ { + cur_out = "" + if ($2 == "connected") { + cur_out = $1 + conn[cur_out] = 1 + } + next + } + cur_out != "" && /^[[:space:]]+[0-9]+x[0-9]+/ { + mode = $1 + modes[cur_out SUBSEP mode] = 1 + next + } + END { + hdr = "[profile:" sig "]" + in_sec = 0 + en_cnt = 0 + out_cnt = 0 + while ((getline line < conf) > 0) { + gsub(/\r$/, "", line) + s = line + gsub(/^[ \t]+|[ \t]+$/, "", s) + if (s == "" || substr(s, 1, 1) == "#" || substr(s, 1, 1) == ";") continue + if (substr(s, 1, 1) == "[") { + if (in_sec) break + in_sec = (s == hdr) + continue + } + if (!in_sec || substr(s, 1, 7) != "output=") continue + n = split(substr(s, 8), f, ",") + if (n < 8) continue + name = f[1]; en = f[2]; pri = f[3]; mode = f[4] + hz = f[5]; px = f[6]; py = f[7]; rot = f[8] + if (name !~ /^[A-Za-z0-9._-]+$/ || !(name in conn)) continue + if (en != "0" && en != "1") continue + if (pri != "0" && pri != "1") continue + if (px !~ /^-?[0-9]+$/ || py !~ /^-?[0-9]+$/) continue + if (rot != "normal" && rot != "left" && rot != "inverted" && rot != "right") continue + + if (en == "0") { + rows[++out_cnt] = name "|0|0|-|-|0|0|normal" + continue + } + has_mode = (mode ~ /^[0-9]+x[0-9]+$/ && ((name SUBSEP mode) in modes)) + if (!has_mode) mode = "auto" + if (hz !~ /^[0-9]+(\.[0-9]+)?$/) hz = "" + rows[++out_cnt] = name "|1|" pri "|" mode "|" hz "|" px "|" py "|" rot + en_cnt++ + } + close(conf) + if (en_cnt < 1) exit 0 + for (i = 1; i <= out_cnt; i++) { + print rows[i] + } + } +')" + +if [ -z "$XR_SPEC" ]; then + exit 0 +fi + +set -- +OLD_IFS="$IFS" +IFS=' +' +for row in $XR_SPEC; do + _name="${row%%|*}"; _rest="${row#*|}" + _en="${_rest%%|*}"; _rest="${_rest#*|}" + _pri="${_rest%%|*}"; _rest="${_rest#*|}" + _mode="${_rest%%|*}"; _rest="${_rest#*|}" + _hz="${_rest%%|*}"; _rest="${_rest#*|}" + _px="${_rest%%|*}"; _rest="${_rest#*|}" + _py="${_rest%%|*}"; _rot="${_rest#*|}" + + set -- "$@" "--output" "$_name" + if [ "$_en" = "0" ]; then + set -- "$@" "--off" + continue + fi + if [ "$_mode" = "auto" ]; then + set -- "$@" "--auto" + else + set -- "$@" "--mode" "$_mode" + if [ -n "$_hz" ] && [ "$_hz" != "-" ]; then + set -- "$@" "--rate" "$_hz" + fi + fi + set -- "$@" "--pos" "${_px}x${_py}" "--rotate" "$_rot" + if [ "$_pri" = "1" ]; then + set -- "$@" "--primary" + fi +done +IFS="$OLD_IFS" + +if [ $# -gt 0 ]; then + xrandr "$@" >/dev/null 2>&1 || true +fi diff --git a/scripts/anode-apply-scale b/scripts/anode-apply-scale index 0d7b228..7d992ef 100755 --- a/scripts/anode-apply-scale +++ b/scripts/anode-apply-scale @@ -73,9 +73,7 @@ detect_edid_scale() { if [ "$_dpi" = "96" ] && [ -n "${DISPLAY:-}" ] && command -v xrandr >/dev/null 2>&1; then _xrandr_dpi="$(xrandr --query 2>/dev/null | awk ' / connected/ { - if (match($0, /[0-9]+x[0-9]+/) && match($0, /[0-9]+mm x [0-9]+mm/)) { - res = substr($0, RSTART) - } + is_pri = ($0 ~ / primary /) px = 0; wmm = 0 for (i = 1; i <= NF; i++) { if ($i ~ /^[0-9]+x[0-9]+(\+[0-9]+\+[0-9]+)?$/ && px == 0) { @@ -86,10 +84,19 @@ detect_edid_scale() { } } if (px > 0 && wmm > 0) { - printf "%.2f\n", (px * 25.4) / wmm - exit + val = (px * 25.4) / wmm + if (is_pri) { + printf "%.2f\n", val + got = 1 + exit + } else if (fallback == "") { + fallback = sprintf("%.2f", val) + } } } + END { + if (!got && fallback != "") print fallback + } ' || true)" if [ -n "${_xrandr_dpi:-}" ]; then _dpi="$_xrandr_dpi" diff --git a/scripts/anode-apply-theme b/scripts/anode-apply-theme index 68dc84e..54e4bc1 100755 --- a/scripts/anode-apply-theme +++ b/scripts/anode-apply-theme @@ -11,16 +11,84 @@ SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then cat <<'EOF' -Usage: anode-apply-theme [THEME_NAME | /path/to/Theme.xth] +Usage: + anode-apply-theme [THEME_NAME | /path/to/Theme.xth] + anode-apply-theme --install /path/to/Theme.xth [Name] EOF exit 0 fi -REQ_THEME="${1:-}" +sanitize_theme_name() { + printf '%s' "$1" | tr -c 'A-Za-z0-9_-' '_' | sed 's/^_*//; s/_*$//' +} + +INSTALL_SRC="" +INSTALL_NAME="" +REQ_THEME="" +if [ "${1:-}" = "--install" ]; then + if [ $# -lt 2 ] || [ -z "${2:-}" ]; then + printf 'anode-apply-theme: --install requires a .xth file path\n' >&2 + exit 1 + fi + INSTALL_SRC="$2" + INSTALL_NAME="${3:-}" +else + REQ_THEME="${1:-}" +fi + +if [ -n "$INSTALL_SRC" ]; then + if [ ! -f "$INSTALL_SRC" ] || [ ! -r "$INSTALL_SRC" ]; then + printf 'anode-apply-theme: cannot read theme file: %s\n' "$INSTALL_SRC" >&2 + exit 1 + fi + if ! awk ' + { + s = $0 + gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s) + if (s == "" || substr(s, 1, 1) == "!" || substr(s, 1, 1) == "#") next + if (index(s, ":") > 1) { ok = 1; exit } + } + END { exit(ok ? 0 : 1) } + ' "$INSTALL_SRC"; then + printf 'anode-apply-theme: invalid .xth theme file: %s\n' "$INSTALL_SRC" >&2 + exit 1 + fi + if [ -z "$INSTALL_NAME" ]; then + INSTALL_NAME="$(awk -F: '/^theme\.name[[:space:]]*:/ { sub(/^[[:space:]]+/, "", $2); sub(/[ \t\r\n]+$/, "", $2); print $2; exit }' "$INSTALL_SRC" || true)" + fi + if [ -z "$INSTALL_NAME" ]; then + INSTALL_NAME="$(basename "$INSTALL_SRC" .xth)" + fi + SAFE_NAME="$(sanitize_theme_name "$INSTALL_NAME")" + if [ -z "$SAFE_NAME" ] || [ "$SAFE_NAME" = "." ] || [ "$SAFE_NAME" = ".." ]; then + printf 'anode-apply-theme: invalid target theme name\n' >&2 + exit 1 + fi + mkdir -p "$CONF_DIR/themes" + DEST_XTH="$CONF_DIR/themes/$SAFE_NAME.xth" + TMP_INST="$DEST_XTH.tmp.$$" + awk -v tname="$SAFE_NAME" ' + BEGIN { had_name = 0 } + /^theme\.name[[:space:]]*:/ { + if (!had_name) { + printf "theme.name: %s\n", tname + had_name = 1 + } + next + } + { print $0 } + END { + if (!had_name) printf "theme.name: %s\n", tname + } + ' "$INSTALL_SRC" > "$TMP_INST" + mv -f "$TMP_INST" "$DEST_XTH" + REQ_THEME="$DEST_XTH" +fi + if [ -z "$REQ_THEME" ] && [ -f "$THEME_CONF" ]; then REQ_THEME="$(awk -F= '/^THEME=/{ print $2; exit }' "$THEME_CONF" 2>/dev/null || true)" fi -: "${REQ_THEME:=AnodeDefault}" +: "${REQ_THEME:=Anodized}" find_xth() { _q="$1" @@ -49,6 +117,13 @@ find_xth() { } XTH_FILE="$(find_xth "$REQ_THEME" || true)" +if [ -z "$XTH_FILE" ] || [ ! -r "$XTH_FILE" ]; then + _req_base="$(basename "$REQ_THEME" .xth)" + if [ "$_req_base" = "AnodeDefault" ]; then + printf 'anode-apply-theme: warning: AnodeDefault is deprecated; using Anodized\n' >&2 + XTH_FILE="$(find_xth "Anodized" || true)" + fi +fi if [ -z "$XTH_FILE" ] || [ ! -r "$XTH_FILE" ]; then printf 'anode-apply-theme: theme not found: %s\n' "$REQ_THEME" >&2 exit 1 diff --git a/scripts/anode-session b/scripts/anode-session index 8de05cd..b3375b2 100755 --- a/scripts/anode-session +++ b/scripts/anode-session @@ -94,6 +94,9 @@ for _envfile in "$ANODE_PREFIX/share/anode/env.sh" "$SCRIPT_DIR/../data/env.sh"; done unset _envfile +if [ -n "${DISPLAY:-}" ] && command -v anode-apply-display >/dev/null 2>&1; then + anode-apply-display >/dev/null 2>&1 || true +fi if [ ! -f "$XDG_CONFIG_HOME/anode/scale.conf" ] && command -v anode-apply-scale >/dev/null 2>&1; then anode-apply-scale auto --no-apply >/dev/null 2>&1 || true fi @@ -114,7 +117,7 @@ if [ "${ANODE_NO_DBUS:-0}" != "1" ]; then fi if [ ! -f "$HOME/.Xresources" ] && command -v anode-apply-theme >/dev/null 2>&1; then - anode-apply-theme AnodeDefault >/dev/null 2>&1 || true + anode-apply-theme Anodized >/dev/null 2>&1 || true elif [ -f "$HOME/.Xresources" ]; then if command -v xrdb >/dev/null 2>&1; then xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true @@ -150,7 +153,9 @@ spawn_bg xsettingsd spawn_bg dunst spawn_bg anode-statusd spawn_bg anode-powerd -spawn_bg anode-touchd +if [ "${ANODE_NO_TOUCHD:-0}" != "1" ]; then + spawn_bg anode-touchd +fi if [ "${ANODE_TOUCH:-0}" = "1" ]; then spawn_bg anode-vkbd diff --git a/scripts/anode-sync-dunst-theme b/scripts/anode-sync-dunst-theme index d5c141f..936a0e4 100755 --- a/scripts/anode-sync-dunst-theme +++ b/scripts/anode-sync-dunst-theme @@ -43,14 +43,14 @@ FONT_FACE="$(xres_get theme.fontFace "Fira Code")" SCALE="$(xres_get theme.scale "1.00")" BASE_SZ="$(xres_get theme.baseFontSize "15")" -BG_OVERLAY="$(xres_get theme.bgOverlay "#192231")" -BG_URGENT="$(xres_get theme.dangerBg "#471d24")" -FG_BRIGHT="$(xres_get theme.fgBright "#ffffff")" -FG_MAIN="$(xres_get theme.fgMain "#e6e1cf")" -BORDER="$(xres_get theme.border "#283444")" -ACCENT="$(xres_get theme.accent "#59c2ff")" -WARNING="$(xres_get theme.warning "#ffb454")" -DANGER="$(xres_get theme.danger "#f07178")" +BG_OVERLAY="$(xres_get theme.bgOverlay "#171b22")" +BG_URGENT="$(xres_get theme.dangerBg "#3f1d20")" +FG_BRIGHT="$(xres_get theme.fgBright "#f5f7fa")" +FG_MAIN="$(xres_get theme.fgMain "#e4e8ee")" +BORDER="$(xres_get theme.border "#2d3440")" +ACCENT="$(xres_get theme.accent "#cfd6e0")" +WARNING="$(xres_get theme.warning "#e2bc72")" +DANGER="$(xres_get theme.danger "#e07a7a")" GEOM="$(awk -v s="$SCALE" -v bsz="$BASE_SZ" 'BEGIN { sc = s + 0.0 diff --git a/scripts/anode-sync-gtk-theme b/scripts/anode-sync-gtk-theme index dcf83ff..edb938c 100755 --- a/scripts/anode-sync-gtk-theme +++ b/scripts/anode-sync-gtk-theme @@ -68,7 +68,7 @@ resolve_ui_font() { printf '%s\n' "$_req" } -TNAME="$(xres_get theme.name "AnodeDefault")" +TNAME="$(xres_get theme.name "Anodized")" DARK="$(xres_get theme.isDark "")" FONT_FACE="$(xres_get theme.fontFace "Fira Code")" MONO_FONT="$FONT_FACE" @@ -79,30 +79,30 @@ XFT_DPI="$(xres_get Xft.dpi "")" CUR_SZ="$(xres_get Xcursor.size "24")" ICON_THEME="$(xres_get theme.iconTheme "Adwaita")" -BG_MAIN="$(xres_get theme.bgMain "#0b0e14")" -BG_BAR="$(xres_get theme.bgBar "#11161f")" -BG_HEADER="$(xres_get theme.bgHeader "#141a24")" -BG_FOOTER="$(xres_get theme.bgFooter "#0f141d")" -BG_OVERLAY="$(xres_get theme.bgOverlay "#192231")" -BG_ALT_EVEN="$(xres_get theme.bgAltEven "#131923")" -BG_ALT_ODD="$(xres_get theme.bgAltOdd "#171f2b")" -BG_INPUT="$(xres_get theme.bgInput "#1a2330")" -BG_INPUT_FOC="$(xres_get theme.bgInputFocus "#202c3d")" -BG_BUTTON="$(xres_get theme.bgButton "#1e2838")" -BG_SEARCH="$(xres_get theme.bgSearch "#1b2433")" -FG_MAIN="$(xres_get theme.fgMain "#e6e1cf")" -FG_BRIGHT="$(xres_get theme.fgBright "#ffffff")" -FG_MUTED="$(xres_get theme.fgMuted "#8693a6")" -SEL_BG="$(xres_get theme.selBg "#2b5278")" -SEL_FG="$(xres_get theme.selFg "#ffffff")" -ACCENT="$(xres_get theme.accent "#59c2ff")" -ACCENT_ALT="$(xres_get theme.accentAlt "#73d0ff")" -HIGHLIGHT="$(xres_get theme.highlight "#ffd173")" -BORDER="$(xres_get theme.border "#283444")" -DIVIDER="$(xres_get theme.divider "#1e2736")" -SUCCESS="$(xres_get theme.success "#7fd962")" -WARNING="$(xres_get theme.warning "#ffb454")" -DANGER="$(xres_get theme.danger "#f07178")" +BG_MAIN="$(xres_get theme.bgMain "#08090b")" +BG_BAR="$(xres_get theme.bgBar "#0e1014")" +BG_HEADER="$(xres_get theme.bgHeader "#12151a")" +BG_FOOTER="$(xres_get theme.bgFooter "#0b0d11")" +BG_OVERLAY="$(xres_get theme.bgOverlay "#171b22")" +BG_ALT_EVEN="$(xres_get theme.bgAltEven "#101318")" +BG_ALT_ODD="$(xres_get theme.bgAltOdd "#14181f")" +BG_INPUT="$(xres_get theme.bgInput "#161a21")" +BG_INPUT_FOC="$(xres_get theme.bgInputFocus "#1e232c")" +BG_BUTTON="$(xres_get theme.bgButton "#1c212a")" +BG_SEARCH="$(xres_get theme.bgSearch "#191e27")" +FG_MAIN="$(xres_get theme.fgMain "#e4e8ee")" +FG_BRIGHT="$(xres_get theme.fgBright "#f5f7fa")" +FG_MUTED="$(xres_get theme.fgMuted "#89929f")" +SEL_BG="$(xres_get theme.selBg "#38414f")" +SEL_FG="$(xres_get theme.selFg "#f5f7fa")" +ACCENT="$(xres_get theme.accent "#cfd6e0")" +ACCENT_ALT="$(xres_get theme.accentAlt "#e5eaf0")" +HIGHLIGHT="$(xres_get theme.highlight "#e2bc72")" +BORDER="$(xres_get theme.border "#2d3440")" +DIVIDER="$(xres_get theme.divider "#20252f")" +SUCCESS="$(xres_get theme.success "#79cf9c")" +WARNING="$(xres_get theme.warning "#e2bc72")" +DANGER="$(xres_get theme.danger "#e07a7a")" THEME_ID="ANODE-$TNAME" diff --git a/scripts/detect-env.sh b/scripts/detect-env.sh index 7f890ec..7bd8528 100755 --- a/scripts/detect-env.sh +++ b/scripts/detect-env.sh @@ -166,8 +166,8 @@ if "$PKG_CFG" --exists xscrnsaver 2>/dev/null; then POWERD_DEFS="-DHAVE_XSCRNSAVER=1" fi -DWM_CFLAGS="$("$PKG_CFG" --cflags fontconfig freetype2 xft pango pangoxft harfbuzz x11 xinerama xrender)" -DWM_LIBS="$("$PKG_CFG" --libs fontconfig freetype2 xft pango pangoxft harfbuzz x11 xinerama xrender)" +DWM_CFLAGS="$("$PKG_CFG" --cflags fontconfig freetype2 xft pango pangoxft harfbuzz x11 xinerama xrandr xrender)" +DWM_LIBS="$("$PKG_CFG" --libs fontconfig freetype2 xft pango pangoxft harfbuzz x11 xinerama xrandr xrender)" DMENU_CFLAGS="$("$PKG_CFG" --cflags fontconfig freetype2 xft pango pangoxft harfbuzz x11 xfixes xi xinerama)" DMENU_LIBS="$("$PKG_CFG" --libs fontconfig freetype2 xft pango pangoxft harfbuzz x11 xfixes xi xinerama) -lm" diff --git a/src/apps/anode-display.c b/src/apps/anode-display.c index 13b354f..dea773f 100644 --- a/src/apps/anode-display.c +++ b/src/apps/anode-display.c @@ -2,119 +2,226 @@ #include "gemui.h" #include "anode_plat.h" #include "anode_scale.h" +#include "anode_display_cfg.h" +#include "anode_power_policy.h" +#include #include #include #include #include -#define MAX_OUTPUTS 8 -#define MAX_MODES 24 +#define MAX_MODES 36 +#define MODES_PER_PAGE 4 typedef struct { - char name[32]; - int cur_w, cur_h; - double cur_hz; int mode_w[MAX_MODES]; int mode_h[MAX_MODES]; double mode_hz[MAX_MODES]; int num_modes; - int rot_idx; /* 0=normal, 1=left, 2=inverted, 3=right */ - bool active; -} out_info_t; + int sel_mode; +} out_modes_t; + +enum { TAB_ARRANGE = 0, TAB_SCALING = 1 }; typedef struct { gemui_app_t *app; - out_info_t outs[MAX_OUTPUTS]; + int tab; + out_modes_t modes[ANODE_DISP_MAX_OUTS]; + anode_disp_out_t cfg[ANODE_DISP_MAX_OUTS]; + anode_disp_out_t pre_apply[ANODE_DISP_MAX_OUTS]; int n_outs; + int n_pre; int sel_out; - int sel_mode; + int mode_page; + int confirm_sec; + + bool dragging; + bool drag_moved; + int drag_idx; + int drag_start_px; + int drag_start_py; + int drag_orig_x; + int drag_orig_y; + gemui_rect_t canvas_rect; + double map_scale; + int map_vx0; + int map_vy0; + int map_cx0; + int map_cy0; + + bool bri_dragging; + gemui_rect_t bri_rect; double scale; bool touch_mode; int bri_pct; + anode_power_cfg_t pwr_cfg; } disp_state_t; enum { - HIT_OUT = 1, - HIT_MODE, + HIT_TAB = 1, + HIT_CANVAS_MON, + HIT_PRESET, + HIT_ENABLE_TOGGLE, + HIT_SET_PRIMARY, HIT_ROT, + HIT_MODE_PAGE, + HIT_MODE, + HIT_REFRESH, + HIT_SAVE_PROFILE, + HIT_APPLY_LAYOUT, + HIT_CONFIRM_KEEP, + HIT_CONFIRM_REVERT, HIT_SCALE_PRESET, HIT_SCALE_STEP, HIT_TOUCH, HIT_BRI, - HIT_APPLY_MODE, + HIT_DIM_STEP, + HIT_LOCK_STEP, + HIT_SUSP_STEP, + HIT_SUSP_AC, HIT_QUIT }; static const double PRESETS[] = {0.75, 1.00, 1.25, 1.50, 1.75, 2.00, 2.50, 3.00}; static const char *ROTS[] = {"normal", "left", "inverted", "right"}; +static const char *PRESET_LABELS[] = { + "Extend Right", "Extend Left", "Stack Above", "Stack Below", "Mirror", "Single" +}; + +static void sync_sel_mode_for(disp_state_t *st, int oi) { + if (oi < 0 || oi >= st->n_outs) return; + out_modes_t *om = &st->modes[oi]; + const anode_disp_out_t *co = &st->cfg[oi]; + om->sel_mode = 0; + for (int i = 0; i < om->num_modes; i++) { + if (om->mode_w[i] == co->w && om->mode_h[i] == co->h && + (int)(om->mode_hz[i] + 0.5) == (int)(co->hz + 0.5)) { + om->sel_mode = i; + break; + } + } +} + +static void load_power_cfg(disp_state_t *st) { + char dir[512], path[576]; + anode_config_dir(dir, sizeof(dir)); + snprintf(path, sizeof(path), "%s/power.conf", dir); + anode_power_cfg_load(path, &st->pwr_cfg); +} + +static void save_power_cfg(disp_state_t *st, const char *toast_msg) { + char dir[512], path[576]; + anode_config_dir(dir, sizeof(dir)); + snprintf(path, sizeof(path), "%s/power.conf", dir); + if (anode_power_cfg_save(path, &st->pwr_cfg)) { + const char *pd[] = {"anode-powerd"}; + anode_signal_procs(pd, 1, SIGUSR1); + gemui_show_toast(st->app, toast_msg, 1800); + } else { + gemui_show_toast(st->app, "Failed to save power.conf", 2200); + } +} static void scan_outputs(disp_state_t *st) { Display *dpy = gemui_display(st->app); Window root = DefaultRootWindow(dpy); st->n_outs = 0; + XRRScreenResources *res = XRRGetScreenResourcesCurrent(dpy, root); if (!res) res = XRRGetScreenResources(dpy, root); - if (!res) return; + RROutput primary_out = XRRGetOutputPrimary(dpy, root); - for (int i = 0; i < res->noutput && st->n_outs < MAX_OUTPUTS; i++) { - XRROutputInfo *oi = XRRGetOutputInfo(dpy, res, res->outputs[i]); - if (!oi || oi->connection != RR_Connected) { - if (oi) XRRFreeOutputInfo(oi); - continue; - } - out_info_t *o = &st->outs[st->n_outs++]; - memset(o, 0, sizeof(*o)); - snprintf(o->name, sizeof(o->name), "%s", oi->name); - - RRMode cur_mode = None; - if (oi->crtc) { - XRRCrtcInfo *ci = XRRGetCrtcInfo(dpy, res, oi->crtc); - if (ci) { - o->active = (ci->width > 0 && ci->height > 0); - o->cur_w = (int)ci->width; - o->cur_h = (int)ci->height; - cur_mode = ci->mode; - if (ci->rotation & RR_Rotate_90) o->rot_idx = 1; - else if (ci->rotation & RR_Rotate_180) o->rot_idx = 2; - else if (ci->rotation & RR_Rotate_270) o->rot_idx = 3; - else o->rot_idx = 0; - XRRFreeCrtcInfo(ci); + if (res) { + for (int i = 0; i < res->noutput && st->n_outs < ANODE_DISP_MAX_OUTS; i++) { + XRROutputInfo *oi = XRRGetOutputInfo(dpy, res, res->outputs[i]); + if (!oi || oi->connection != RR_Connected) { + if (oi) XRRFreeOutputInfo(oi); + continue; } - } + int idx = st->n_outs++; + out_modes_t *om = &st->modes[idx]; + anode_disp_out_t *co = &st->cfg[idx]; + memset(om, 0, sizeof(*om)); + memset(co, 0, sizeof(*co)); + snprintf(co->name, sizeof(co->name), "%s", oi->name); + co->primary = (res->outputs[i] == primary_out); - for (int m = 0; m < oi->nmode && o->num_modes < MAX_MODES; m++) { - for (int k = 0; k < res->nmode; k++) { - if (res->modes[k].id == oi->modes[m]) { - XRRModeInfo *mi = &res->modes[k]; - double hz = (mi->hTotal && mi->vTotal) - ? (double)mi->dotClock / ((double)mi->hTotal * (double)mi->vTotal) - : 60.0; - bool dup = false; - for (int d = 0; d < o->num_modes; d++) { - if (o->mode_w[d] == (int)mi->width && o->mode_h[d] == (int)mi->height && - (int)(o->mode_hz[d] + 0.5) == (int)(hz + 0.5)) { - dup = true; - break; - } + RRMode cur_mode = None; + if (oi->crtc) { + XRRCrtcInfo *ci = XRRGetCrtcInfo(dpy, res, oi->crtc); + if (ci) { + co->enabled = (ci->width > 0 && ci->height > 0); + co->x = ci->x; + co->y = ci->y; + co->w = (int)ci->width; + co->h = (int)ci->height; + cur_mode = ci->mode; + if (ci->rotation & RR_Rotate_90) co->rot = 1; + else if (ci->rotation & RR_Rotate_180) co->rot = 2; + else if (ci->rotation & RR_Rotate_270) co->rot = 3; + else co->rot = 0; + /* Reverse physical W/H back to unrotated mode dimensions */ + if (co->rot == 1 || co->rot == 3) { + int tmp = co->w; + co->w = co->h; + co->h = tmp; } - if (!dup) { - int idx = o->num_modes++; - o->mode_w[idx] = (int)mi->width; - o->mode_h[idx] = (int)mi->height; - o->mode_hz[idx] = hz; - if (mi->id == cur_mode) { - o->cur_hz = hz; - st->sel_mode = idx; - } - } - break; + XRRFreeCrtcInfo(ci); } } + + for (int m = 0; m < oi->nmode && om->num_modes < MAX_MODES; m++) { + for (int k = 0; k < res->nmode; k++) { + if (res->modes[k].id == oi->modes[m]) { + XRRModeInfo *mi = &res->modes[k]; + double hz = (mi->hTotal && mi->vTotal) + ? (double)mi->dotClock / ((double)mi->hTotal * (double)mi->vTotal) + : 60.0; + bool dup = false; + for (int d = 0; d < om->num_modes; d++) { + if (om->mode_w[d] == (int)mi->width && om->mode_h[d] == (int)mi->height && + (int)(om->mode_hz[d] + 0.5) == (int)(hz + 0.5)) { + dup = true; + break; + } + } + if (!dup) { + int midx = om->num_modes++; + om->mode_w[midx] = (int)mi->width; + om->mode_h[midx] = (int)mi->height; + om->mode_hz[midx] = hz; + if (mi->id == cur_mode) { + co->hz = hz; + om->sel_mode = midx; + } + } + break; + } + } + } + + if (om->num_modes > 0) { + if (co->w <= 0 || co->h <= 0) { + co->w = om->mode_w[0]; + co->h = om->mode_h[0]; + co->hz = om->mode_hz[0]; + } else if (co->hz <= 0.0) { + co->hz = om->mode_hz[om->sel_mode]; + } + } + if (!co->enabled) co->primary = false; + XRRFreeOutputInfo(oi); } - XRRFreeOutputInfo(oi); + XRRFreeScreenResources(res); + } + + anode_disp_normalize(st->cfg, st->n_outs); + if (st->sel_out >= st->n_outs) st->sel_out = st->n_outs > 0 ? st->n_outs - 1 : 0; + for (int i = 0; i < st->n_outs; i++) sync_sel_mode_for(st, i); + if (st->n_outs > 0) { + st->mode_page = st->modes[st->sel_out].sel_mode / MODES_PER_PAGE; } - XRRFreeScreenResources(res); double dpi = 96.0, sc = 1.0; int tm = 0; @@ -128,6 +235,105 @@ static void scan_outputs(disp_state_t *st) { } else { st->bri_pct = 100; } + load_power_cfg(st); +} + +static bool save_current_profile(disp_state_t *st, bool quiet_toast) { + if (st->n_outs <= 0) return false; + char dir[512], path[544]; + anode_config_dir(dir, sizeof(dir)); + snprintf(path, sizeof(path), "%s/displays.conf", dir); + bool ok = anode_disp_save_profile(path, st->cfg, st->n_outs); + if (!quiet_toast) { + gemui_show_toast(st->app, + ok ? "Saved monitor profile to displays.conf" : "Failed to save monitor profile", + 2000); + } + return ok; +} + +static void confirm_revert(disp_state_t *st); + +static void on_timer(gemui_app_t *app, void *ud) { + (void)app; + disp_state_t *st = (disp_state_t *)ud; + if (st->confirm_sec <= 0) { + gemui_set_timer_ms(st->app, 0, NULL, NULL); + return; + } + st->confirm_sec--; + if (st->confirm_sec <= 0) { + confirm_revert(st); + } else { + gemui_request_redraw(st->app); + } +} + +static void confirm_keep(disp_state_t *st) { + gemui_set_timer_ms(st->app, 0, NULL, NULL); + st->confirm_sec = 0; + save_current_profile(st, true); + scan_outputs(st); + gemui_show_toast(st->app, "Layout kept & saved to displays.conf", 2200); + gemui_request_redraw(st->app); +} + +static void confirm_revert(disp_state_t *st) { + gemui_set_timer_ms(st->app, 0, NULL, NULL); + st->confirm_sec = 0; + if (st->n_pre > 0) { + const char *av[96]; + char tokbuf[1024]; + if (anode_disp_build_xrandr_argv(st->pre_apply, st->n_pre, av, 96, tokbuf, sizeof(tokbuf)) > 0) { + anode_run_cmd_timeout(av, NULL, 0, 5000); + } + } + scan_outputs(st); + gemui_show_toast(st->app, "Reverted previous monitor layout", 2200); + gemui_request_redraw(st->app); +} + +static void apply_layout_now(disp_state_t *st) { + if (st->n_outs <= 0) return; + bool any_en = false; + for (int i = 0; i < st->n_outs; i++) { + if (st->cfg[i].enabled) { any_en = true; break; } + } + if (!any_en) { + gemui_show_toast(st->app, "At least one monitor must stay enabled", 2000); + gemui_request_redraw(st->app); + return; + } + + anode_disp_normalize(st->cfg, st->n_outs); + + if (st->confirm_sec == 0) { + /* Snapshot live XRandR outputs right before applying */ + disp_state_t live_snap; + memset(&live_snap, 0, sizeof(live_snap)); + live_snap.app = st->app; + scan_outputs(&live_snap); + st->n_pre = live_snap.n_outs; + if (st->n_pre > 0) { + memcpy(st->pre_apply, live_snap.cfg, (size_t)st->n_pre * sizeof(st->pre_apply[0])); + } + } + + const char *av[96]; + char tokbuf[1024]; + if (anode_disp_build_xrandr_argv(st->cfg, st->n_outs, av, 96, tokbuf, sizeof(tokbuf)) <= 0) { + gemui_show_toast(st->app, "Invalid layout specification", 2000); + gemui_request_redraw(st->app); + return; + } + if (anode_run_cmd_timeout(av, NULL, 0, 5000) == 0) { + st->confirm_sec = 15; + gemui_set_timer_ms(st->app, 1000, on_timer, st); + gemui_show_toast(st->app, "Layout applied - click Keep within 15s", 2200); + } else { + gemui_show_toast(st->app, "xrandr layout apply failed", 2200); + } + gemui_request_redraw(st->app); } static void apply_scale_now(disp_state_t *st, const char *scale_arg, int touch_override) { @@ -153,50 +359,278 @@ static void apply_scale_now(disp_state_t *st, const char *scale_arg, int touch_o gemui_request_redraw(st->app); } -static void apply_selected_mode(disp_state_t *st) { - if (st->sel_out < 0 || st->sel_out >= st->n_outs) return; - out_info_t *o = &st->outs[st->sel_out]; - if (st->sel_mode < 0 || st->sel_mode >= o->num_modes) return; - char mode[48], rate[24]; - snprintf(mode, sizeof(mode), "%dx%d", o->mode_w[st->sel_mode], o->mode_h[st->sel_mode]); - snprintf(rate, sizeof(rate), "%.2f", o->mode_hz[st->sel_mode]); - const char *av[] = { - "xrandr", "--output", o->name, "--mode", mode, "--rate", rate, - "--rotate", ROTS[o->rot_idx], NULL - }; - if (anode_run_cmd_timeout(av, NULL, 0, 4000) == 0) { - scan_outputs(st); - gemui_show_toast(st->app, "Output mode applied", 1800); - } else { - gemui_show_toast(st->app, "xrandr mode apply failed", 2000); +static void draw_arrangement_tab(disp_state_t *st, cairo_t *cr, int w, int h, int y) { + const gemui_theme_t *t = gemui_theme(st->app); + int pad = gemui_scale_px(st->app, 12); + int cw = w - pad * 2; + int btn_h = gemui_touch_row_px(st->app, 30); + + /* Confirmation countdown bar when testing new layout */ + if (st->confirm_sec > 0) { + int cbh = gemui_touch_row_px(st->app, 38); + gemui_rect_t cbr = {pad, y, cw, cbh}; + gemui_fill_round(cr, cbr, (double)gemui_scale_px(st->app, 6), t->bg_toast); + gemui_stroke_round(cr, cbr, (double)gemui_scale_px(st->app, 6), 1.5, t->highlight); + char cmsg[96]; + snprintf(cmsg, sizeof(cmsg), "Keep this monitor layout? Reverting in %ds", st->confirm_sec); + int bbw = gemui_scale_px(st->app, 118); + gemui_draw_text(cr, t, (gemui_rect_t){pad + gemui_scale_px(st->app, 10), y, cw - bbw * 2 - pad * 3, cbh}, + cmsg, 0, true, GEMUI_ALIGN_LEFT, t->fg_bright); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad * 2 - bbw * 2 - gemui_scale_px(st->app, 6), y + 4, bbw, cbh - 8}, + "Keep & Save", HIT_CONFIRM_KEEP, 0, true, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - bbw - gemui_scale_px(st->app, 4), y + 4, bbw, cbh - 8}, + "Revert Now", HIT_CONFIRM_REVERT, 0, false, false, false); + y += cbh + pad / 2; } - gemui_request_redraw(st->app); + + /* Quick preset bar */ + int prw = (cw - pad / 2 * 5) / 6; + for (int i = 0; i < 6; i++) { + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + i * (prw + pad / 2), y, prw, btn_h}, + PRESET_LABELS[i], HIT_PRESET, i, false, false, false); + } + y += btn_h + pad / 2; + + /* 2D interactive monitor arrangement canvas */ + int ftr_h = btn_h + pad * 2; + int insp_h = btn_h * 4 + pad * 2; + int can_h = h - ftr_h - insp_h - y - pad / 2; + int min_can = gemui_scale_px(st->app, 130); + if (can_h < min_can) can_h = min_can; + gemui_rect_t can_r = {pad, y, cw, can_h}; + st->canvas_rect = can_r; + + gemui_fill_round(cr, can_r, (double)gemui_scale_px(st->app, 6), t->bg_alt_even); + gemui_stroke_round(cr, can_r, (double)gemui_scale_px(st->app, 6), 1.0, t->border); + + if (st->n_outs <= 0) { + gemui_draw_text(cr, t, can_r, "No connected XRandR outputs detected", 0, false, GEMUI_ALIGN_CENTER, t->fg_muted); + } else { + int vx[ANODE_DISP_MAX_OUTS], vy[ANODE_DISP_MAX_OUTS]; + int vw[ANODE_DISP_MAX_OUTS], vh[ANODE_DISP_MAX_OUTS]; + int act_max_x = 0; + bool any_en = false; + for (int i = 0; i < st->n_outs; i++) { + anode_disp_eff_size(st->cfg[i].w > 0 ? st->cfg[i].w : 1280, + st->cfg[i].h > 0 ? st->cfg[i].h : 720, + st->cfg[i].rot, &vw[i], &vh[i]); + if (st->cfg[i].enabled) { + vx[i] = st->cfg[i].x; + vy[i] = st->cfg[i].y; + if (!any_en || vx[i] + vw[i] > act_max_x) act_max_x = vx[i] + vw[i]; + any_en = true; + } + } + int off_y = 0; + int off_x = any_en ? (act_max_x + 260) : 0; + for (int i = 0; i < st->n_outs; i++) { + if (!st->cfg[i].enabled) { + vx[i] = off_x; + vy[i] = off_y; + off_y += vh[i] + 180; + } + } + + int min_vx = vx[0], min_vy = vy[0], max_vx = vx[0] + vw[0], max_vy = vy[0] + vh[0]; + for (int i = 1; i < st->n_outs; i++) { + if (vx[i] < min_vx) min_vx = vx[i]; + if (vy[i] < min_vy) min_vy = vy[i]; + if (vx[i] + vw[i] > max_vx) max_vx = vx[i] + vw[i]; + if (vy[i] + vh[i] > max_vy) max_vy = vy[i] + vh[i]; + } + int span_w = max_vx - min_vx; + int span_h = max_vy - min_vy; + if (span_w < 640) span_w = 640; + if (span_h < 480) span_h = 480; + + int inset = gemui_scale_px(st->app, 16); + int inner_w = can_r.w - inset * 2; + int inner_h = can_r.h - inset * 2; + double sx = (double)inner_w / (double)span_w; + double sy = (double)inner_h / (double)span_h; + double sc = sx < sy ? sx : sy; + if (sc <= 0.0) sc = 0.05; + + int drawn_w = (int)(span_w * sc); + int drawn_h = (int)(span_h * sc); + int cx0 = can_r.x + inset + (inner_w - drawn_w) / 2; + int cy0 = can_r.y + inset + (inner_h - drawn_h) / 2; + st->map_scale = sc; + st->map_vx0 = min_vx; + st->map_vy0 = min_vy; + st->map_cx0 = cx0; + st->map_cy0 = cy0; + + for (int i = 0; i < st->n_outs; i++) { + int rx = cx0 + (int)((vx[i] - min_vx) * sc); + int ry = cy0 + (int)((vy[i] - min_vy) * sc); + int rw = (int)(vw[i] * sc); + int rh = (int)(vh[i] * sc); + if (rw < gemui_scale_px(st->app, 54)) rw = gemui_scale_px(st->app, 54); + if (rh < gemui_scale_px(st->app, 36)) rh = gemui_scale_px(st->app, 36); + + bool is_sel = (i == st->sel_out); + gemui_rect_t mr = {rx, ry, rw, rh}; + gemui_color_t mbg = !st->cfg[i].enabled ? t->bg_main : (is_sel ? t->sel_bg : t->bg_button); + gemui_color_t mbd = is_sel ? t->accent : (st->cfg[i].enabled ? t->border : t->divider); + double mrad = (double)gemui_scale_px(st->app, 5); + gemui_fill_round(cr, mr, mrad, mbg); + gemui_stroke_round(cr, mr, mrad, is_sel ? 2.0 : 1.0, mbd); + + char line1[48], line2[48]; + snprintf(line1, sizeof(line1), "%s%s", st->cfg[i].primary ? "* " : "", st->cfg[i].name); + if (st->cfg[i].enabled) { + snprintf(line2, sizeof(line2), "%dx%d @%d,%d", vw[i], vh[i], st->cfg[i].x, st->cfg[i].y); + } else { + snprintf(line2, sizeof(line2), "[OFF]"); + } + int lh = mr.h / 2; + gemui_draw_text(cr, t, (gemui_rect_t){mr.x + 4, mr.y + 4, mr.w - 8, lh}, + line1, -1, true, GEMUI_ALIGN_CENTER, + st->cfg[i].enabled ? t->fg_bright : t->fg_muted); + gemui_draw_text(cr, t, (gemui_rect_t){mr.x + 4, mr.y + lh - 2, mr.w - 8, lh}, + line2, -2, false, GEMUI_ALIGN_CENTER, + is_sel ? t->accent : t->fg_muted); + gemui_hit_add(st->app, mr, HIT_CANVAS_MON, i); + } + } + y += can_h + pad / 2; + + /* Inspector for selected output */ + if (st->n_outs > 0 && st->sel_out >= 0 && st->sel_out < st->n_outs) { + anode_disp_out_t *so = &st->cfg[st->sel_out]; + out_modes_t *om = &st->modes[st->sel_out]; + + /* Row 1: info + Enable + Primary */ + int ctrl_w = gemui_scale_px(st->app, 128); + int info_w = cw - ctrl_w * 2 - pad; + char ilbl[128]; + snprintf(ilbl, sizeof(ilbl), "%s (%d, %d) %s", + so->name, so->x, so->y, so->primary ? "Primary" : (so->enabled ? "Secondary" : "Disabled")); + gemui_draw_text(cr, t, (gemui_rect_t){pad, y, info_w, btn_h}, + ilbl, 0, true, GEMUI_ALIGN_LEFT, t->fg_bright); + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad + info_w + pad / 2, y, ctrl_w, btn_h}, + "Enabled", so->enabled, HIT_ENABLE_TOGGLE, st->sel_out, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + info_w + ctrl_w + pad, y, ctrl_w, btn_h}, + "Set Primary", HIT_SET_PRIMARY, st->sel_out, false, so->primary, false); + y += btn_h + 6; + + /* Row 2: Rotation */ + int rot_lbl_w = gemui_scale_px(st->app, 86); + int rw = (cw - rot_lbl_w - pad * 3) / 4; + gemui_draw_text(cr, t, (gemui_rect_t){pad, y, rot_lbl_w, btn_h}, + "Rotation", -1, false, GEMUI_ALIGN_LEFT, t->fg_muted); + for (int i = 0; i < 4; i++) { + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + rot_lbl_w + i * (rw + pad), y, rw, btn_h}, + ROTS[i], HIT_ROT, i, false, i == so->rot, false); + } + y += btn_h + 6; + + /* Row 3: Paginated full Modes list */ + int nav_w = gemui_scale_px(st->app, 52); + int total_pages = (om->num_modes + MODES_PER_PAGE - 1) / MODES_PER_PAGE; + if (total_pages < 1) total_pages = 1; + if (st->mode_page >= total_pages) st->mode_page = total_pages - 1; + if (st->mode_page < 0) st->mode_page = 0; + + gemui_draw_text(cr, t, (gemui_rect_t){pad, y, rot_lbl_w, btn_h}, + "Mode", -1, false, GEMUI_ALIGN_LEFT, t->fg_muted); + int mstart_x = pad + rot_lbl_w; + int m_area_w = cw - rot_lbl_w - nav_w * 2 - pad * 2; + int mw = (m_area_w - (MODES_PER_PAGE - 1) * (pad / 2)) / MODES_PER_PAGE; + int first = st->mode_page * MODES_PER_PAGE; + for (int i = 0; i < MODES_PER_PAGE && first + i < om->num_modes; i++) { + int mi = first + i; + char mlbl[32]; + snprintf(mlbl, sizeof(mlbl), "%dx%d@%.0f", om->mode_w[mi], om->mode_h[mi], om->mode_hz[mi]); + gemui_draw_button(st->app, cr, (gemui_rect_t){mstart_x + i * (mw + pad / 2), y, mw, btn_h}, + mlbl, HIT_MODE, mi, false, mi == om->sel_mode, false); + } + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - nav_w * 2 - pad / 2, y, nav_w, btn_h}, + "<", HIT_MODE_PAGE, -1, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - nav_w, y, nav_w, btn_h}, + ">", HIT_MODE_PAGE, 1, false, false, false); + } + + /* Footer */ + int bw = gemui_scale_px(st->app, 128); + int sbw = gemui_scale_px(st->app, 108); + int fy = h - btn_h - pad; + gemui_draw_button(st->app, cr, (gemui_rect_t){pad, fy, sbw, btn_h}, + "Rescan", HIT_REFRESH, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + sbw + pad / 2, fy, sbw, btn_h}, + "Save Profile", HIT_SAVE_PROFILE, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad * 2 - bw * 2, fy, bw, btn_h}, + "Apply Layout", HIT_APPLY_LAYOUT, 0, true, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - bw, fy, bw, btn_h}, + "Close", HIT_QUIT, 0, false, false, false); } -static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { - disp_state_t *st = (disp_state_t *)ud; +static void draw_timeout_stepper(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *label, uint32_t ms, int hit_id) { const gemui_theme_t *t = gemui_theme(app); + double rad = (double)gemui_scale_px(app, 6); + double lw = (t->scale >= 1.5 ? 1.5 : 1.0); + gemui_fill_round(cr, r, rad, t->bg_alt_even); + gemui_stroke_round(cr, r, rad, lw, t->border); - char badge[64]; - snprintf(badge, sizeof(badge), "Scale %.2fx (%d DPI)", st->scale, t->dpi); - gemui_draw_header(app, cr, NULL, "ANODE Display & Fractional Scaling", badge); + int pad_x = gemui_scale_px(app, 10); + int gap = gemui_scale_px(app, 4); + int pad_y = gemui_scale_px(app, 4); + int bh = r.h - pad_y * 2; + if (bh < gemui_scale_px(app, 20)) bh = r.h - 4; + int bw = bh; + if (bw < gemui_scale_px(app, 28)) bw = gemui_scale_px(app, 28); + int vw = gemui_scale_px(app, 48); + int ctrl_w = bw * 2 + vw + gap * 2; - int pad = gemui_scale_px(app, 12); - int y = gemui_scale_px(app, 42) + pad; - int cw = w - pad * 2; - int btn_h = gemui_touch_row_px(app, 32); + gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad_x, r.y, r.w - ctrl_w - pad_x * 2, r.h}, + label, 0, false, GEMUI_ALIGN_LEFT, t->fg_main); - /* Outputs strip */ - if (st->n_outs > 0) { - int ow = (cw - pad * (st->n_outs - 1)) / st->n_outs; - for (int i = 0; i < st->n_outs; i++) { - char lbl[64]; - snprintf(lbl, sizeof(lbl), "%s (%dx%d)", st->outs[i].name, st->outs[i].cur_w, st->outs[i].cur_h); - gemui_draw_button(app, cr, (gemui_rect_t){pad + i * (ow + pad), y, ow, btn_h}, - lbl, HIT_OUT, i, false, i == st->sel_out, false); + int cx = r.x + r.w - pad_x - ctrl_w; + int by = r.y + (r.h - bh) / 2; + gemui_draw_button(app, cr, (gemui_rect_t){cx, by, bw, bh}, "-", hit_id, -1, false, false, false); + + char vtxt[16]; + anode_power_format_timeout(ms, vtxt, sizeof(vtxt)); + gemui_draw_text(cr, t, (gemui_rect_t){cx + bw + gap, r.y, vw, r.h}, + vtxt, 0, true, GEMUI_ALIGN_CENTER, + ms > 0U ? t->fg_bright : t->fg_muted); + + gemui_draw_button(app, cr, (gemui_rect_t){cx + bw + gap + vw + gap, by, bw, bh}, + "+", hit_id, 1, false, false, false); +} + +static bool adjust_timeout_hit(disp_state_t *st, int hit_id, int dir) { + struct { + int hit; + uint32_t *field; + const char *label; + bool is_susp; + } items[3] = { + {HIT_DIM_STEP, &st->pwr_cfg.dim_ms, "Dim brightness after", false}, + {HIT_LOCK_STEP, &st->pwr_cfg.lock_ms, "Lock screen after", false}, + {HIT_SUSP_STEP, &st->pwr_cfg.suspend_ms, "Auto suspend after", true} + }; + for (int i = 0; i < 3; i++) { + if (items[i].hit == hit_id) { + *items[i].field = items[i].is_susp + ? anode_power_step_suspend_timeout_ms(*items[i].field, dir) + : anode_power_step_screen_timeout_ms(*items[i].field, dir); + char vtxt[16], msg[64]; + anode_power_format_timeout(*items[i].field, vtxt, sizeof(vtxt)); + snprintf(msg, sizeof(msg), "%s: %s", items[i].label, vtxt); + save_power_cfg(st, msg); + return true; } - y += btn_h + pad; } + return false; +} + +static void draw_scaling_tab(disp_state_t *st, cairo_t *cr, int w, int h, int y) { + int pad = gemui_scale_px(st->app, 12); + int cw = w - pad * 2; + int btn_h = gemui_touch_row_px(st->app, 32); /* Scale presets grid (2 rows of 4 + Auto & -/+ steps) */ int pw = (cw - pad * 3) / 4; @@ -205,67 +639,140 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { char lbl[24]; snprintf(lbl, sizeof(lbl), "%.2fx", PRESETS[i]); bool act = (st->scale >= PRESETS[i] - 0.02 && st->scale <= PRESETS[i] + 0.02); - gemui_draw_button(app, cr, (gemui_rect_t){pad + c * (pw + pad), y + r * (btn_h + 6), pw, btn_h}, + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + c * (pw + pad), y + r * (btn_h + 6), pw, btn_h}, lbl, HIT_SCALE_PRESET, i, false, act, false); } y += (btn_h + 6) * 2 + pad / 2; int sw = (cw - pad * 2) / 3; - gemui_draw_button(app, cr, (gemui_rect_t){pad, y, sw, btn_h}, "-0.05 Scale", HIT_SCALE_STEP, -1, false, false, false); - gemui_draw_button(app, cr, (gemui_rect_t){pad + sw + pad, y, sw, btn_h}, "Auto EDID", HIT_SCALE_STEP, 0, true, false, false); - gemui_draw_button(app, cr, (gemui_rect_t){pad + (sw + pad) * 2, y, sw, btn_h}, "+0.05 Scale", HIT_SCALE_STEP, 1, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad, y, sw, btn_h}, "-0.05 Scale", HIT_SCALE_STEP, -1, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + sw + pad, y, sw, btn_h}, "Auto EDID", HIT_SCALE_STEP, 0, true, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (sw + pad) * 2, y, sw, btn_h}, "+0.05 Scale", HIT_SCALE_STEP, 1, false, false, false); y += btn_h + pad; /* Touch & Virtual Keyboard toggle */ - gemui_draw_toggle(app, cr, (gemui_rect_t){pad, y, cw, btn_h + 4}, + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad, y, cw, btn_h + 4}, "Touch Device Mode & Larger Hit Targets", st->touch_mode, HIT_TOUCH, 0, false); y += btn_h + 4 + pad; /* Brightness */ - int sli_h = gemui_touch_row_px(app, 50); + int sli_h = gemui_touch_row_px(st->app, 50); char btxt[24]; snprintf(btxt, sizeof(btxt), "%d%%", st->bri_pct); - gemui_draw_slider(app, cr, (gemui_rect_t){pad, y, cw, sli_h}, + gemui_draw_slider(st->app, cr, (gemui_rect_t){pad, y, cw, sli_h}, "Screen Brightness", (double)st->bri_pct / 100.0, btxt, HIT_BRI, 0, false); y += sli_h + pad; - /* Rotation + top modes */ - int rw = (cw - pad * 3) / 4; - int cur_rot = (st->n_outs > 0) ? st->outs[st->sel_out].rot_idx : 0; - for (int i = 0; i < 4; i++) { - gemui_draw_button(app, cr, (gemui_rect_t){pad + i * (rw + pad), y, rw, btn_h}, - ROTS[i], HIT_ROT, i, false, i == cur_rot, false); - } - y += btn_h + pad; + /* Screen Idle Timeouts */ + const gemui_theme_t *t = gemui_theme(st->app); + int lbl_h = gemui_scale_px(st->app, 20); + gemui_draw_text(cr, t, (gemui_rect_t){pad, y, cw, lbl_h}, + "Screen Idle Timeouts", -1, true, GEMUI_ALIGN_LEFT, t->fg_muted); + y += lbl_h + pad / 3; - if (st->n_outs > 0 && y + btn_h + pad < h - btn_h - pad) { - out_info_t *o = &st->outs[st->sel_out]; - int n_show = o->num_modes > 4 ? 4 : o->num_modes; - int mw = n_show > 0 ? (cw - pad * (n_show - 1)) / n_show : cw; - for (int i = 0; i < n_show; i++) { - char mlbl[32]; - snprintf(mlbl, sizeof(mlbl), "%dx%d@%.0f", o->mode_w[i], o->mode_h[i], o->mode_hz[i]); - gemui_draw_button(app, cr, (gemui_rect_t){pad + i * (mw + pad), y, mw, btn_h}, - mlbl, HIT_MODE, i, false, i == st->sel_mode, false); - } - } + int tw = (cw - pad) / 2; + draw_timeout_stepper(st->app, cr, (gemui_rect_t){pad, y, tw, btn_h}, + "Dim Brightness", st->pwr_cfg.dim_ms, HIT_DIM_STEP); + draw_timeout_stepper(st->app, cr, (gemui_rect_t){pad + tw + pad, y, tw, btn_h}, + "Lock Screen", st->pwr_cfg.lock_ms, HIT_LOCK_STEP); + y += btn_h + pad / 2; + draw_timeout_stepper(st->app, cr, (gemui_rect_t){pad, y, tw, btn_h}, + "Auto Suspend", st->pwr_cfg.suspend_ms, HIT_SUSP_STEP); + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad + tw + pad, y, tw, btn_h}, + "Suspend on AC", st->pwr_cfg.suspend_on_ac, HIT_SUSP_AC, 0, false); - /* Footer */ - int bw = gemui_scale_px(app, 140); + int bw = gemui_scale_px(st->app, 128); int fy = h - btn_h - pad; - gemui_draw_button(app, cr, (gemui_rect_t){w - pad * 2 - bw * 2, fy, bw, btn_h}, - "Apply Output", HIT_APPLY_MODE, 0, true, false, false); - gemui_draw_button(app, cr, (gemui_rect_t){w - pad - bw, fy, bw, btn_h}, + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - bw, fy, bw, btn_h}, "Close", HIT_QUIT, 0, false, false, false); } +static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { + disp_state_t *st = (disp_state_t *)ud; + const gemui_theme_t *t = gemui_theme(app); + + char badge[64]; + snprintf(badge, sizeof(badge), "Scale %.2fx (%d DPI)", st->scale, t->dpi); + gemui_draw_header(app, cr, NULL, "ANODE Display & Arrangement", badge); + + int pad = gemui_scale_px(st->app, 12); + int y = gemui_scale_px(st->app, 42) + pad / 2; + int cw = w - pad * 2; + int tab_h = gemui_touch_row_px(app, 30); + int tab_w = (cw - pad) / 2; + + gemui_draw_button(app, cr, (gemui_rect_t){pad, y, tab_w, tab_h}, + "Monitor Arrangement", HIT_TAB, TAB_ARRANGE, false, st->tab == TAB_ARRANGE, false); + gemui_draw_button(app, cr, (gemui_rect_t){pad + tab_w + pad, y, tab_w, tab_h}, + "Scaling, Brightness & Timeouts", HIT_TAB, TAB_SCALING, false, st->tab == TAB_SCALING, false); + y += tab_h + pad / 2; + + if (st->tab == TAB_ARRANGE) draw_arrangement_tab(st, cr, w, h, y); + else draw_scaling_tab(st, cr, w, h, y); +} + static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) { - (void)state; (void)utf8; disp_state_t *st = (disp_state_t *)ud; - if (ks == XK_Escape || ks == XK_q) gemui_quit(app, 0); - else if (ks == XK_r) { scan_outputs(st); gemui_request_redraw(app); } - else if (ks == XK_plus || ks == XK_equal) { + if (ks == XK_Escape) { + if (st->confirm_sec > 0) confirm_revert(st); + else gemui_quit(app, 0); + return; + } + if (ks == XK_q) { + if (st->confirm_sec > 0) confirm_revert(st); + gemui_quit(app, 0); + return; + } + if (ks == XK_Return && st->confirm_sec > 0) { + confirm_keep(st); + return; + } + if (ks == XK_Tab) { + st->tab = (st->tab == TAB_ARRANGE) ? TAB_SCALING : TAB_ARRANGE; + if (st->tab == TAB_SCALING) load_power_cfg(st); + gemui_request_redraw(app); + return; + } + if (ks == XK_r) { + scan_outputs(st); + gemui_request_redraw(app); + return; + } + if (st->tab == TAB_ARRANGE && st->n_outs > 0 && st->sel_out >= 0 && st->sel_out < st->n_outs) { + int step = (state & ShiftMask) ? 128 : 16; + anode_disp_out_t *so = &st->cfg[st->sel_out]; + if (ks == XK_Left && so->enabled) { + int nx = 0, ny = 0; + anode_disp_snap(st->cfg, st->n_outs, st->sel_out, so->x - step, so->y, 24, &nx, &ny); + so->x = nx; so->y = ny; + anode_disp_normalize(st->cfg, st->n_outs); + gemui_request_redraw(app); + return; + } else if (ks == XK_Right && so->enabled) { + int nx = 0, ny = 0; + anode_disp_snap(st->cfg, st->n_outs, st->sel_out, so->x + step, so->y, 24, &nx, &ny); + so->x = nx; so->y = ny; + anode_disp_normalize(st->cfg, st->n_outs); + gemui_request_redraw(app); + return; + } else if (ks == XK_Up && so->enabled) { + int nx = 0, ny = 0; + anode_disp_snap(st->cfg, st->n_outs, st->sel_out, so->x, so->y - step, 24, &nx, &ny); + so->x = nx; so->y = ny; + anode_disp_normalize(st->cfg, st->n_outs); + gemui_request_redraw(app); + return; + } else if (ks == XK_Down && so->enabled) { + int nx = 0, ny = 0; + anode_disp_snap(st->cfg, st->n_outs, st->sel_out, so->x, so->y + step, 24, &nx, &ny); + so->x = nx; so->y = ny; + anode_disp_normalize(st->cfg, st->n_outs); + gemui_request_redraw(app); + return; + } + } + if (ks == XK_plus || ks == XK_equal) { char b[16]; snprintf(b, sizeof(b), "%.2f", anode_clamp_scale(st->scale + 0.05)); apply_scale_now(st, b, -1); } else if (ks == XK_minus) { @@ -276,14 +783,138 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char * static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { disp_state_t *st = (disp_state_t *)ud; + + if (type == GEMUI_PTR_UP) { + if (st->dragging) { + if (st->drag_moved) { + anode_disp_normalize(st->cfg, st->n_outs); + gemui_request_redraw(app); + } + st->dragging = false; + st->drag_moved = false; + } + st->bri_dragging = false; + return; + } + + if (type == GEMUI_PTR_MOVE) { + if (st->dragging && st->drag_idx >= 0 && st->drag_idx < st->n_outs && + st->cfg[st->drag_idx].enabled && st->map_scale > 0.0) { + int dx_px = x - st->drag_start_px; + int dy_px = y - st->drag_start_py; + if (!st->drag_moved && (abs(dx_px) + abs(dy_px) < 4)) return; + st->drag_moved = true; + int raw_x = st->drag_orig_x + (int)((double)dx_px / st->map_scale); + int raw_y = st->drag_orig_y + (int)((double)dy_px / st->map_scale); + int sx = raw_x, sy = raw_y; + anode_disp_snap(st->cfg, st->n_outs, st->drag_idx, raw_x, raw_y, 64, &sx, &sy); + st->cfg[st->drag_idx].x = sx; + st->cfg[st->drag_idx].y = sy; + gemui_request_redraw(app); + } else if (st->bri_dragging && st->bri_rect.w > 0) { + int pct = ((x - st->bri_rect.x) * 100) / st->bri_rect.w; + if (pct < 5) pct = 5; + if (pct > 100) pct = 100; + st->bri_pct = pct; + anode_backlight_set((double)pct / 100.0); + gemui_request_redraw(app); + } + return; + } + if (type != GEMUI_PTR_DOWN || btn != Button1) return; const gemui_hit_t *hit = gemui_hit_test(app, x, y); if (!hit) return; - if (hit->id == HIT_OUT) { st->sel_out = hit->val; st->sel_mode = 0; gemui_request_redraw(app); } - else if (hit->id == HIT_MODE) { st->sel_mode = hit->val; gemui_request_redraw(app); } - else if (hit->id == HIT_ROT && st->n_outs > 0) { - st->outs[st->sel_out].rot_idx = hit->val; + + if (hit->id == HIT_TAB) { + st->tab = hit->val; + if (st->tab == TAB_SCALING) load_power_cfg(st); gemui_request_redraw(app); + } else if (hit->id == HIT_CANVAS_MON && hit->val >= 0 && hit->val < st->n_outs) { + st->sel_out = hit->val; + st->mode_page = st->modes[st->sel_out].sel_mode / MODES_PER_PAGE; + if (st->cfg[hit->val].enabled) { + st->dragging = true; + st->drag_moved = false; + st->drag_idx = hit->val; + st->drag_start_px = x; + st->drag_start_py = y; + st->drag_orig_x = st->cfg[hit->val].x; + st->drag_orig_y = st->cfg[hit->val].y; + } + gemui_request_redraw(app); + } else if (hit->id == HIT_PRESET && hit->val >= 0 && hit->val <= ANODE_DISP_PRESET_PRIMARY_ONLY) { + anode_disp_apply_preset(st->cfg, st->n_outs, st->sel_out, (anode_disp_preset_t)hit->val); + gemui_request_redraw(app); + } else if (hit->id == HIT_ENABLE_TOGGLE && hit->val >= 0 && hit->val < st->n_outs) { + if (st->cfg[hit->val].enabled) { + int en_cnt = 0; + for (int i = 0; i < st->n_outs; i++) { + if (st->cfg[i].enabled) en_cnt++; + } + if (en_cnt <= 1) { + gemui_show_toast(app, "At least one monitor must stay enabled", 2000); + return; + } + st->cfg[hit->val].enabled = false; + st->cfg[hit->val].primary = false; + } else { + st->cfg[hit->val].enabled = true; + if (st->cfg[hit->val].w <= 0 && st->modes[hit->val].num_modes > 0) { + st->cfg[hit->val].w = st->modes[hit->val].mode_w[0]; + st->cfg[hit->val].h = st->modes[hit->val].mode_h[0]; + st->cfg[hit->val].hz = st->modes[hit->val].mode_hz[0]; + } + int max_x = 0; + for (int i = 0; i < st->n_outs; i++) { + if (i != hit->val && st->cfg[i].enabled) { + int ew = 0, eh = 0; + anode_disp_eff_size(st->cfg[i].w, st->cfg[i].h, st->cfg[i].rot, &ew, &eh); + if (st->cfg[i].x + ew > max_x) max_x = st->cfg[i].x + ew; + } + } + st->cfg[hit->val].x = max_x; + st->cfg[hit->val].y = 0; + } + anode_disp_normalize(st->cfg, st->n_outs); + gemui_request_redraw(app); + } else if (hit->id == HIT_SET_PRIMARY && hit->val >= 0 && hit->val < st->n_outs) { + if (!st->cfg[hit->val].enabled) st->cfg[hit->val].enabled = true; + for (int i = 0; i < st->n_outs; i++) st->cfg[i].primary = (i == hit->val); + anode_disp_normalize(st->cfg, st->n_outs); + gemui_request_redraw(app); + } else if (hit->id == HIT_ROT && st->n_outs > 0) { + st->cfg[st->sel_out].rot = hit->val & 3; + gemui_request_redraw(app); + } else if (hit->id == HIT_MODE_PAGE && st->n_outs > 0) { + int n_modes = st->modes[st->sel_out].num_modes; + int pages = (n_modes + MODES_PER_PAGE - 1) / MODES_PER_PAGE; + if (pages < 1) pages = 1; + st->mode_page += hit->val; + if (st->mode_page < 0) st->mode_page = 0; + if (st->mode_page >= pages) st->mode_page = pages - 1; + gemui_request_redraw(app); + } else if (hit->id == HIT_MODE && st->n_outs > 0) { + out_modes_t *om = &st->modes[st->sel_out]; + if (hit->val >= 0 && hit->val < om->num_modes) { + om->sel_mode = hit->val; + st->cfg[st->sel_out].w = om->mode_w[hit->val]; + st->cfg[st->sel_out].h = om->mode_h[hit->val]; + st->cfg[st->sel_out].hz = om->mode_hz[hit->val]; + gemui_request_redraw(app); + } + } else if (hit->id == HIT_REFRESH) { + scan_outputs(st); + gemui_show_toast(app, "Rescanned connected displays", 1400); + gemui_request_redraw(app); + } else if (hit->id == HIT_SAVE_PROFILE) { + save_current_profile(st, false); + } else if (hit->id == HIT_APPLY_LAYOUT) { + apply_layout_now(st); + } else if (hit->id == HIT_CONFIRM_KEEP) { + confirm_keep(st); + } else if (hit->id == HIT_CONFIRM_REVERT) { + confirm_revert(st); } else if (hit->id == HIT_SCALE_PRESET) { char b[16]; snprintf(b, sizeof(b), "%.2f", PRESETS[hit->val]); apply_scale_now(st, b, -1); @@ -297,25 +928,37 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v char b[16]; snprintf(b, sizeof(b), "%.2f", st->scale); apply_scale_now(st, b, st->touch_mode ? 0 : 1); } else if (hit->id == HIT_BRI) { + st->bri_dragging = true; + st->bri_rect = hit->r; int pct = ((x - hit->r.x) * 100) / (hit->r.w > 0 ? hit->r.w : 1); if (pct < 5) pct = 5; if (pct > 100) pct = 100; st->bri_pct = pct; anode_backlight_set((double)pct / 100.0); gemui_request_redraw(app); - } else if (hit->id == HIT_APPLY_MODE) { - apply_selected_mode(st); + } else if (adjust_timeout_hit(st, hit->id, hit->val)) { + gemui_request_redraw(app); + } else if (hit->id == HIT_SUSP_AC) { + st->pwr_cfg.suspend_on_ac = !st->pwr_cfg.suspend_on_ac; + save_power_cfg(st, st->pwr_cfg.suspend_on_ac ? "Suspend on AC: On" : "Suspend on AC: Off"); + gemui_request_redraw(app); } else if (hit->id == HIT_QUIT) { + if (st->confirm_sec > 0) confirm_revert(st); gemui_quit(app, 0); } } -int main(void) { +int main(int argc, char **argv) { + bool force_arrange = false; + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--arrange") == 0) force_arrange = true; + } disp_state_t st; memset(&st, 0, sizeof(st)); - st.app = gemui_create("anode-display", "ANODE Display & Scaling", 840, 560, false); + st.app = gemui_create("anode-display", "ANODE Display & Arrangement", 920, 620, false); if (!st.app) return 1; scan_outputs(&st); + st.tab = (force_arrange || st.n_outs > 1) ? TAB_ARRANGE : TAB_SCALING; gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr }; gemui_set_handlers(st.app, &h, &st); int rc = gemui_run(st.app); diff --git a/src/apps/anode-lock.c b/src/apps/anode-lock.c index 89f362c..cdf60c7 100644 --- a/src/apps/anode-lock.c +++ b/src/apps/anode-lock.c @@ -15,9 +15,7 @@ typedef struct { gemui_app_t *app; char pw[128]; char user[64]; - char host[64]; char msg[96]; - anode_battery_info_t bat; } lock_state_t; enum { HIT_UNLOCK = 1, HIT_VKBD }; @@ -79,19 +77,30 @@ static void try_unlock(lock_state_t *st) { } static void on_timer(gemui_app_t *app, void *ud) { - lock_state_t *st = (lock_state_t *)ud; - anode_read_battery(&st->bat); + (void)ud; gemui_request_redraw(app); } static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { lock_state_t *st = (lock_state_t *)ud; const gemui_theme_t *t = gemui_theme(app); + (void)w; + (void)h; - int card_w = gemui_scale_px(app, 380); - if (card_w > w - gemui_scale_px(app, 32)) card_w = w - gemui_scale_px(app, 32); - int card_h = gemui_scale_px(app, 250); - gemui_rect_t card = {(w - card_w) / 2, (h - card_h) / 2, card_w, card_h}; + gemui_rect_t mon = gemui_primary_monitor_rect(app); + int pad = gemui_scale_px(app, 18); + int clk_h = gemui_scale_px(app, 38); + int gap_sm = gemui_scale_px(app, 6); + int date_h = gemui_scale_px(app, 22); + int gap_md = gemui_scale_px(app, 12); + int in_h = gemui_touch_row_px(app, 38); + int msg_h = gemui_scale_px(app, 22); + int btn_h = gemui_touch_row_px(app, 34); + + int card_w = gemui_scale_px(app, 360); + if (card_w > mon.w - gemui_scale_px(app, 32)) card_w = mon.w - gemui_scale_px(app, 32); + int card_h = pad + clk_h + gap_sm + date_h + gap_md + in_h + gap_sm + msg_h + gap_sm + btn_h + pad; + gemui_rect_t card = {mon.x + (mon.w - card_w) / 2, mon.y + (mon.h - card_h) / 2, card_w, card_h}; gemui_fill_round(cr, card, (double)gemui_scale_px(app, 10), t->bg_overlay); gemui_stroke_round(cr, card, (double)gemui_scale_px(app, 10), 2.0, t->accent); @@ -100,37 +109,27 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { localtime_r(&now, &tmb); char cstr[32], dstr[64]; strftime(cstr, sizeof(cstr), "%H:%M:%S", &tmb); - strftime(dstr, sizeof(dstr), "%A, %Y-%m-%d", &tmb); + strftime(dstr, sizeof(dstr), "%a, %Y-%m-%d", &tmb); - int pad = gemui_scale_px(app, 18); int y = card.y + pad; - gemui_draw_text(cr, t, (gemui_rect_t){card.x + pad, y, card.w - pad * 2, gemui_scale_px(app, 38)}, + gemui_draw_text(cr, t, (gemui_rect_t){card.x + pad, y, card.w - pad * 2, clk_h}, cstr, 10, true, GEMUI_ALIGN_CENTER, t->fg_bright); - y += gemui_scale_px(app, 40); + y += clk_h + gap_sm; - char sub[256]; - if (st->bat.present && st->bat.capacity >= 0) { - snprintf(sub, sizeof(sub), "%s | %s@%s | %d%% %s", dstr, st->user, st->host, - st->bat.capacity, st->bat.on_ac ? "AC" : "BAT"); - } else { - snprintf(sub, sizeof(sub), "%s | %s@%s", dstr, st->user, st->host); - } - gemui_draw_text(cr, t, (gemui_rect_t){card.x + pad, y, card.w - pad * 2, gemui_scale_px(app, 24)}, - sub, -2, false, GEMUI_ALIGN_CENTER, t->fg_muted); - y += gemui_scale_px(app, 34); + gemui_draw_text(cr, t, (gemui_rect_t){card.x + pad, y, card.w - pad * 2, date_h}, + dstr, -1, false, GEMUI_ALIGN_CENTER, t->fg_muted); + y += date_h + gap_md; - int in_h = gemui_touch_row_px(app, 38); gemui_draw_input(app, cr, (gemui_rect_t){card.x + pad, y, card.w - pad * 2, in_h}, "Password...", st->pw, true, true, -1, 0); - y += in_h + gemui_scale_px(app, 14); + y += in_h + gap_sm; if (st->msg[0]) { - gemui_draw_text(cr, t, (gemui_rect_t){card.x + pad, y, card.w - pad * 2, gemui_scale_px(app, 22)}, + gemui_draw_text(cr, t, (gemui_rect_t){card.x + pad, y, card.w - pad * 2, msg_h}, st->msg, -1, false, GEMUI_ALIGN_CENTER, t->danger); } - y += gemui_scale_px(app, 28); + y += msg_h + gap_sm; - int btn_h = gemui_touch_row_px(app, 34); int half = (card.w - pad * 3) / 2; gemui_draw_button(app, cr, (gemui_rect_t){card.x + pad, y, half, btn_h}, "Keyboard", HIT_VKBD, 0, false, false, false); @@ -181,8 +180,6 @@ int main(void) { memset(&st, 0, sizeof(st)); struct passwd *pw = getpwuid(getuid()); snprintf(st.user, sizeof(st.user), "%s", (pw && pw->pw_name) ? pw->pw_name : "user"); - if (gethostname(st.host, sizeof(st.host) - 1) != 0) snprintf(st.host, sizeof(st.host), "anode"); - anode_read_battery(&st.bat); st.app = gemui_create("anode-lock", "ANODE Lock", 0, 0, true); if (!st.app) return 1; diff --git a/src/apps/anode-power.c b/src/apps/anode-power.c index 8769faf..4456d06 100644 --- a/src/apps/anode-power.c +++ b/src/apps/anode-power.c @@ -1,6 +1,7 @@ #define _POSIX_C_SOURCE 200809L #include "gemui.h" #include "anode_plat.h" +#include "anode_power_policy.h" #include #include @@ -10,11 +11,15 @@ typedef struct { gemui_app_t *app; anode_battery_info_t bat; + anode_power_cfg_t pwr_cfg; int bri_pct; int vol_pct; bool muted; char prof[32]; int focus_idx; + bool dragging_vol; + bool dragging_bri; + gemui_rect_t drag_rect; } pwr_state_t; enum { @@ -22,10 +27,16 @@ enum { HIT_VOL_MUTE, HIT_BRI_SLIDER, HIT_PROF, + HIT_DIM_STEP, + HIT_LOCK_STEP, + HIT_SUSP_STEP, + HIT_SUSP_AC, HIT_TOOL, HIT_ACT }; +#define PWR_FOCUS_COUNT 21 + static const char *PROFILES[] = {"power-saver", "balanced", "performance"}; static const char *TOOLS[][2] = { {"Network", "anode-net"}, @@ -43,8 +54,29 @@ static const char *ACTIONS[][2] = { {"Power Off", "poweroff"} }; +static void load_power_cfg(pwr_state_t *st) { + char cdir[512], path[576]; + anode_config_dir(cdir, sizeof(cdir)); + snprintf(path, sizeof(path), "%s/power.conf", cdir); + anode_power_cfg_load(path, &st->pwr_cfg); +} + +static void save_power_cfg(pwr_state_t *st, const char *toast_msg) { + char cdir[512], path[576]; + anode_config_dir(cdir, sizeof(cdir)); + snprintf(path, sizeof(path), "%s/power.conf", cdir); + if (anode_power_cfg_save(path, &st->pwr_cfg)) { + const char *pd[] = {"anode-powerd"}; + anode_signal_procs(pd, 1, SIGUSR1); + gemui_show_toast(st->app, toast_msg, 1800); + } else { + gemui_show_toast(st->app, "Failed to save power.conf", 2200); + } +} + static void refresh_state(pwr_state_t *st) { anode_read_battery(&st->bat); + load_power_cfg(st); int cur = 50, maxv = 100; if (anode_backlight_get(&cur, &maxv, NULL, 0) && maxv > 0) { st->bri_pct = (cur * 100 + maxv / 2) / maxv; @@ -60,6 +92,86 @@ static void refresh_state(pwr_state_t *st) { } } +static void draw_timeout_stepper(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *label, uint32_t ms, int hit_id, bool focused) { + const gemui_theme_t *t = gemui_theme(app); + double rad = (double)gemui_scale_px(app, 6); + double lw = focused ? (t->scale >= 1.5 ? 2.5 : 2.0) : (t->scale >= 1.5 ? 1.5 : 1.0); + gemui_fill_round(cr, r, rad, t->bg_alt_even); + gemui_stroke_round(cr, r, rad, lw, focused ? t->accent : t->border); + + int pad_x = gemui_scale_px(app, 10); + int gap = gemui_scale_px(app, 4); + int pad_y = gemui_scale_px(app, 4); + int bh = r.h - pad_y * 2; + if (bh < gemui_scale_px(app, 20)) bh = r.h - 4; + int bw = bh; + if (bw < gemui_scale_px(app, 28)) bw = gemui_scale_px(app, 28); + int vw = gemui_scale_px(app, 48); + int ctrl_w = bw * 2 + vw + gap * 2; + + gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad_x, r.y, r.w - ctrl_w - pad_x * 2, r.h}, + label, 0, false, GEMUI_ALIGN_LEFT, t->fg_main); + + int cx = r.x + r.w - pad_x - ctrl_w; + int by = r.y + (r.h - bh) / 2; + gemui_draw_button(app, cr, (gemui_rect_t){cx, by, bw, bh}, "-", hit_id, -1, false, false, false); + + char vtxt[16]; + anode_power_format_timeout(ms, vtxt, sizeof(vtxt)); + gemui_draw_text(cr, t, (gemui_rect_t){cx + bw + gap, r.y, vw, r.h}, + vtxt, 0, true, GEMUI_ALIGN_CENTER, + ms > 0U ? t->fg_bright : t->fg_muted); + + gemui_draw_button(app, cr, (gemui_rect_t){cx + bw + gap + vw + gap, by, bw, bh}, + "+", hit_id, 1, false, false, false); +} + +static bool adjust_timeout_hit(pwr_state_t *st, int hit_id, int dir) { + struct { + int hit; + uint32_t *field; + const char *label; + bool is_susp; + } items[3] = { + {HIT_DIM_STEP, &st->pwr_cfg.dim_ms, "Dim brightness after", false}, + {HIT_LOCK_STEP, &st->pwr_cfg.lock_ms, "Lock screen after", false}, + {HIT_SUSP_STEP, &st->pwr_cfg.suspend_ms, "Auto suspend after", true} + }; + for (int i = 0; i < 3; i++) { + if (items[i].hit == hit_id) { + *items[i].field = items[i].is_susp + ? anode_power_step_suspend_timeout_ms(*items[i].field, dir) + : anode_power_step_screen_timeout_ms(*items[i].field, dir); + char vtxt[16], msg[64]; + anode_power_format_timeout(*items[i].field, vtxt, sizeof(vtxt)); + snprintf(msg, sizeof(msg), "%s: %s", items[i].label, vtxt); + save_power_cfg(st, msg); + return true; + } + } + return false; +} + +static void toggle_timeout_default(pwr_state_t *st, int focus_idx) { + struct { + uint32_t *field; + uint32_t def_ms; + const char *label; + } items[3] = { + {&st->pwr_cfg.dim_ms, 300000U, "Dim brightness after"}, + {&st->pwr_cfg.lock_ms, 600000U, "Lock screen after"}, + {&st->pwr_cfg.suspend_ms, 1800000U, "Auto suspend after"} + }; + int idx = focus_idx - 6; + if (idx < 0 || idx >= 3) return; + *items[idx].field = (*items[idx].field > 0U) ? 0U : items[idx].def_ms; + char vtxt[16], msg[64]; + anode_power_format_timeout(*items[idx].field, vtxt, sizeof(vtxt)); + snprintf(msg, sizeof(msg), "%s: %s", items[idx].label, vtxt); + save_power_cfg(st, msg); +} + static void on_timer(gemui_app_t *app, void *ud) { pwr_state_t *st = (pwr_state_t *)ud; refresh_state(st); @@ -118,7 +230,7 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { y += slider_h + pad; /* Power profile row */ - int row_h = gemui_touch_row_px(app, 36); + int row_h = gemui_touch_row_px(app, 34); int pw = (cw - pad * 2) / 3; for (int i = 0; i < 3; i++) { bool act = (strcmp(st->prof, PROFILES[i]) == 0); @@ -127,13 +239,33 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { } y += row_h + pad; + /* Screen & idle timeouts */ + const gemui_theme_t *t = gemui_theme(app); + int lbl_h = gemui_scale_px(app, 20); + gemui_draw_text(cr, t, (gemui_rect_t){pad, y, cw, lbl_h}, + "Screen & Idle Timeouts", -1, true, GEMUI_ALIGN_LEFT, t->fg_muted); + y += lbl_h + pad / 3; + + int gap = gemui_scale_px(app, 8); + int iw = (cw - pad) / 2; + draw_timeout_stepper(app, cr, (gemui_rect_t){pad, y, iw, row_h}, + "Dim Brightness", st->pwr_cfg.dim_ms, HIT_DIM_STEP, st->focus_idx == 6); + draw_timeout_stepper(app, cr, (gemui_rect_t){pad + iw + pad, y, iw, row_h}, + "Lock Screen", st->pwr_cfg.lock_ms, HIT_LOCK_STEP, st->focus_idx == 7); + y += row_h + gap; + draw_timeout_stepper(app, cr, (gemui_rect_t){pad, y, iw, row_h}, + "Auto Suspend", st->pwr_cfg.suspend_ms, HIT_SUSP_STEP, st->focus_idx == 8); + gemui_draw_toggle(app, cr, (gemui_rect_t){pad + iw + pad, y, iw, row_h}, + "Suspend on AC", st->pwr_cfg.suspend_on_ac, HIT_SUSP_AC, 0, st->focus_idx == 9); + y += row_h + pad; + /* Quick utilities grid */ int cols = 3; int tw = (cw - pad * (cols - 1)) / cols; for (int i = 0; i < 6; i++) { int r = i / cols, c = i % cols; gemui_draw_button(app, cr, (gemui_rect_t){pad + c * (tw + pad), y + r * (row_h + pad / 2), tw, row_h}, - TOOLS[i][0], HIT_TOOL, i, false, false, st->focus_idx == 6 + i); + TOOLS[i][0], HIT_TOOL, i, false, false, st->focus_idx == 10 + i); } /* Bottom power actions bar */ @@ -141,7 +273,32 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { int ay = h - row_h - pad; for (int i = 0; i < 5; i++) { gemui_draw_button(app, cr, (gemui_rect_t){pad + i * (aw + pad), ay, aw, row_h}, - ACTIONS[i][0], HIT_ACT, i, i == 0, false, st->focus_idx == 12 + i); + ACTIONS[i][0], HIT_ACT, i, i == 0, false, st->focus_idx == 16 + i); + } +} + +static void apply_vol_at_x(pwr_state_t *st, int x, gemui_rect_t r, bool signal_statusd) { + int pct = ((x - r.x) * 100) / (r.w > 0 ? r.w : 1); + if (pct < 0) pct = 0; + if (pct > 100) pct = 100; + st->vol_pct = pct; + anode_audio_set_vol(false, pct); + if (signal_statusd) { + const char *ns[] = {"anode-statusd"}; + anode_signal_procs(ns, 1, SIGUSR1); + } +} + +static void apply_bri_at_x(pwr_state_t *st, int x, gemui_rect_t r, bool priv_fallback) { + int pct = ((x - r.x) * 100) / (r.w > 0 ? r.w : 1); + if (pct < 5) pct = 5; + if (pct > 100) pct = 100; + st->bri_pct = pct; + if (!anode_backlight_set((double)pct / 100.0) && priv_fallback) { + char pbuf[16]; + snprintf(pbuf, sizeof(pbuf), "%d", pct); + const char *av[] = {"anode-power-ctl", "backlight", pbuf, NULL}; + anode_run_priv_timeout(av, NULL, 0, 2000); } } @@ -150,13 +307,14 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char * pwr_state_t *st = (pwr_state_t *)ud; if (ks == XK_Escape || ks == XK_q) { gemui_quit(app, 0); return; } if (ks == XK_Tab || ks == XK_Down || ks == XK_j) { - st->focus_idx = (st->focus_idx + ((state & ShiftMask) ? 16 : 1)) % 17; + st->focus_idx = (st->focus_idx + ((state & ShiftMask) ? (PWR_FOCUS_COUNT - 1) : 1)) % PWR_FOCUS_COUNT; gemui_request_redraw(app); } else if (ks == XK_Up || ks == XK_k) { - st->focus_idx = (st->focus_idx + 16) % 17; + st->focus_idx = (st->focus_idx + PWR_FOCUS_COUNT - 1) % PWR_FOCUS_COUNT; gemui_request_redraw(app); } else if (ks == XK_Left || ks == XK_h || ks == XK_Right || ks == XK_l) { - int d = (ks == XK_Right || ks == XK_l) ? 5 : -5; + int dir = (ks == XK_Right || ks == XK_l) ? 1 : -1; + int d = dir * 5; if (st->focus_idx == 0) { int nv = st->vol_pct + d; if (nv < 0) nv = 0; @@ -169,10 +327,24 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char * int nb = st->bri_pct + d; if (nb < 5) nb = 5; if (nb > 100) nb = 100; - anode_backlight_set((double)nb / 100.0); + if (!anode_backlight_set((double)nb / 100.0)) { + char pbuf[16]; + snprintf(pbuf, sizeof(pbuf), "%d", nb); + const char *av[] = {"anode-power-ctl", "backlight", pbuf, NULL}; + anode_run_priv_timeout(av, NULL, 0, 2000); + } refresh_state(st); + } else if (st->focus_idx == 6) { + adjust_timeout_hit(st, HIT_DIM_STEP, dir); + } else if (st->focus_idx == 7) { + adjust_timeout_hit(st, HIT_LOCK_STEP, dir); + } else if (st->focus_idx == 8) { + adjust_timeout_hit(st, HIT_SUSP_STEP, dir); + } else if (st->focus_idx == 9) { + st->pwr_cfg.suspend_on_ac = !st->pwr_cfg.suspend_on_ac; + save_power_cfg(st, st->pwr_cfg.suspend_on_ac ? "Suspend on AC: On" : "Suspend on AC: Off"); } else { - st->focus_idx = (st->focus_idx + (d > 0 ? 1 : 16)) % 17; + st->focus_idx = (st->focus_idx + (dir > 0 ? 1 : PWR_FOCUS_COUNT - 1)) % PWR_FOCUS_COUNT; } gemui_request_redraw(app); } else if (ks == XK_Return || ks == XK_space) { @@ -186,8 +358,13 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char * const char *av[] = {"anode-power-ctl", "profile", PROFILES[pi], NULL}; if (anode_run_priv_timeout(av, NULL, 0, 2000) == 0) snprintf(st->prof, sizeof(st->prof), "%s", PROFILES[pi]); } - } else if (st->focus_idx >= 6 && st->focus_idx <= 11) { - int ti = st->focus_idx - 6; + } else if (st->focus_idx >= 6 && st->focus_idx <= 8) { + toggle_timeout_default(st, st->focus_idx); + } else if (st->focus_idx == 9) { + st->pwr_cfg.suspend_on_ac = !st->pwr_cfg.suspend_on_ac; + save_power_cfg(st, st->pwr_cfg.suspend_on_ac ? "Suspend on AC: On" : "Suspend on AC: Off"); + } else if (st->focus_idx >= 10 && st->focus_idx <= 15) { + int ti = st->focus_idx - 10; if (strcmp(TOOLS[ti][1], "vkbd-toggle") == 0) { const char *av[] = {"anode-media-key", "vkbd-toggle", NULL}; anode_spawn_detached(av); @@ -195,8 +372,8 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char * const char *av[] = {TOOLS[ti][1], NULL}; anode_spawn_detached(av); } - } else if (st->focus_idx >= 12) { - do_action(st, st->focus_idx - 12); + } else if (st->focus_idx >= 16) { + do_action(st, st->focus_idx - 16); } gemui_request_redraw(app); } @@ -204,25 +381,44 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char * static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { pwr_state_t *st = (pwr_state_t *)ud; + if (type == GEMUI_PTR_MOVE) { + if (st->dragging_vol) { + apply_vol_at_x(st, x, st->drag_rect, false); + gemui_request_redraw(app); + } else if (st->dragging_bri) { + apply_bri_at_x(st, x, st->drag_rect, false); + gemui_request_redraw(app); + } + return; + } + if (type == GEMUI_PTR_UP) { + bool handled = st->dragging_vol || st->dragging_bri; + if (st->dragging_vol) { + st->dragging_vol = false; + apply_vol_at_x(st, x, st->drag_rect, true); + } + if (st->dragging_bri) { + st->dragging_bri = false; + apply_bri_at_x(st, x, st->drag_rect, true); + } + if (handled) { + refresh_state(st); + gemui_request_redraw(app); + } + return; + } if (type != GEMUI_PTR_DOWN || btn != Button1) return; const gemui_hit_t *hit = gemui_hit_test(app, x, y); if (!hit) return; - if (hit->id == HIT_VOL_SLIDER || hit->id == HIT_BRI_SLIDER) { - int pct = ((x - hit->r.x) * 100) / (hit->r.w > 0 ? hit->r.w : 1); - if (pct < 1) pct = 1; - if (pct > 100) pct = 100; - if (hit->id == HIT_VOL_SLIDER) { - anode_audio_set_vol(false, pct); - const char *ns[] = {"anode-statusd"}; - anode_signal_procs(ns, 1, SIGUSR1); - } else { - if (!anode_backlight_set((double)pct / 100.0)) { - char pbuf[16]; - snprintf(pbuf, sizeof(pbuf), "%d", pct); - const char *av[] = {"anode-power-ctl", "backlight", pbuf, NULL}; - anode_run_priv_timeout(av, NULL, 0, 2000); - } - } + if (hit->id == HIT_VOL_SLIDER) { + st->dragging_vol = true; + st->drag_rect = hit->r; + apply_vol_at_x(st, x, hit->r, true); + refresh_state(st); + } else if (hit->id == HIT_BRI_SLIDER) { + st->dragging_bri = true; + st->drag_rect = hit->r; + apply_bri_at_x(st, x, hit->r, true); refresh_state(st); } else if (hit->id == HIT_VOL_MUTE) { anode_audio_toggle_mute(false); @@ -234,6 +430,11 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v anode_run_priv_timeout(av, NULL, 0, 2000); } refresh_state(st); + } else if (adjust_timeout_hit(st, hit->id, hit->val)) { + /* Handled and saved */ + } else if (hit->id == HIT_SUSP_AC) { + st->pwr_cfg.suspend_on_ac = !st->pwr_cfg.suspend_on_ac; + save_power_cfg(st, st->pwr_cfg.suspend_on_ac ? "Suspend on AC: On" : "Suspend on AC: Off"); } else if (hit->id == HIT_TOOL) { if (strcmp(TOOLS[hit->val][1], "vkbd-toggle") == 0) { const char *av[] = {"anode-media-key", "vkbd-toggle", NULL}; @@ -251,7 +452,7 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v int main(void) { pwr_state_t st; memset(&st, 0, sizeof(st)); - st.app = gemui_create("anode-power", "ANODE Control Center", 760, 480, false); + st.app = gemui_create("anode-power", "ANODE Control Center", 780, 580, false); if (!st.app) return 1; refresh_state(&st); gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr }; diff --git a/src/apps/anode-themes.c b/src/apps/anode-themes.c index 64762e0..6ffe395 100644 --- a/src/apps/anode-themes.c +++ b/src/apps/anode-themes.c @@ -1,30 +1,116 @@ #define _POSIX_C_SOURCE 200809L #include "gemui.h" #include "anode_plat.h" +#include "anode_xth.h" +#include #include #include #include #include +#include +#include -#define MAX_THEMES 64 +#define MAX_THEMES 128 +#define MAX_DIR_ITEMS 256 + +enum { VIEW_BROWSE = 0, VIEW_EDITOR = 1, VIEW_IMPORT = 2 }; +enum { ED_TAB_GEN = 0, ED_TAB_UI = 1, ED_TAB_WM = 2, ED_TAB_TERM = 3 }; typedef struct { char name[64]; char path[512]; gemui_theme_t preview; + bool is_user; + bool has_sys; } theme_entry_t; +typedef struct { + char name[260]; + bool is_dir; +} dir_item_t; + typedef struct { gemui_app_t *app; + int view; + + /* Browse view */ theme_entry_t themes[MAX_THEMES]; int count; int sel; int scroll; char active_name[64]; + char filter[64]; + + /* Active text input */ + int focus_id; + char *focus_buf; + size_t focus_cap; + + /* Editor view */ + anode_xth_t ed_xth; + anode_xth_t ed_orig; + int ed_tab; + int ed_color_idx; + int ed_scroll; + int ed_r, ed_g, ed_b; + char ed_hex[16]; + bool ed_auto_sync; + bool ed_is_new; + int ed_drag_chan; /* 0=none, 1=R, 2=G, 3=B */ + gemui_rect_t ed_slider_rect[3]; + + /* Import view */ + char imp_dir[512]; + char imp_path[800]; + char imp_name[64]; + bool imp_show_all; + dir_item_t imp_items[MAX_DIR_ITEMS]; + int imp_count; + int imp_sel; + int imp_scroll; + anode_xth_t imp_preview; + bool imp_valid; } themes_state_t; -enum { HIT_ROW = 1, HIT_APPLY, HIT_QUIT }; +enum { + HIT_FILTER = 1, + HIT_ROW, + HIT_APPLY, + HIT_EDIT, + HIT_DUPLICATE, + HIT_NEW, + HIT_OPEN_IMPORT, + HIT_DELETE, + HIT_QUIT, + + HIT_ED_TAB, + HIT_ED_FIELD, + HIT_ED_DARK, + HIT_ED_FONTSZ, + HIT_ED_BORDERPX, + HIT_ED_AUTOSYNC, + HIT_ED_SLOT, + HIT_ED_HEX, + HIT_ED_PASTE_HEX, + HIT_ED_SLIDER_R, + HIT_ED_SLIDER_G, + HIT_ED_SLIDER_B, + HIT_ED_SAVE, + HIT_ED_SAVE_APPLY, + HIT_ED_REVERT, + HIT_ED_BACK, + + HIT_IMP_PATH, + HIT_IMP_PASTE_PATH, + HIT_IMP_QUICK_DIR, + HIT_IMP_TOGGLE_ALL, + HIT_IMP_ITEM, + HIT_IMP_NAME, + HIT_IMP_DO, + HIT_IMP_DO_APPLY, + HIT_IMP_BACK +}; static int cmp_theme_entry(const void *a, const void *b) { const theme_entry_t *ta = (const theme_entry_t *)a; @@ -32,12 +118,95 @@ static int cmp_theme_entry(const void *a, const void *b) { return strcmp(ta->name, tb->name); } -static void scan_dir(themes_state_t *st, const char *dir) { +static int cmp_dir_item(const void *a, const void *b) { + const dir_item_t *da = (const dir_item_t *)a; + const dir_item_t *db = (const dir_item_t *)b; + if (da->is_dir != db->is_dir) return da->is_dir ? -1 : 1; + return strcmp(da->name, db->name); +} + +static bool ci_contains(const char *hay, const char *needle) { + if (!needle || !needle[0]) return true; + if (!hay || !hay[0]) return false; + size_t nlen = strlen(needle); + for (const char *p = hay; *p; p++) { + size_t i = 0; + while (i < nlen && p[i] && tolower((unsigned char)p[i]) == tolower((unsigned char)needle[i])) i++; + if (i == nlen) return true; + } + return false; +} + +static void mkdir_p_user(const char *dir) { + char tmp[512]; + snprintf(tmp, sizeof(tmp), "%s", dir); + size_t n = strlen(tmp); + if (n > 1 && tmp[n - 1] == '/') tmp[n - 1] = '\0'; + for (char *p = tmp + 1; *p; p++) { + if (*p == '/') { + *p = '\0'; + mkdir(tmp, 0755); + *p = '/'; + } + } + mkdir(tmp, 0755); +} + +static void user_themes_dir(char *buf, size_t sz) { + char cfg[480]; + anode_config_dir(cfg, sizeof(cfg)); + snprintf(buf, sz, "%s/themes", cfg); +} + +static void set_focus_input(themes_state_t *st, int id, char *buf, size_t cap) { + st->focus_id = id; + st->focus_buf = buf; + st->focus_cap = cap; +} + +static void build_preview_from_xth(const anode_xth_t *x, gemui_theme_t *gt) { + gemui_theme_defaults(gt); + snprintf(gt->name, sizeof(gt->name), "%s", x->name); + snprintf(gt->font_face, sizeof(gt->font_face), "%s", x->font_face[0] ? x->font_face : "Fira Code"); + snprintf(gt->icon_font_face, sizeof(gt->icon_font_face), "%s", + x->icon_font_face[0] ? x->icon_font_face : "DejaVuSansM Nerd Font"); + gemui_color_parse(x->colors[ANODE_XTH_BG_MAIN], >->bg_main); + gemui_color_parse(x->colors[ANODE_XTH_BG_BAR], >->bg_bar); + gemui_color_parse(x->colors[ANODE_XTH_BG_HEADER], >->bg_header); + gemui_color_parse(x->colors[ANODE_XTH_BG_FOOTER], >->bg_footer); + gemui_color_parse(x->colors[ANODE_XTH_BG_OVERLAY], >->bg_overlay); + gemui_color_parse(x->colors[ANODE_XTH_BG_ALT_EVEN], >->bg_alt_even); + gemui_color_parse(x->colors[ANODE_XTH_BG_ALT_ODD], >->bg_alt_odd); + gemui_color_parse(x->colors[ANODE_XTH_BG_INPUT], >->bg_input); + gemui_color_parse(x->colors[ANODE_XTH_BG_INPUT_FOCUS], >->bg_input_focus); + gemui_color_parse(x->colors[ANODE_XTH_BG_BUTTON], >->bg_button); + gemui_color_parse(x->colors[ANODE_XTH_BG_SEARCH], >->bg_search); + gemui_color_parse(x->colors[ANODE_XTH_BG_BUBBLE_IN], >->bg_bubble_in); + gemui_color_parse(x->colors[ANODE_XTH_BG_BUBBLE_OUT], >->bg_bubble_out); + gemui_color_parse(x->colors[ANODE_XTH_BG_TOAST], >->bg_toast); + gemui_color_parse(x->colors[ANODE_XTH_FG_MAIN], >->fg_main); + gemui_color_parse(x->colors[ANODE_XTH_FG_BRIGHT], >->fg_bright); + gemui_color_parse(x->colors[ANODE_XTH_FG_MUTED], >->fg_muted); + gemui_color_parse(x->colors[ANODE_XTH_SEL_BG], >->sel_bg); + gemui_color_parse(x->colors[ANODE_XTH_SEL_FG], >->sel_fg); + gemui_color_parse(x->colors[ANODE_XTH_ACCENT], >->accent); + gemui_color_parse(x->colors[ANODE_XTH_ACCENT_ALT], >->accent_alt); + gemui_color_parse(x->colors[ANODE_XTH_HIGHLIGHT], >->highlight); + gemui_color_parse(x->colors[ANODE_XTH_BORDER], >->border); + gemui_color_parse(x->colors[ANODE_XTH_DIVIDER], >->divider); + gemui_color_parse(x->colors[ANODE_XTH_SUCCESS], >->success); + gemui_color_parse(x->colors[ANODE_XTH_INFO], >->info); + gemui_color_parse(x->colors[ANODE_XTH_WARNING], >->warning); + gemui_color_parse(x->colors[ANODE_XTH_DANGER], >->danger); + gemui_color_parse(x->colors[ANODE_XTH_DANGER_BG], >->danger_bg); +} + +static void scan_dir(themes_state_t *st, const char *dir, bool mark_user) { if (!dir || !dir[0]) return; DIR *d = opendir(dir); if (!d) return; struct dirent *de; - while ((de = readdir(d)) != NULL && st->count < MAX_THEMES) { + while ((de = readdir(d)) != NULL) { size_t len = strlen(de->d_name); if (len < 5 || strcmp(de->d_name + len - 4, ".xth") != 0) continue; char full[512]; @@ -60,51 +229,64 @@ static void scan_dir(themes_state_t *st, const char *dir) { break; } } + if (existing < 0 && st->count >= MAX_THEMES) continue; theme_entry_t *e = (existing >= 0) ? &st->themes[existing] : &st->themes[st->count++]; + if (existing < 0) memset(e, 0, sizeof(*e)); snprintf(e->name, sizeof(e->name), "%s", tname); snprintf(e->path, sizeof(e->path), "%s", full); e->preview = prev; + if (mark_user) e->is_user = true; + else e->has_sys = true; } closedir(d); } -static void reload_themes(themes_state_t *st) { +static void reload_themes(themes_state_t *st, const char *prefer_select) { st->count = 0; - char cfg[512], sysdir[512], udir[544]; - anode_config_dir(cfg, sizeof(cfg)); + char sysdir[512], udir[512]; anode_themes_sys_dir(sysdir, sizeof(sysdir)); + user_themes_dir(udir, sizeof(udir)); - scan_dir(st, sysdir); - scan_dir(st, "data/themes"); + scan_dir(st, sysdir, false); + scan_dir(st, "data/themes", false); const char *home = getenv("HOME"); if (home && home[0]) { - snprintf(udir, sizeof(udir), "%s/.xthemes", home); - scan_dir(st, udir); + char xdir[544]; + snprintf(xdir, sizeof(xdir), "%s/.xthemes", home); + scan_dir(st, xdir, true); } - snprintf(udir, sizeof(udir), "%s/themes", cfg); - scan_dir(st, udir); + scan_dir(st, udir, true); if (st->count > 1) { qsort(st->themes, (size_t)st->count, sizeof(st->themes[0]), cmp_theme_entry); } const gemui_theme_t *cur = gemui_theme(st->app); snprintf(st->active_name, sizeof(st->active_name), "%s", cur ? cur->name : ""); + const char *target = (prefer_select && prefer_select[0]) ? prefer_select : st->active_name; for (int i = 0; i < st->count; i++) { - if (strcmp(st->themes[i].name, st->active_name) == 0) { + if (strcmp(st->themes[i].name, target) == 0) { st->sel = i; break; } } if (st->sel >= st->count) st->sel = st->count > 0 ? st->count - 1 : 0; + if (st->sel < 0) st->sel = 0; +} + +static int apply_path_now(themes_state_t *st, const char *path) { + const char *av[] = {"anode-apply-theme", path, NULL}; + if (anode_run_cmd_timeout(av, NULL, 0, 5000) == 0) { + gemui_theme_reload(st->app); + const gemui_theme_t *cur = gemui_theme(st->app); + snprintf(st->active_name, sizeof(st->active_name), "%s", cur ? cur->name : ""); + return 0; + } + return -1; } static void apply_selected(themes_state_t *st) { if (st->sel < 0 || st->sel >= st->count) return; - const char *av[] = {"anode-apply-theme", st->themes[st->sel].path, NULL}; - if (anode_run_cmd_timeout(av, NULL, 0, 5000) == 0) { - gemui_theme_reload(st->app); - const gemui_theme_t *cur = gemui_theme(st->app); - snprintf(st->active_name, sizeof(st->active_name), "%s", cur ? cur->name : st->themes[st->sel].name); + if (apply_path_now(st, st->themes[st->sel].path) == 0) { char msg[128]; snprintf(msg, sizeof(msg), "Applied %s across DE", st->themes[st->sel].name); gemui_show_toast(st->app, msg, 2000); @@ -114,6 +296,674 @@ static void apply_selected(themes_state_t *st) { gemui_request_redraw(st->app); } +static void ed_sync_picker_from_slot(themes_state_t *st) { + if (st->ed_color_idx < 0 || st->ed_color_idx >= ANODE_XTH_COLOR_COUNT) st->ed_color_idx = 0; + const char *hex = st->ed_xth.colors[st->ed_color_idx]; + anode_xth_parse_hex(hex, &st->ed_r, &st->ed_g, &st->ed_b); + snprintf(st->ed_hex, sizeof(st->ed_hex), "%s", hex); +} + +static void ed_commit_rgb_to_slot(themes_state_t *st) { + anode_xth_format_hex(st->ed_r, st->ed_g, st->ed_b, st->ed_hex, sizeof(st->ed_hex)); + snprintf(st->ed_xth.colors[st->ed_color_idx], 16, "%s", st->ed_hex); + if (st->ed_auto_sync && st->ed_tab == ED_TAB_UI) { + anode_xth_sync_derived(&st->ed_xth); + } +} + +static void ed_tab_slot_range(int tab, int *first, int *last) { + if (tab == ED_TAB_UI) { *first = 0; *last = ANODE_XTH_DANGER_BG; } + else if (tab == ED_TAB_WM) { *first = ANODE_XTH_DWM_NORM_BG; *last = ANODE_XTH_DMENU_OUT_FG; } + else if (tab == ED_TAB_TERM) { *first = ANODE_XTH_ST_BG; *last = ANODE_XTH_ST_COLOR15; } + else { *first = 0; *last = -1; } +} + +static bool name_exists(const themes_state_t *st, const char *name) { + for (int i = 0; i < st->count; i++) { + if (strcmp(st->themes[i].name, name) == 0) return true; + } + return false; +} + +static void make_unique_copy_name(const themes_state_t *st, const char *base, char *out, size_t sz) { + char clean[48]; + anode_xth_sanitize_name(base, clean, sizeof(clean)); + if (!clean[0]) snprintf(clean, sizeof(clean), "Theme"); + snprintf(out, sz, "%s_Copy", clean); + for (int n = 2; name_exists(st, out) && n < 100; n++) { + snprintf(out, sz, "%s_Copy%d", clean, n); + } +} + +static void open_editor(themes_state_t *st, const anode_xth_t *src, bool is_new) { + st->ed_xth = *src; + st->ed_orig = *src; + st->ed_is_new = is_new; + st->ed_auto_sync = true; + st->ed_tab = is_new ? ED_TAB_GEN : ED_TAB_UI; + st->ed_color_idx = ANODE_XTH_BG_MAIN; + st->ed_scroll = 0; + st->ed_drag_chan = 0; + ed_sync_picker_from_slot(st); + st->view = VIEW_EDITOR; + if (is_new) set_focus_input(st, HIT_ED_FIELD, st->ed_xth.name, sizeof(st->ed_xth.name)); + else set_focus_input(st, HIT_ED_HEX, st->ed_hex, sizeof(st->ed_hex)); + gemui_request_redraw(st->app); +} + +static bool editor_save(themes_state_t *st, bool and_apply) { + char clean[64]; + anode_xth_sanitize_name(st->ed_xth.name, clean, sizeof(clean)); + if (!clean[0]) { + gemui_show_toast(st->app, "Enter a valid alphanumeric theme name", 2200); + set_focus_input(st, HIT_ED_FIELD, st->ed_xth.name, sizeof(st->ed_xth.name)); + gemui_request_redraw(st->app); + return false; + } + snprintf(st->ed_xth.name, sizeof(st->ed_xth.name), "%s", clean); + if (st->ed_auto_sync) anode_xth_sync_derived(&st->ed_xth); + + char udir[512], path[592]; + user_themes_dir(udir, sizeof(udir)); + mkdir_p_user(udir); + snprintf(path, sizeof(path), "%s/%s.xth", udir, clean); + if (!anode_xth_save_file(path, &st->ed_xth)) { + gemui_show_toast(st->app, "Failed to write user .xth file", 2200); + return false; + } + reload_themes(st, clean); + if (and_apply) { + if (apply_path_now(st, path) == 0) { + char msg[128]; + snprintf(msg, sizeof(msg), "Saved & applied %s", clean); + gemui_show_toast(st->app, msg, 2200); + } else { + gemui_show_toast(st->app, "Saved theme, but apply failed", 2200); + } + } else { + char msg[128]; + snprintf(msg, sizeof(msg), "Saved %s to ~/.config/anode/themes", clean); + gemui_show_toast(st->app, msg, 2200); + } + gemui_request_redraw(st->app); + return true; +} + +static void expand_tilde(const char *in, char *out, size_t sz) { + if (in[0] == '~' && (in[1] == '/' || in[1] == '\0')) { + const char *home = getenv("HOME"); + if (home && home[0]) { + snprintf(out, sz, "%s%s", home, in + 1); + return; + } + } + snprintf(out, sz, "%s", in); +} + +static void imp_scan_dir(themes_state_t *st, const char *dir) { + char exp[800]; + expand_tilde(dir, exp, sizeof(exp)); + DIR *d = opendir(exp); + if (!d) return; + + snprintf(st->imp_dir, sizeof(st->imp_dir), "%.*s", (int)sizeof(st->imp_dir) - 1, exp); + st->imp_count = 0; + if (strcmp(st->imp_dir, "/") != 0) { + snprintf(st->imp_items[st->imp_count].name, sizeof(st->imp_items[0].name), ".."); + st->imp_items[st->imp_count].is_dir = true; + st->imp_count++; + } + + struct dirent *de; + dir_item_t rest[MAX_DIR_ITEMS]; + int rc = 0; + while ((de = readdir(d)) != NULL && rc < MAX_DIR_ITEMS - 1) { + if (de->d_name[0] == '.') continue; + char full[1024]; + snprintf(full, sizeof(full), "%s/%s", st->imp_dir, de->d_name); + struct stat sb; + if (stat(full, &sb) != 0) continue; + bool is_d = S_ISDIR(sb.st_mode); + if (!is_d && !st->imp_show_all) { + size_t nl = strlen(de->d_name); + if (nl < 5 || strcmp(de->d_name + nl - 4, ".xth") != 0) continue; + } + snprintf(rest[rc].name, sizeof(rest[0].name), "%s", de->d_name); + rest[rc].is_dir = is_d; + rc++; + } + closedir(d); + + if (rc > 1) qsort(rest, (size_t)rc, sizeof(rest[0]), cmp_dir_item); + for (int i = 0; i < rc && st->imp_count < MAX_DIR_ITEMS; i++) { + st->imp_items[st->imp_count++] = rest[i]; + } + st->imp_sel = 0; + st->imp_scroll = 0; +} + +static void imp_refresh_preview(themes_state_t *st, bool update_name) { + char exp[800]; + expand_tilde(st->imp_path, exp, sizeof(exp)); + struct stat sb; + st->imp_valid = false; + if (stat(exp, &sb) == 0 && S_ISREG(sb.st_mode)) { + if (anode_xth_load_file(exp, &st->imp_preview)) { + st->imp_valid = true; + if (update_name) { + snprintf(st->imp_name, sizeof(st->imp_name), "%s", st->imp_preview.name); + } + } + } +} + +static void open_importer(themes_state_t *st) { + const char *home = getenv("HOME"); + if (!st->imp_dir[0]) { + snprintf(st->imp_dir, sizeof(st->imp_dir), "%s", (home && home[0]) ? home : "/"); + } + snprintf(st->imp_path, sizeof(st->imp_path), "%s", st->imp_dir); + st->imp_name[0] = '\0'; + st->imp_valid = false; + imp_scan_dir(st, st->imp_dir); + st->view = VIEW_IMPORT; + set_focus_input(st, HIT_IMP_PATH, st->imp_path, sizeof(st->imp_path)); + gemui_request_redraw(st->app); +} + +static void do_import_now(themes_state_t *st, bool and_apply) { + char exp[800]; + expand_tilde(st->imp_path, exp, sizeof(exp)); + char udir[512], dest[592]; + user_themes_dir(udir, sizeof(udir)); + mkdir_p_user(udir); + + if (!anode_xth_import_file(exp, udir, st->imp_name, dest, sizeof(dest))) { + gemui_show_toast(st->app, "Invalid or unreadable .xth theme file", 2200); + return; + } + anode_xth_t loaded; + char sel_name[64] = ""; + if (anode_xth_load_file(dest, &loaded)) { + snprintf(sel_name, sizeof(sel_name), "%s", loaded.name); + } + reload_themes(st, sel_name); + if (and_apply) { + if (apply_path_now(st, dest) == 0) { + char msg[128]; + snprintf(msg, sizeof(msg), "Imported & applied %s", sel_name); + gemui_show_toast(st->app, msg, 2200); + } else { + gemui_show_toast(st->app, "Imported theme, apply failed", 2200); + } + } else { + char msg[128]; + snprintf(msg, sizeof(msg), "Imported %s to ~/.config/anode/themes", sel_name); + gemui_show_toast(st->app, msg, 2200); + } + st->view = VIEW_BROWSE; + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(st->app); +} + +static void draw_mini_preview(themes_state_t *st, cairo_t *cr, gemui_rect_t r, + const gemui_theme_t *p, const anode_xth_t *xopt) { + const gemui_theme_t *ui = gemui_theme(st->app); + int pad = gemui_scale_px(st->app, 10); + gemui_fill_round(cr, r, (double)gemui_scale_px(st->app, 8), p->bg_main); + gemui_stroke_round(cr, r, (double)gemui_scale_px(st->app, 8), 2.0, p->accent); + + int iy = r.y + pad; + int bar_h = gemui_scale_px(st->app, 26); + + /* Simulated mini DWM bar */ + gemui_fill_round(cr, (gemui_rect_t){r.x + pad, iy, r.w - pad * 2, bar_h}, + (double)gemui_scale_px(st->app, 4), p->bg_bar); + int tag_w = gemui_scale_px(st->app, 26); + gemui_fill_round(cr, (gemui_rect_t){r.x + pad, iy, tag_w, bar_h}, + (double)gemui_scale_px(st->app, 4), p->sel_bg); + gemui_draw_text(cr, ui, (gemui_rect_t){r.x + pad, iy, tag_w, bar_h}, + "1", -1, true, GEMUI_ALIGN_CENTER, p->sel_fg); + gemui_draw_text(cr, ui, (gemui_rect_t){r.x + pad + tag_w + 8, iy, r.w - pad * 2 - tag_w - 12, bar_h}, + p->name, -1, true, GEMUI_ALIGN_LEFT, p->fg_bright); + iy += bar_h + pad / 2; + + /* Sample typography line */ + int lh = gemui_scale_px(st->app, 24); + gemui_draw_text(cr, ui, (gemui_rect_t){r.x + pad, iy, r.w - pad * 2, lh}, + "Fira Code: -> => != === ::", -1, false, GEMUI_ALIGN_LEFT, p->fg_main); + iy += lh; + + /* Color swatches row */ + const gemui_color_t sw[6] = { p->accent, p->sel_bg, p->success, p->warning, p->danger, p->highlight }; + int sw_sz = gemui_scale_px(st->app, 22); + int gap = gemui_scale_px(st->app, 6); + for (int c = 0; c < 6 && (pad + (c + 1) * (sw_sz + gap)) < r.w; c++) { + gemui_fill_round(cr, (gemui_rect_t){r.x + pad + c * (sw_sz + gap), iy, sw_sz, sw_sz}, + (double)gemui_scale_px(st->app, 4), sw[c]); + } + iy += sw_sz + pad / 2; + + /* ANSI 16-color terminal bar when anode_xth_t provided */ + if (xopt && iy + gemui_scale_px(st->app, 36) < r.y + r.h) { + int cols_per_row = 8; + int cw = (r.w - pad * 2 - gap * (cols_per_row - 1)) / cols_per_row; + int ch = gemui_scale_px(st->app, 14); + for (int i = 0; i < 16; i++) { + gemui_color_t ac; + gemui_color_parse(xopt->colors[ANODE_XTH_ST_COLOR0 + i], &ac); + int row = i / 8, col = i % 8; + gemui_fill_round(cr, (gemui_rect_t){r.x + pad + col * (cw + gap), iy + row * (ch + 3), cw, ch}, + 2.0, ac); + } + iy += ch * 2 + 10; + } + + /* Sample button + status */ + if (iy + lh < r.y + r.h) { + gemui_draw_text(cr, ui, (gemui_rect_t){r.x + pad, iy, r.w - pad * 2, lh}, + "Applies to X11, DWM, dmenu, st, GemUI, GTK, Qt", + -2, false, GEMUI_ALIGN_LEFT, p->fg_muted); + } +} + +static void draw_browse_view(themes_state_t *st, cairo_t *cr, int w, int h) { + const gemui_theme_t *t = gemui_theme(st->app); + char badge[96]; + snprintf(badge, sizeof(badge), "Active: %s", st->active_name[0] ? st->active_name : t->name); + gemui_draw_header(st->app, cr, NULL, "ANODE Themes & Editor", badge); + + int hdr_h = gemui_scale_px(st->app, 42); + int pad = gemui_scale_px(st->app, 12); + int btn_h = gemui_touch_row_px(st->app, 32); + int ftr_h = btn_h * 2 + pad + gemui_scale_px(st->app, 8); + int body_y = hdr_h + pad; + int body_h = h - body_y - ftr_h - pad / 2; + int list_w = (w * 43) / 100; + if (list_w < gemui_scale_px(st->app, 220)) list_w = gemui_scale_px(st->app, 220); + + /* Filter box */ + int in_h = gemui_touch_row_px(st->app, 32); + gemui_draw_input(st->app, cr, (gemui_rect_t){pad, body_y, list_w, in_h}, + "Filter themes...", st->filter, false, st->focus_id == HIT_FILTER, HIT_FILTER, 0); + + int ly = body_y + in_h + pad / 2; + int lh = body_h - in_h - pad / 2; + gemui_rect_t list_r = {pad, ly, list_w, lh}; + gemui_fill_round(cr, list_r, (double)gemui_scale_px(st->app, 6), t->bg_alt_even); + gemui_stroke_round(cr, list_r, (double)gemui_scale_px(st->app, 6), 1.0, t->border); + + int vis_indices[MAX_THEMES]; + int vis_cnt = 0; + int sel_vis_pos = 0; + for (int i = 0; i < st->count; i++) { + if (ci_contains(st->themes[i].name, st->filter)) { + if (i == st->sel) sel_vis_pos = vis_cnt; + vis_indices[vis_cnt++] = i; + } + } + + int row_h = gemui_touch_row_px(st->app, 30); + int vis_rows = (lh - pad) / row_h; + if (vis_rows < 1) vis_rows = 1; + if (sel_vis_pos < st->scroll) st->scroll = sel_vis_pos; + if (sel_vis_pos >= st->scroll + vis_rows) st->scroll = sel_vis_pos - vis_rows + 1; + if (st->scroll > vis_cnt - vis_rows) st->scroll = vis_cnt - vis_rows; + if (st->scroll < 0) st->scroll = 0; + + for (int i = 0; i < vis_rows && (st->scroll + i) < vis_cnt; i++) { + int idx = vis_indices[st->scroll + i]; + gemui_rect_t rr = {list_r.x + pad / 2, list_r.y + pad / 2 + i * row_h, list_r.w - pad, row_h - 4}; + bool is_sel = (idx == st->sel); + bool is_act = (strcmp(st->themes[idx].name, st->active_name) == 0); + if (is_sel) gemui_fill_round(cr, rr, (double)gemui_scale_px(st->app, 5), t->sel_bg); + + char lbl[96]; + snprintf(lbl, sizeof(lbl), "%s%s", is_act ? "* " : " ", st->themes[idx].name); + const char *tag = st->themes[idx].is_user ? "[User]" : "[Sys]"; + int tag_w = gemui_scale_px(st->app, 58); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 6, rr.y, rr.w - tag_w - 8, rr.h}, + lbl, 0, is_sel || is_act, GEMUI_ALIGN_LEFT, is_sel ? t->sel_fg : t->fg_main); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + rr.w - tag_w - 4, rr.y, tag_w, rr.h}, + tag, -2, false, GEMUI_ALIGN_RIGHT, is_sel ? t->sel_fg : t->fg_muted); + gemui_hit_add(st->app, rr, HIT_ROW, idx); + } + + /* Preview card */ + int px = list_r.x + list_r.w + pad; + int pw = w - px - pad; + if (st->sel >= 0 && st->sel < st->count && pw > 80) { + anode_xth_t xprev; + bool has_x = anode_xth_load_file(st->themes[st->sel].path, &xprev); + draw_mini_preview(st, cr, (gemui_rect_t){px, body_y, pw, body_h}, + &st->themes[st->sel].preview, has_x ? &xprev : NULL); + } + + /* Footer actions (2 tidy rows) */ + int cw = w - pad * 2; + int fy1 = h - ftr_h; + int fy2 = fy1 + btn_h + gemui_scale_px(st->app, 6); + int bw5 = (cw - (pad / 2) * 4) / 5; + gemui_draw_button(st->app, cr, (gemui_rect_t){pad, fy1, bw5, btn_h}, + "Edit", HIT_EDIT, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (bw5 + pad / 2), fy1, bw5, btn_h}, + "Duplicate", HIT_DUPLICATE, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (bw5 + pad / 2) * 2, fy1, bw5, btn_h}, + "New", HIT_NEW, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (bw5 + pad / 2) * 3, fy1, bw5, btn_h}, + "Import .xth", HIT_OPEN_IMPORT, 0, false, false, false); + const char *del_lbl = (st->sel < st->count && st->themes[st->sel].is_user && st->themes[st->sel].has_sys) + ? "Reset" : "Delete"; + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (bw5 + pad / 2) * 4, fy1, bw5, btn_h}, + del_lbl, HIT_DELETE, 0, false, false, false); + + int abw = gemui_scale_px(st->app, 140); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad * 2 - abw * 2, fy2, abw, btn_h}, + "Apply", HIT_APPLY, 0, true, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - abw, fy2, abw, btn_h}, + "Close", HIT_QUIT, 0, false, false, false); +} + +static void draw_editor_view(themes_state_t *st, cairo_t *cr, int w, int h) { + const gemui_theme_t *t = gemui_theme(st->app); + char badge[96]; + snprintf(badge, sizeof(badge), "Editing: %s", st->ed_xth.name[0] ? st->ed_xth.name : "(unnamed)"); + gemui_draw_header(st->app, cr, NULL, "ANODE Theme Editor", badge); + + int pad = gemui_scale_px(st->app, 12); + int y = gemui_scale_px(st->app, 42) + pad / 2; + int cw = w - pad * 2; + int btn_h = gemui_touch_row_px(st->app, 30); + + /* Editor sub-tabs */ + static const char *TABS[] = {"General & Fonts", "UI Colors", "WM & Menu", "Terminal"}; + int tw = (cw - (pad / 2) * 3) / 4; + for (int i = 0; i < 4; i++) { + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + i * (tw + pad / 2), y, tw, btn_h}, + TABS[i], HIT_ED_TAB, i, false, st->ed_tab == i, false); + } + y += btn_h + pad / 2; + + int ftr_h = btn_h + pad + gemui_scale_px(st->app, 6); + int body_h = h - y - ftr_h - pad / 2; + int left_w = (cw * 46) / 100; + int right_x = pad + left_w + pad; + int right_w = cw - left_w - pad; + + /* Left pane */ + gemui_rect_t left_r = {pad, y, left_w, body_h}; + gemui_fill_round(cr, left_r, (double)gemui_scale_px(st->app, 6), t->bg_alt_even); + gemui_stroke_round(cr, left_r, (double)gemui_scale_px(st->app, 6), 1.0, t->border); + + if (st->ed_tab == ED_TAB_GEN) { + int fy = y + pad / 2; + int in_h = gemui_touch_row_px(st->app, 30); + int lbl_w = gemui_scale_px(st->app, 110); + int fx = pad + pad / 2 + lbl_w; + int fw = left_w - lbl_w - pad; + + const char *flabels[4] = {"Name", "Mono Font", "UI Font", "Icon Font"}; + char *fbufs[4] = {st->ed_xth.name, st->ed_xth.font_face, st->ed_xth.ui_font_face, st->ed_xth.icon_font_face}; + for (int i = 0; i < 4; i++) { + gemui_draw_text(cr, t, (gemui_rect_t){pad + pad / 2, fy, lbl_w - 4, in_h}, + flabels[i], -1, false, GEMUI_ALIGN_LEFT, t->fg_muted); + bool foc = (st->focus_id == HIT_ED_FIELD && st->focus_buf == fbufs[i]); + gemui_draw_input(st->app, cr, (gemui_rect_t){fx, fy, fw, in_h}, flabels[i], fbufs[i], false, foc, HIT_ED_FIELD, i); + fy += in_h + gemui_scale_px(st->app, 8); + } + + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad + pad / 2, fy, left_w - pad, in_h}, + "Dark Palette Variant", st->ed_xth.is_dark != 0, HIT_ED_DARK, 0, false); + fy += in_h + gemui_scale_px(st->app, 8); + + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad + pad / 2, fy, left_w - pad, in_h}, + "Auto-sync DWM / dmenu / st", st->ed_auto_sync, HIT_ED_AUTOSYNC, 0, false); + fy += in_h + gemui_scale_px(st->app, 8); + + /* Steppers: Font size + DWM borderpx */ + int step_w = gemui_scale_px(st->app, 38); + char bsz_lbl[48]; + snprintf(bsz_lbl, sizeof(bsz_lbl), "Base Font Size: %dpx", st->ed_xth.base_font_size); + gemui_draw_text(cr, t, (gemui_rect_t){pad + pad / 2, fy, left_w - pad - step_w * 2 - 12, in_h}, + bsz_lbl, -1, false, GEMUI_ALIGN_LEFT, t->fg_main); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + left_w - pad / 2 - step_w * 2 - 4, fy, step_w, in_h}, + "-", HIT_ED_FONTSZ, -1, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + left_w - pad / 2 - step_w, fy, step_w, in_h}, + "+", HIT_ED_FONTSZ, 1, false, false, false); + fy += in_h + gemui_scale_px(st->app, 8); + + char bpx_lbl[48]; + snprintf(bpx_lbl, sizeof(bpx_lbl), "DWM Border Width: %dpx", st->ed_xth.dwm_borderpx); + gemui_draw_text(cr, t, (gemui_rect_t){pad + pad / 2, fy, left_w - pad - step_w * 2 - 12, in_h}, + bpx_lbl, -1, false, GEMUI_ALIGN_LEFT, t->fg_main); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + left_w - pad / 2 - step_w * 2 - 4, fy, step_w, in_h}, + "-", HIT_ED_BORDERPX, -1, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + left_w - pad / 2 - step_w, fy, step_w, in_h}, + "+", HIT_ED_BORDERPX, 1, false, false, false); + } else { + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + + int ansi_h = 0; + if (st->ed_tab == ED_TAB_TERM) { + /* Draw 2x8 clickable ANSI palette grid at bottom of left pane */ + ansi_h = gemui_scale_px(st->app, 78); + int gx = pad + pad / 2; + int gy = y + body_h - ansi_h; + int gw = (left_w - pad - 7 * 4) / 8; + int gh = gemui_scale_px(st->app, 32); + for (int i = 0; i < 16; i++) { + int slot = ANODE_XTH_ST_COLOR0 + i; + gemui_color_t sc; + gemui_color_parse(st->ed_xth.colors[slot], &sc); + int col = i % 8, row = i / 8; + gemui_rect_t cr_tile = {gx + col * (gw + 4), gy + row * (gh + 4), gw, gh}; + gemui_fill_round(cr, cr_tile, 4.0, sc); + gemui_stroke_round(cr, cr_tile, 4.0, st->ed_color_idx == slot ? 2.0 : 1.0, + st->ed_color_idx == slot ? t->highlight : t->border); + char num[8]; + snprintf(num, sizeof(num), "%d", i); + gemui_color_t num_fg = anode_xth_rel_lum(st->ed_xth.colors[slot]) > 0.35 ? t->bg_main : t->fg_bright; + gemui_draw_text(cr, t, cr_tile, num, -2, true, GEMUI_ALIGN_CENTER, num_fg); + gemui_hit_add(st->app, cr_tile, HIT_ED_SLOT, slot); + } + last = ANODE_XTH_ST_REVCURSOR; + } + + int list_h = body_h - ansi_h - pad / 2; + int total_slots = (last >= first) ? (last - first + 1) : 0; + int row_h = gemui_touch_row_px(st->app, 28); + int vis_rows = (list_h - pad / 2) / row_h; + if (vis_rows < 1) vis_rows = 1; + + int rel_sel = (st->ed_color_idx >= first && st->ed_color_idx <= last) ? (st->ed_color_idx - first) : 0; + if (rel_sel < st->ed_scroll) st->ed_scroll = rel_sel; + if (rel_sel >= st->ed_scroll + vis_rows) st->ed_scroll = rel_sel - vis_rows + 1; + if (st->ed_scroll > total_slots - vis_rows) st->ed_scroll = total_slots - vis_rows; + if (st->ed_scroll < 0) st->ed_scroll = 0; + + int sw_sz = gemui_scale_px(st->app, 20); + for (int i = 0; i < vis_rows && st->ed_scroll + i < total_slots; i++) { + int slot = first + st->ed_scroll + i; + gemui_rect_t rr = {pad + pad / 2, y + pad / 2 + i * row_h, left_w - pad, row_h - 3}; + bool is_sel = (slot == st->ed_color_idx); + if (is_sel) gemui_fill_round(cr, rr, 4.0, t->sel_bg); + + gemui_color_t sc; + gemui_color_parse(st->ed_xth.colors[slot], &sc); + gemui_rect_t sw_r = {rr.x + 6, rr.y + (rr.h - sw_sz) / 2, sw_sz, sw_sz}; + gemui_fill_round(cr, sw_r, 3.0, sc); + gemui_stroke_round(cr, sw_r, 3.0, 1.0, t->border); + + gemui_draw_text(cr, t, (gemui_rect_t){sw_r.x + sw_sz + 8, rr.y, rr.w - sw_sz - 76, rr.h}, + ANODE_XTH_SLOTS[slot].label, -1, is_sel, GEMUI_ALIGN_LEFT, + is_sel ? t->sel_fg : t->fg_main); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + rr.w - 68, rr.y, 64, rr.h}, + st->ed_xth.colors[slot], -2, false, GEMUI_ALIGN_RIGHT, + is_sel ? t->sel_fg : t->fg_muted); + gemui_hit_add(st->app, rr, HIT_ED_SLOT, slot); + } + } + + /* Right pane: Color Picker (top) + Live Preview (bottom) */ + int pick_h = gemui_scale_px(st->app, 232); + if (pick_h > body_h - gemui_scale_px(st->app, 140)) pick_h = body_h - gemui_scale_px(st->app, 140); + gemui_rect_t pick_r = {right_x, y, right_w, pick_h}; + gemui_fill_round(cr, pick_r, (double)gemui_scale_px(st->app, 6), t->bg_alt_even); + gemui_stroke_round(cr, pick_r, (double)gemui_scale_px(st->app, 6), 1.0, t->border); + + int py = y + pad / 2; + int in_h = gemui_touch_row_px(st->app, 28); + int sw_w = gemui_scale_px(st->app, 38); + int paste_w = gemui_scale_px(st->app, 66); + gemui_color_t cur_c; + gemui_color_parse(st->ed_xth.colors[st->ed_color_idx], &cur_c); + gemui_fill_round(cr, (gemui_rect_t){right_x + pad, py, sw_w, in_h}, 4.0, cur_c); + gemui_stroke_round(cr, (gemui_rect_t){right_x + pad, py, sw_w, in_h}, 4.0, 1.0, t->border); + + int hex_x = right_x + pad + sw_w + 8; + int hex_w = gemui_scale_px(st->app, 106); + gemui_draw_input(st->app, cr, (gemui_rect_t){hex_x, py, hex_w, in_h}, + "#RRGGBB", st->ed_hex, false, st->focus_id == HIT_ED_HEX, HIT_ED_HEX, 0); + gemui_draw_button(st->app, cr, (gemui_rect_t){hex_x + hex_w + 6, py, paste_w, in_h}, + "Paste", HIT_ED_PASTE_HEX, 0, false, false, false); + + double cr_bg = anode_xth_contrast_ratio(st->ed_xth.colors[st->ed_color_idx], + st->ed_xth.colors[ANODE_XTH_BG_MAIN]); + char cr_txt[48]; + snprintf(cr_txt, sizeof(cr_txt), "vs bgMain %.1f:1", cr_bg); + gemui_draw_text(cr, t, (gemui_rect_t){hex_x + hex_w + paste_w + 12, py, + right_w - pad * 2 - sw_w - hex_w - paste_w - 20, in_h}, + cr_txt, -2, false, GEMUI_ALIGN_RIGHT, cr_bg >= 4.5 ? t->success : t->fg_muted); + py += in_h + gemui_scale_px(st->app, 6); + + /* RGB Sliders */ + int sli_h = gemui_touch_row_px(st->app, 44); + const int rgb_vals[3] = {st->ed_r, st->ed_g, st->ed_b}; + const char *rgb_names[3] = {"Red (R)", "Green (G)", "Blue (B)"}; + const int rgb_hits[3] = {HIT_ED_SLIDER_R, HIT_ED_SLIDER_G, HIT_ED_SLIDER_B}; + for (int ci = 0; ci < 3; ci++) { + char vtxt[16]; + snprintf(vtxt, sizeof(vtxt), "%d", rgb_vals[ci]); + gemui_rect_t sr = {right_x + pad, py, right_w - pad * 2, sli_h}; + st->ed_slider_rect[ci] = sr; + gemui_draw_slider(st->app, cr, sr, rgb_names[ci], (double)rgb_vals[ci] / 255.0, vtxt, + rgb_hits[ci], ci + 1, st->ed_drag_chan == ci + 1); + py += sli_h + gemui_scale_px(st->app, 6); + } + + /* Live miniature theme preview */ + int prev_y = y + pick_h + pad / 2; + int prev_h = body_h - pick_h - pad / 2; + if (prev_h > gemui_scale_px(st->app, 80)) { + gemui_theme_t live_prev; + build_preview_from_xth(&st->ed_xth, &live_prev); + draw_mini_preview(st, cr, (gemui_rect_t){right_x, prev_y, right_w, prev_h}, &live_prev, &st->ed_xth); + } + + /* Editor Footer */ + int fy = h - btn_h - pad; + int bw = gemui_scale_px(st->app, 124); + int sbw = gemui_scale_px(st->app, 138); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad, fy, bw, btn_h}, + "Back", HIT_ED_BACK, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + bw + pad / 2, fy, bw, btn_h}, + "Revert", HIT_ED_REVERT, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad * 2 - bw - sbw, fy, bw, btn_h}, + "Save", HIT_ED_SAVE, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - sbw, fy, sbw, btn_h}, + "Save & Apply", HIT_ED_SAVE_APPLY, 0, true, false, false); +} + +static void draw_import_view(themes_state_t *st, cairo_t *cr, int w, int h) { + const gemui_theme_t *t = gemui_theme(st->app); + gemui_draw_header(st->app, cr, NULL, "Import .xth Theme File", st->imp_valid ? "Valid .xth" : "Browse or paste path"); + + int pad = gemui_scale_px(st->app, 12); + int y = gemui_scale_px(st->app, 42) + pad / 2; + int cw = w - pad * 2; + int in_h = gemui_touch_row_px(st->app, 32); + + /* Path input + Paste */ + int pw = gemui_scale_px(st->app, 84); + gemui_draw_input(st->app, cr, (gemui_rect_t){pad, y, cw - pw - 8, in_h}, + "/path/to/theme.xth", st->imp_path, false, st->focus_id == HIT_IMP_PATH, HIT_IMP_PATH, 0); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - pw, y, pw, in_h}, + "Paste Path", HIT_IMP_PASTE_PATH, 0, false, false, false); + y += in_h + pad / 2; + + /* Quick directory buttons + filter toggle */ + int qbw = gemui_scale_px(st->app, 96); + const char *qnames[3] = {"Home", "Root /", "User Themes"}; + for (int i = 0; i < 3; i++) { + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + i * (qbw + 6), y, qbw, in_h}, + qnames[i], HIT_IMP_QUICK_DIR, i, false, false, false); + } + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad + (qbw + 6) * 3 + 8, y, gemui_scale_px(st->app, 210), in_h}, + "Show all files", st->imp_show_all, HIT_IMP_TOGGLE_ALL, 0, false); + y += in_h + pad / 2; + + int ftr_h = in_h + pad + gemui_scale_px(st->app, 6); + int body_h = h - y - ftr_h - in_h - pad; + int list_w = (cw * 46) / 100; + gemui_rect_t list_r = {pad, y, list_w, body_h}; + gemui_fill_round(cr, list_r, (double)gemui_scale_px(st->app, 6), t->bg_alt_even); + gemui_stroke_round(cr, list_r, (double)gemui_scale_px(st->app, 6), 1.0, t->border); + + int row_h = gemui_touch_row_px(st->app, 28); + int vis_rows = (body_h - pad) / row_h; + if (vis_rows < 1) vis_rows = 1; + if (st->imp_sel < st->imp_scroll) st->imp_scroll = st->imp_sel; + if (st->imp_sel >= st->imp_scroll + vis_rows) st->imp_scroll = st->imp_sel - vis_rows + 1; + if (st->imp_scroll > st->imp_count - vis_rows) st->imp_scroll = st->imp_count - vis_rows; + if (st->imp_scroll < 0) st->imp_scroll = 0; + + for (int i = 0; i < vis_rows && st->imp_scroll + i < st->imp_count; i++) { + int idx = st->imp_scroll + i; + gemui_rect_t rr = {pad + pad / 2, y + pad / 2 + i * row_h, list_w - pad, row_h - 3}; + bool is_sel = (idx == st->imp_sel); + if (is_sel) gemui_fill_round(cr, rr, 4.0, t->sel_bg); + char lbl[280]; + snprintf(lbl, sizeof(lbl), "%s%s", st->imp_items[idx].is_dir ? "[DIR] " : "", st->imp_items[idx].name); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 8, rr.y, rr.w - 16, rr.h}, + lbl, 0, is_sel || st->imp_items[idx].is_dir, GEMUI_ALIGN_LEFT, + is_sel ? t->sel_fg : (st->imp_items[idx].is_dir ? t->accent : t->fg_main)); + gemui_hit_add(st->app, rr, HIT_IMP_ITEM, idx); + } + + /* Right preview pane */ + int rx = pad + list_w + pad; + int rw = cw - list_w - pad; + gemui_rect_t pr = {rx, y, rw, body_h}; + if (st->imp_valid) { + gemui_theme_t gp; + build_preview_from_xth(&st->imp_preview, &gp); + draw_mini_preview(st, cr, pr, &gp, &st->imp_preview); + } else { + gemui_fill_round(cr, pr, (double)gemui_scale_px(st->app, 6), t->bg_alt_even); + gemui_stroke_round(cr, pr, (double)gemui_scale_px(st->app, 6), 1.0, t->border); + gemui_draw_text(cr, t, pr, "Select or paste a .xth file path to preview", 0, false, GEMUI_ALIGN_CENTER, t->fg_muted); + } + + /* Target name input row */ + int ny = y + body_h + pad / 2; + int nlbl_w = gemui_scale_px(st->app, 118); + gemui_draw_text(cr, t, (gemui_rect_t){pad, ny, nlbl_w, in_h}, + "Install as name", -1, false, GEMUI_ALIGN_LEFT, t->fg_muted); + gemui_draw_input(st->app, cr, (gemui_rect_t){pad + nlbl_w, ny, cw - nlbl_w, in_h}, + "Theme name (optional)", st->imp_name, false, st->focus_id == HIT_IMP_NAME, HIT_IMP_NAME, 0); + + /* Footer */ + int fy = h - in_h - pad; + int bw = gemui_scale_px(st->app, 132); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad, fy, bw, in_h}, + "Back", HIT_IMP_BACK, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad * 2 - bw * 2, fy, bw, in_h}, + "Import", HIT_IMP_DO, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - bw, fy, bw, in_h}, + "Import & Apply", HIT_IMP_DO_APPLY, 0, true, false, false); +} + static void on_theme(gemui_app_t *app, void *ud) { themes_state_t *st = (themes_state_t *)ud; const gemui_theme_t *cur = gemui_theme(app); @@ -122,143 +972,417 @@ static void on_theme(gemui_app_t *app, void *ud) { } static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { + (void)app; themes_state_t *st = (themes_state_t *)ud; - const gemui_theme_t *t = gemui_theme(app); - char badge[96]; - snprintf(badge, sizeof(badge), "Active: %s", st->active_name[0] ? st->active_name : t->name); - gemui_draw_header(app, cr, NULL, "ANODE Themes & Typography", badge); + if (st->view == VIEW_EDITOR) draw_editor_view(st, cr, w, h); + else if (st->view == VIEW_IMPORT) draw_import_view(st, cr, w, h); + else draw_browse_view(st, cr, w, h); +} - int hdr_h = gemui_scale_px(app, 42); - int pad = gemui_scale_px(app, 12); - int ftr_h = gemui_scale_px(app, 44); - int body_y = hdr_h + pad; - int body_h = h - body_y - ftr_h - pad; - int list_w = (w * 42) / 100; - if (list_w < gemui_scale_px(app, 180)) list_w = gemui_scale_px(app, 180); - - gemui_rect_t list_r = {pad, body_y, list_w, body_h}; - gemui_fill_round(cr, list_r, (double)gemui_scale_px(app, 6), t->bg_alt_even); - gemui_stroke_round(cr, list_r, (double)gemui_scale_px(app, 6), 1.0, t->border); - - int row_h = gemui_touch_row_px(app, 32); - int vis_rows = (body_h - pad) / row_h; - if (vis_rows < 1) vis_rows = 1; - if (st->sel < st->scroll) st->scroll = st->sel; - if (st->sel >= st->scroll + vis_rows) st->scroll = st->sel - vis_rows + 1; - - for (int i = 0; i < vis_rows && (st->scroll + i) < st->count; i++) { - int idx = st->scroll + i; - gemui_rect_t rr = {list_r.x + pad / 2, list_r.y + pad / 2 + i * row_h, list_r.w - pad, row_h - 4}; - bool is_sel = (idx == st->sel); - bool is_act = (strcmp(st->themes[idx].name, st->active_name) == 0); - if (is_sel) { - gemui_fill_round(cr, rr, (double)gemui_scale_px(app, 5), t->sel_bg); - } - char lbl[96]; - snprintf(lbl, sizeof(lbl), "%s%s", is_act ? "* " : " ", st->themes[idx].name); - gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 8, rr.y, rr.w - 16, rr.h}, - lbl, 0, is_sel || is_act, GEMUI_ALIGN_LEFT, - is_sel ? t->sel_fg : t->fg_main); - gemui_hit_add(app, rr, HIT_ROW, idx); +static void apply_text_paste(themes_state_t *st) { + if (!st->focus_buf || st->focus_cap < 2) return; + char clip[512]; + if (!gemui_clipboard_get(st->app, clip, sizeof(clip))) return; + size_t len = 0; + for (size_t i = 0; clip[i] && len + 1 < st->focus_cap; i++) { + unsigned char ch = (unsigned char)clip[i]; + if (ch >= 0x20 && ch != 0x7f) st->focus_buf[len++] = (char)ch; } - - /* Preview card */ - int px = list_r.x + list_r.w + pad; - int pw = w - px - pad; - gemui_rect_t prev_r = {px, body_y, pw, body_h}; - if (st->sel >= 0 && st->sel < st->count && pw > 80) { - const gemui_theme_t *p = &st->themes[st->sel].preview; - gemui_fill_round(cr, prev_r, (double)gemui_scale_px(app, 8), p->bg_main); - gemui_stroke_round(cr, prev_r, (double)gemui_scale_px(app, 8), 2.0, p->accent); - - int iy = prev_r.y + pad; - int line_h = gemui_scale_px(app, 28); - gemui_fill_round(cr, (gemui_rect_t){prev_r.x + pad, iy, prev_r.w - pad * 2, line_h}, - (double)gemui_scale_px(app, 4), p->bg_header); - gemui_draw_text(cr, t, (gemui_rect_t){prev_r.x + pad * 2, iy, prev_r.w - pad * 4, line_h}, - st->themes[st->sel].name, 1, true, GEMUI_ALIGN_LEFT, p->fg_bright); - iy += line_h + pad; - - gemui_draw_text(cr, t, (gemui_rect_t){prev_r.x + pad, iy, prev_r.w - pad * 2, line_h}, - "Fira Code Ligatures: -> => != === <= >= ::", -1, false, GEMUI_ALIGN_LEFT, p->fg_main); - iy += line_h + pad / 2; - - const gemui_color_t sw_cols[6] = { - p->accent, p->sel_bg, p->success, p->warning, p->danger, p->highlight - }; - int sw_sz = gemui_scale_px(app, 28); - int gap = gemui_scale_px(app, 8); - for (int c = 0; c < 6 && (pad + (c + 1) * (sw_sz + gap)) < prev_r.w; c++) { - gemui_fill_round(cr, (gemui_rect_t){prev_r.x + pad + c * (sw_sz + gap), iy, sw_sz, sw_sz}, - (double)gemui_scale_px(app, 4), sw_cols[c]); + st->focus_buf[len] = '\0'; + if (st->focus_id == HIT_ED_HEX) { + int r = 0, g = 0, b = 0; + if (anode_xth_parse_hex(st->ed_hex, &r, &g, &b)) { + st->ed_r = r; st->ed_g = g; st->ed_b = b; + ed_commit_rgb_to_slot(st); } - iy += sw_sz + pad; - gemui_draw_text(cr, t, (gemui_rect_t){prev_r.x + pad, iy, prev_r.w - pad * 2, line_h}, - "Affects X11, DWM, st, dmenu, GemUI, GTK2/3/4, Qt5/6, Tk", - -2, false, GEMUI_ALIGN_LEFT, p->fg_muted); + } else if (st->focus_id == HIT_IMP_PATH) { + imp_refresh_preview(st, true); } - - /* Footer */ - int fy = h - ftr_h + gemui_scale_px(app, 4); - int bh = gemui_scale_px(app, 32); - int bw = gemui_scale_px(app, 120); - gemui_draw_button(app, cr, (gemui_rect_t){w - pad - bw * 2 - pad, fy, bw, bh}, - "Apply", HIT_APPLY, 0, true, false, false); - gemui_draw_button(app, cr, (gemui_rect_t){w - pad - bw, fy, bw, bh}, - "Close", HIT_QUIT, 0, false, false, false); + gemui_request_redraw(st->app); } static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) { - (void)state; - (void)utf8; themes_state_t *st = (themes_state_t *)ud; - if (ks == XK_Escape || ks == XK_q) { - gemui_quit(app, 0); - } else if (ks == XK_Down || ks == XK_j) { - if (st->sel + 1 < st->count) st->sel++; - gemui_request_redraw(app); - } else if (ks == XK_Up || ks == XK_k) { - if (st->sel > 0) st->sel--; - gemui_request_redraw(app); - } else if (ks == XK_Return || ks == XK_space) { - apply_selected(st); - } else if (ks == XK_r) { - reload_themes(st); - gemui_request_redraw(app); + + if ((state & ControlMask) && (ks == XK_v || ks == XK_V)) { + apply_text_paste(st); + return; } + if ((state & ControlMask) && (ks == XK_u || ks == XK_U)) { + if (st->focus_buf) { + st->focus_buf[0] = '\0'; + gemui_request_redraw(app); + } + return; + } + if (ks == XK_Escape) { + if (st->view != VIEW_BROWSE) { + st->view = VIEW_BROWSE; + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(app); + } else if (st->focus_buf) { + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(app); + } else { + gemui_quit(app, 0); + } + return; + } + + /* Editable active text box handling */ + if (st->focus_buf) { + if (ks == XK_BackSpace) { + gemui_utf8_pop_char(st->focus_buf); + if (st->focus_id == HIT_ED_HEX) { + int r = 0, g = 0, b = 0; + if (anode_xth_parse_hex(st->ed_hex, &r, &g, &b)) { + st->ed_r = r; st->ed_g = g; st->ed_b = b; + snprintf(st->ed_xth.colors[st->ed_color_idx], 16, "#%02x%02x%02x", r, g, b); + if (st->ed_auto_sync && st->ed_tab == ED_TAB_UI) anode_xth_sync_derived(&st->ed_xth); + } + } else if (st->focus_id == HIT_IMP_PATH) { + imp_refresh_preview(st, true); + } + gemui_request_redraw(app); + return; + } + if (ks == XK_Return || ks == XK_KP_Enter) { + if (st->focus_id == HIT_IMP_PATH) { + char exp[800]; + expand_tilde(st->imp_path, exp, sizeof(exp)); + struct stat sb; + if (stat(exp, &sb) == 0 && S_ISDIR(sb.st_mode)) { + imp_scan_dir(st, exp); + } else { + imp_refresh_preview(st, true); + if (st->imp_valid) do_import_now(st, false); + } + gemui_request_redraw(app); + return; + } + if (st->focus_id == HIT_FILTER && st->view == VIEW_BROWSE) { + apply_selected(st); + return; + } + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(app); + return; + } + if (utf8 && utf8[0]) { + size_t cur = strlen(st->focus_buf); + size_t add = strlen(utf8); + if (cur + add + 1 < st->focus_cap) { + memcpy(st->focus_buf + cur, utf8, add); + st->focus_buf[cur + add] = '\0'; + if (st->focus_id == HIT_ED_HEX) { + int r = 0, g = 0, b = 0; + if (anode_xth_parse_hex(st->ed_hex, &r, &g, &b)) { + st->ed_r = r; st->ed_g = g; st->ed_b = b; + snprintf(st->ed_xth.colors[st->ed_color_idx], 16, "#%02x%02x%02x", r, g, b); + if (st->ed_auto_sync && st->ed_tab == ED_TAB_UI) anode_xth_sync_derived(&st->ed_xth); + } + } else if (st->focus_id == HIT_IMP_PATH) { + imp_refresh_preview(st, true); + } + gemui_request_redraw(app); + } + return; + } + } + + /* Unfocused navigation shortcuts */ + if (st->view == VIEW_BROWSE) { + if (ks == XK_q) gemui_quit(app, 0); + else if (ks == XK_Down || ks == XK_j) { + if (st->sel + 1 < st->count) st->sel++; + gemui_request_redraw(app); + } else if (ks == XK_Up || ks == XK_k) { + if (st->sel > 0) st->sel--; + gemui_request_redraw(app); + } else if (ks == XK_Return || ks == XK_space) { + apply_selected(st); + } else if (ks == XK_r) { + reload_themes(st, NULL); + gemui_request_redraw(app); + } + } else if (st->view == VIEW_EDITOR) { + if (ks == XK_Down) { + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + if (st->ed_color_idx < last) { + st->ed_color_idx++; + ed_sync_picker_from_slot(st); + gemui_request_redraw(app); + } + } else if (ks == XK_Up) { + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + if (st->ed_color_idx > first) { + st->ed_color_idx--; + ed_sync_picker_from_slot(st); + gemui_request_redraw(app); + } + } + } +} + +static void update_rgb_slider_from_x(themes_state_t *st, int chan, int x) { + if (chan < 1 || chan > 3) return; + gemui_rect_t sr = st->ed_slider_rect[chan - 1]; + if (sr.w <= 0) return; + int v = ((x - sr.x) * 255 + sr.w / 2) / sr.w; + if (v < 0) v = 0; + if (v > 255) v = 255; + if (chan == 1) st->ed_r = v; + else if (chan == 2) st->ed_g = v; + else st->ed_b = v; + ed_commit_rgb_to_slot(st); + gemui_request_redraw(st->app); } static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { themes_state_t *st = (themes_state_t *)ud; - if (type == GEMUI_PTR_SCROLL_UP) { - if (st->sel > 0) st->sel--; - gemui_request_redraw(app); + + if (type == GEMUI_PTR_SCROLL_UP || type == GEMUI_PTR_SCROLL_DOWN) { + int delta = (type == GEMUI_PTR_SCROLL_UP) ? -1 : 1; + if (st->view == VIEW_BROWSE) { + int next = st->sel + delta; + if (next >= 0 && next < st->count) { st->sel = next; gemui_request_redraw(app); } + } else if (st->view == VIEW_EDITOR && st->ed_tab != ED_TAB_GEN) { + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + int next = st->ed_color_idx + delta; + if (next >= first && next <= last) { + st->ed_color_idx = next; + ed_sync_picker_from_slot(st); + gemui_request_redraw(app); + } + } else if (st->view == VIEW_IMPORT) { + int next = st->imp_sel + delta; + if (next >= 0 && next < st->imp_count) { st->imp_sel = next; gemui_request_redraw(app); } + } return; } - if (type == GEMUI_PTR_SCROLL_DOWN) { - if (st->sel + 1 < st->count) st->sel++; - gemui_request_redraw(app); + + if (type == GEMUI_PTR_UP) { + st->ed_drag_chan = 0; return; } + if (type == GEMUI_PTR_MOVE) { + if (st->view == VIEW_EDITOR && st->ed_drag_chan >= 1 && st->ed_drag_chan <= 3) { + update_rgb_slider_from_x(st, st->ed_drag_chan, x); + } + return; + } + if (type != GEMUI_PTR_DOWN || btn != Button1) return; const gemui_hit_t *hit = gemui_hit_test(app, x, y); - if (!hit) return; - if (hit->id == HIT_ROW) { + if (!hit) { + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(app); + return; + } + + /* Clicking away from current text box unfocuses unless hit is another text box */ + if (hit->id != HIT_FILTER && hit->id != HIT_ED_FIELD && + hit->id != HIT_ED_HEX && hit->id != HIT_IMP_PATH && hit->id != HIT_IMP_NAME) { + set_focus_input(st, 0, NULL, 0); + } + + if (hit->id == HIT_FILTER) { + set_focus_input(st, HIT_FILTER, st->filter, sizeof(st->filter)); + gemui_request_redraw(app); + } else if (hit->id == HIT_ROW) { if (st->sel == hit->val) apply_selected(st); else { st->sel = hit->val; gemui_request_redraw(app); } } else if (hit->id == HIT_APPLY) { apply_selected(st); + } else if (hit->id == HIT_EDIT && st->sel >= 0 && st->sel < st->count) { + anode_xth_t xth; + if (!anode_xth_load_file(st->themes[st->sel].path, &xth)) { + gemui_show_toast(app, "Failed to load selected .xth", 2000); + return; + } + open_editor(st, &xth, false); + } else if (hit->id == HIT_DUPLICATE && st->sel >= 0 && st->sel < st->count) { + anode_xth_t xth; + if (!anode_xth_load_file(st->themes[st->sel].path, &xth)) { + anode_xth_init_anodized(&xth); + } + char cname[64]; + make_unique_copy_name(st, st->themes[st->sel].name, cname, sizeof(cname)); + snprintf(xth.name, sizeof(xth.name), "%s", cname); + open_editor(st, &xth, true); + } else if (hit->id == HIT_NEW) { + anode_xth_t xth; + anode_xth_init_anodized(&xth); + snprintf(xth.name, sizeof(xth.name), "Custom"); + for (int n = 2; name_exists(st, xth.name) && n < 100; n++) { + snprintf(xth.name, sizeof(xth.name), "Custom%d", n); + } + open_editor(st, &xth, true); + } else if (hit->id == HIT_OPEN_IMPORT) { + open_importer(st); + } else if (hit->id == HIT_DELETE && st->sel >= 0 && st->sel < st->count) { + theme_entry_t *e = &st->themes[st->sel]; + if (!e->is_user) { + gemui_show_toast(app, "Built-in themes are read-only; Edit to save override", 2200); + gemui_request_redraw(app); + return; + } + bool was_active = (strcmp(e->name, st->active_name) == 0); + bool had_sys = e->has_sys; + char removed_name[64]; + snprintf(removed_name, sizeof(removed_name), "%s", e->name); + if (remove(e->path) == 0) { + reload_themes(st, removed_name); + if (was_active && had_sys && st->sel < st->count) { + apply_path_now(st, st->themes[st->sel].path); + } + gemui_show_toast(app, had_sys ? "Reset theme to system default" : "Deleted user theme", 2000); + } else { + gemui_show_toast(app, "Failed to delete theme file", 2000); + } + gemui_request_redraw(app); } else if (hit->id == HIT_QUIT) { gemui_quit(app, 0); + } else if (hit->id == HIT_ED_TAB) { + st->ed_tab = hit->val; + st->ed_scroll = 0; + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + if (last >= first && (st->ed_color_idx < first || st->ed_color_idx > last)) { + st->ed_color_idx = first; + ed_sync_picker_from_slot(st); + } + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_FIELD) { + char *bufs[4] = {st->ed_xth.name, st->ed_xth.font_face, st->ed_xth.ui_font_face, st->ed_xth.icon_font_face}; + size_t caps[4] = {sizeof(st->ed_xth.name), sizeof(st->ed_xth.font_face), + sizeof(st->ed_xth.ui_font_face), sizeof(st->ed_xth.icon_font_face)}; + if (hit->val >= 0 && hit->val < 4) set_focus_input(st, HIT_ED_FIELD, bufs[hit->val], caps[hit->val]); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_DARK) { + st->ed_xth.is_dark = st->ed_xth.is_dark ? 0 : 1; + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_AUTOSYNC) { + st->ed_auto_sync = !st->ed_auto_sync; + if (st->ed_auto_sync) anode_xth_sync_derived(&st->ed_xth); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_FONTSZ) { + st->ed_xth.base_font_size += hit->val; + if (st->ed_xth.base_font_size < 8) st->ed_xth.base_font_size = 8; + if (st->ed_xth.base_font_size > 28) st->ed_xth.base_font_size = 28; + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_BORDERPX) { + st->ed_xth.dwm_borderpx += hit->val; + if (st->ed_xth.dwm_borderpx < 1) st->ed_xth.dwm_borderpx = 1; + if (st->ed_xth.dwm_borderpx > 6) st->ed_xth.dwm_borderpx = 6; + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_SLOT) { + st->ed_color_idx = hit->val; + ed_sync_picker_from_slot(st); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_HEX) { + set_focus_input(st, HIT_ED_HEX, st->ed_hex, sizeof(st->ed_hex)); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_PASTE_HEX) { + set_focus_input(st, HIT_ED_HEX, st->ed_hex, sizeof(st->ed_hex)); + apply_text_paste(st); + } else if (hit->id == HIT_ED_SLIDER_R || hit->id == HIT_ED_SLIDER_G || hit->id == HIT_ED_SLIDER_B) { + st->ed_drag_chan = hit->val; + update_rgb_slider_from_x(st, hit->val, x); + } else if (hit->id == HIT_ED_SAVE) { + editor_save(st, false); + } else if (hit->id == HIT_ED_SAVE_APPLY) { + editor_save(st, true); + } else if (hit->id == HIT_ED_REVERT) { + st->ed_xth = st->ed_orig; + ed_sync_picker_from_slot(st); + gemui_show_toast(st->app, "Reverted unsaved changes", 1400); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_BACK) { + st->view = VIEW_BROWSE; + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_PATH) { + set_focus_input(st, HIT_IMP_PATH, st->imp_path, sizeof(st->imp_path)); + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_PASTE_PATH) { + set_focus_input(st, HIT_IMP_PATH, st->imp_path, sizeof(st->imp_path)); + apply_text_paste(st); + } else if (hit->id == HIT_IMP_QUICK_DIR) { + const char *home = getenv("HOME"); + char target[512]; + if (hit->val == 1) snprintf(target, sizeof(target), "/"); + else if (hit->val == 2) user_themes_dir(target, sizeof(target)); + else snprintf(target, sizeof(target), "%s", (home && home[0]) ? home : "/"); + mkdir_p_user(target); + imp_scan_dir(st, target); + snprintf(st->imp_path, sizeof(st->imp_path), "%s", st->imp_dir); + st->imp_valid = false; + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_TOGGLE_ALL) { + st->imp_show_all = !st->imp_show_all; + imp_scan_dir(st, st->imp_dir); + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_ITEM && hit->val >= 0 && hit->val < st->imp_count) { + st->imp_sel = hit->val; + const dir_item_t *it = &st->imp_items[hit->val]; + if (it->is_dir) { + char next[1024]; + if (strcmp(it->name, "..") == 0) { + snprintf(next, sizeof(next), "%s", st->imp_dir); + char *slash = strrchr(next, '/'); + if (slash && slash != next) *slash = '\0'; + else snprintf(next, sizeof(next), "/"); + } else { + snprintf(next, sizeof(next), "%s/%s", strcmp(st->imp_dir, "/") == 0 ? "" : st->imp_dir, it->name); + } + imp_scan_dir(st, next); + snprintf(st->imp_path, sizeof(st->imp_path), "%s", st->imp_dir); + st->imp_valid = false; + } else { + snprintf(st->imp_path, sizeof(st->imp_path), "%s/%s", + strcmp(st->imp_dir, "/") == 0 ? "" : st->imp_dir, it->name); + imp_refresh_preview(st, true); + } + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_NAME) { + set_focus_input(st, HIT_IMP_NAME, st->imp_name, sizeof(st->imp_name)); + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_DO) { + do_import_now(st, false); + } else if (hit->id == HIT_IMP_DO_APPLY) { + do_import_now(st, true); + } else if (hit->id == HIT_IMP_BACK) { + st->view = VIEW_BROWSE; + gemui_request_redraw(app); } } -int main(void) { +int main(int argc, char **argv) { + if (argc >= 2 && strcmp(argv[1], "--install") == 0) { + if (argc < 3 || !argv[2][0]) { + fprintf(stderr, "Usage: anode-themes --install /path/to/Theme.xth [Name]\n"); + return 1; + } + const char *ov = (argc >= 4 && argv[3][0]) ? argv[3] : NULL; + char udir[512], dest[592]; + user_themes_dir(udir, sizeof(udir)); + mkdir_p_user(udir); + if (!anode_xth_import_file(argv[2], udir, ov, dest, sizeof(dest))) { + fprintf(stderr, "anode-themes: failed to install theme from %s\n", argv[2]); + return 1; + } + printf("Installed theme to %s\n", dest); + return 0; + } + themes_state_t st; memset(&st, 0, sizeof(st)); - st.app = gemui_create("anode-themes", "ANODE Themes", 820, 520, false); + st.app = gemui_create("anode-themes", "ANODE Themes & Editor", 980, 640, false); if (!st.app) return 1; - reload_themes(&st); + reload_themes(&st, NULL); gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr, .on_theme = on_theme }; gemui_set_handlers(st.app, &h, &st); int rc = gemui_run(st.app); diff --git a/src/apps/anode-vkbd.c b/src/apps/anode-vkbd.c index 6b7eee8..fa576b6 100644 --- a/src/apps/anode-vkbd.c +++ b/src/apps/anode-vkbd.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -182,6 +183,7 @@ typedef struct { cairo_surface_t *xlib_surf; GC gc; int sw, sh; + int mx, my, mw, mh; int wx, wy, ww, wh; double scale; gemui_theme_t theme; @@ -197,13 +199,16 @@ typedef struct { static void update_strut(vkbd_t *v, bool reserve) { if (!v->win) return; if (reserve) { + unsigned long bot = (unsigned long)(v->sh - (v->my + v->mh) + v->wh); + unsigned long sx = (unsigned long)(v->wx > 0 ? v->wx : 0); + unsigned long ex = (unsigned long)(v->wx + (v->ww > 0 ? v->ww - 1 : 0)); unsigned long sp[12] = {0}; - sp[3] = (unsigned long)v->wh; /* bottom */ - sp[10] = 0; /* bottom_start_x */ - sp[11] = (unsigned long)(v->sw > 0 ? v->sw - 1 : v->ww - 1); + sp[3] = bot; /* bottom */ + sp[10] = sx; /* bottom_start_x */ + sp[11] = ex; /* bottom_end_x */ XChangeProperty(v->dpy, v->win, v->a_strut_partial, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)sp, 12); - unsigned long s4[4] = {0, 0, 0, (unsigned long)v->wh}; + unsigned long s4[4] = {0, 0, 0, bot}; XChangeProperty(v->dpy, v->win, v->a_strut, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)s4, 4); } else { @@ -242,14 +247,39 @@ static void load_theme_and_geom(vkbd_t *v) { v->sw = DisplayWidth(v->dpy, v->screen); v->sh = DisplayHeight(v->dpy, v->screen); + v->mx = 0; v->my = 0; v->mw = v->sw; v->mh = v->sh; + { + int xn = 0; + XineramaScreenInfo *xi = XineramaIsActive(v->dpy) ? XineramaQueryScreens(v->dpy, &xn) : NULL; + if (xi && xn > 0) { + Window d_w; + int rx = 0, ry = 0, di = 0; + unsigned int du = 0; + int chosen = 0; + if (XQueryPointer(v->dpy, v->root, &d_w, &d_w, &rx, &ry, &di, &di, &du)) { + for (int k = 0; k < xn; k++) { + if (rx >= xi[k].x_org && rx < xi[k].x_org + xi[k].width && + ry >= xi[k].y_org && ry < xi[k].y_org + xi[k].height) { + chosen = k; + break; + } + } + } + v->mx = xi[chosen].x_org; + v->my = xi[chosen].y_org; + v->mw = xi[chosen].width; + v->mh = xi[chosen].height; + XFree(xi); + } + } int kh = anode_scale_px(210, sc); - int max_kh = (v->sh * 42) / 100; + int max_kh = (v->mh * 42) / 100; if (kh > max_kh) kh = max_kh; - if (kh < 140 && v->sh >= 360) kh = 140; - v->ww = v->sw; + if (kh < 140 && v->mh >= 360) kh = 140; + v->ww = v->mw; v->wh = kh; - v->wx = 0; - v->wy = v->sh - v->wh; + v->wx = v->mx; + v->wy = v->my + v->mh - v->wh; } static void ensure_buffers(vkbd_t *v) { @@ -307,7 +337,11 @@ static void draw_vkbd(vkbd_t *v) { bool pressed = (v->pressed_key == &row[i]); gemui_color_t bg = pressed ? v->theme.accent : (latched ? v->theme.sel_bg : v->theme.bg_button); - gemui_color_t fg = (pressed || latched) ? v->theme.sel_fg : v->theme.fg_bright; + double bgl = 0.299 * bg.r + 0.587 * bg.g + 0.114 * bg.b; + gemui_color_t dark_ink = (0.299 * v->theme.bg_main.r + 0.587 * v->theme.bg_main.g + 0.114 * v->theme.bg_main.b) < 0.35 + ? v->theme.bg_main + : (gemui_color_t){0.031, 0.035, 0.043, 1.0, 0xff08090bU}; + gemui_color_t fg = (bgl > 0.58) ? dark_ink : ((pressed || latched) ? v->theme.sel_fg : v->theme.fg_bright); gemui_fill_round(cr, (gemui_rect_t){cx, cy, kw, row_h}, rad, bg); gemui_stroke_round(cr, (gemui_rect_t){cx, cy, kw, row_h}, rad, 1.0, latched ? v->theme.accent : v->theme.border); diff --git a/src/common/anode_bar_fmt.h b/src/common/anode_bar_fmt.h new file mode 100644 index 0000000..0c865a8 --- /dev/null +++ b/src/common/anode_bar_fmt.h @@ -0,0 +1,144 @@ +/* + * ANODE Status Bar Formatting & Progressive Compaction + * (shared across dwm and unit tests) + */ +#ifndef ANODE_BAR_FMT_H +#define ANODE_BAR_FMT_H + +#include +#include +#include +#include +#include + +static inline bool anode_bar_is_datetime(const char *s) { + if (!s || strlen(s) != 16U) return false; + for (int i = 0; i < 16; i++) { + if (i == 4 || i == 7) { + if (s[i] != '-') return false; + } else if (i == 10) { + if (s[i] != ' ') return false; + } else if (i == 13) { + if (s[i] != ':') return false; + } else if (s[i] < '0' || s[i] > '9') { + return false; + } + } + return true; +} + +static inline bool anode_bar_is_xkb(const char *s) { + if (!s || !s[0]) return false; + size_t len = strlen(s); + if (len > 8U) return false; + if (strcmp(s, "ac") == 0) return false; + for (size_t i = 0; i < len; i++) { + unsigned char c = (unsigned char)s[i]; + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) return false; + } + return true; +} + +static inline void anode_bar_append_tok(char *out, size_t out_sz, size_t *pos, const char *tok) { + if (!tok || !tok[0] || !out || out_sz == 0 || *pos + 1 >= out_sz) return; + int n = snprintf(out + *pos, out_sz - *pos, "%s%s", (*pos > 0) ? " " : "", tok); + if (n > 0) { + if ((size_t)n < out_sz - *pos) *pos += (size_t)n; + else *pos = out_sz - 1; + } +} + +/* + * Progressively compact an anode-statusd bar string to preserve window title space: + * tier 0: full status ("VOL 75% | CPU 12% | RAM 45% | BAT 85%+ | us | 2026-11-27 08:02") + * tier 1: short tags ("V:75% C:12% R:45% B:85%+ us 11-27 08:02") + * tier 2: essentials ("V:75% B:85%+ us 08:02") + * tier 3: minimal ("us 08:02") + */ +static inline void anode_bar_compact_status(const char *raw, int tier, char *out, size_t out_sz) { + if (!out || out_sz == 0) return; + out[0] = '\0'; + if (!raw || !raw[0]) return; + + char buf[512]; + snprintf(buf, sizeof(buf), "%s", raw); + char *p = buf; + while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; + size_t plen = strlen(p); + while (plen > 0 && (p[plen - 1] == ' ' || p[plen - 1] == '\t' || p[plen - 1] == '\n' || p[plen - 1] == '\r')) { + p[--plen] = '\0'; + } + if (!p[0]) return; + + if (tier <= 0) { + snprintf(out, out_sz, "%s", p); + return; + } + + char *segs[12]; + int nsegs = 0; + char work[512]; + snprintf(work, sizeof(work), "%s", p); + char *cur = work; + while (cur && nsegs < 12) { + char *bar = strchr(cur, '|'); + if (bar) *bar = '\0'; + while (*cur == ' ' || *cur == '\t') cur++; + size_t sl = strlen(cur); + while (sl > 0 && (cur[sl - 1] == ' ' || cur[sl - 1] == '\t')) cur[--sl] = '\0'; + if (sl > 0) segs[nsegs++] = cur; + cur = bar ? (bar + 1) : NULL; + } + + if (nsegs < 2) { + snprintf(out, out_sz, "%s", p); + return; + } + + size_t pos = 0; + for (int i = 0; i < nsegs; i++) { + const char *s = segs[i]; + char tok[96] = ""; + if (strncmp(s, "VOL ", 4) == 0) { + if (tier <= 2) { + const char *rest = s + 4; + while (*rest == ' ') rest++; + if (strcmp(rest, "MUTE") == 0) snprintf(tok, sizeof(tok), "V:M"); + else snprintf(tok, sizeof(tok), "V:%.88s", rest); + } + } else if (strncmp(s, "CPU ", 4) == 0) { + if (tier == 1) { + const char *rest = s + 4; + while (*rest == ' ') rest++; + snprintf(tok, sizeof(tok), "C:%.88s", rest); + } + } else if (strncmp(s, "RAM ", 4) == 0) { + if (tier == 1) { + const char *rest = s + 4; + while (*rest == ' ') rest++; + snprintf(tok, sizeof(tok), "R:%.88s", rest); + } + } else if (strncmp(s, "BAT ", 4) == 0) { + if (tier <= 2) { + const char *rest = s + 4; + while (*rest == ' ') rest++; + snprintf(tok, sizeof(tok), "B:%.88s", rest); + } + } else if (strcmp(s, "AC") == 0) { + if (tier == 1) snprintf(tok, sizeof(tok), "AC"); + } else if (anode_bar_is_datetime(s)) { + snprintf(tok, sizeof(tok), "%s", (tier == 1) ? (s + 5) : (s + 11)); + } else if (anode_bar_is_xkb(s) && i + 1 < nsegs && anode_bar_is_datetime(segs[i + 1])) { + snprintf(tok, sizeof(tok), "%s", s); + } else if (tier <= 2) { + snprintf(tok, sizeof(tok), "%s", s); + } + if (tok[0]) anode_bar_append_tok(out, out_sz, &pos, tok); + } + + if (pos == 0 && nsegs > 0) { + snprintf(out, out_sz, "%s", segs[nsegs - 1]); + } +} + +#endif /* ANODE_BAR_FMT_H */ diff --git a/src/common/anode_display_cfg.h b/src/common/anode_display_cfg.h new file mode 100644 index 0000000..01e60fb --- /dev/null +++ b/src/common/anode_display_cfg.h @@ -0,0 +1,455 @@ +/* + * ANODE Display Arrangement & Profile Config Helper (header-only POSIX C99/C11) + * Pure geometry, magnetic snapping, preset layout math, and displays.conf persistence. + */ +#ifndef ANODE_DISPLAY_CFG_H +#define ANODE_DISPLAY_CFG_H + +#include +#include +#include +#include +#include +#include + +#define ANODE_DISP_MAX_OUTS 8 + +typedef enum { + ANODE_DISP_PRESET_RIGHT = 0, + ANODE_DISP_PRESET_LEFT, + ANODE_DISP_PRESET_ABOVE, + ANODE_DISP_PRESET_BELOW, + ANODE_DISP_PRESET_MIRROR, + ANODE_DISP_PRESET_PRIMARY_ONLY +} anode_disp_preset_t; + +typedef struct { + char name[32]; + bool enabled; + bool primary; + int x; + int y; + int w; + int h; + double hz; + int rot; /* 0=normal, 1=left, 2=inverted, 3=right */ +} anode_disp_out_t; + +static inline const char *anode_disp_rot_name(int rot) { + switch (rot & 3) { + case 1: return "left"; + case 2: return "inverted"; + case 3: return "right"; + default: return "normal"; + } +} + +static inline int anode_disp_parse_rot(const char *s) { + if (!s) return 0; + if (strcmp(s, "left") == 0 || strcmp(s, "1") == 0) return 1; + if (strcmp(s, "inverted") == 0 || strcmp(s, "2") == 0) return 2; + if (strcmp(s, "right") == 0 || strcmp(s, "3") == 0) return 3; + return 0; +} + +static inline void anode_disp_eff_size(int w, int h, int rot, int *ew, int *eh) { + if ((rot & 3) == 1 || (rot & 3) == 3) { + if (ew) *ew = h; + if (eh) *eh = w; + } else { + if (ew) *ew = w; + if (eh) *eh = h; + } +} + +static inline bool anode_disp_safe_token(const char *s) { + if (!s || !s[0]) return false; + for (const char *p = s; *p; p++) { + unsigned char ch = (unsigned char)*p; + if (!(isalnum(ch) || ch == '-' || ch == '_' || ch == '.')) return false; + } + return true; +} + +static inline void anode_disp_normalize(anode_disp_out_t *outs, int n) { + if (!outs || n <= 0) return; + int min_x = 0, min_y = 0; + bool any = false; + int first_en = -1; + int pri_idx = -1; + + for (int i = 0; i < n; i++) { + outs[i].rot &= 3; + if (!outs[i].enabled) { + outs[i].primary = false; + continue; + } + if (first_en < 0) first_en = i; + if (outs[i].primary && pri_idx < 0) pri_idx = i; + else if (outs[i].primary) outs[i].primary = false; + + if (!any || outs[i].x < min_x) min_x = outs[i].x; + if (!any || outs[i].y < min_y) min_y = outs[i].y; + any = true; + } + + if (any && (min_x != 0 || min_y != 0)) { + for (int i = 0; i < n; i++) { + if (outs[i].enabled) { + outs[i].x -= min_x; + outs[i].y -= min_y; + } + } + } + if (first_en >= 0 && pri_idx < 0) { + outs[first_en].primary = true; + } +} + +static inline void anode_disp_snap(const anode_disp_out_t *outs, int n, int idx, + int raw_x, int raw_y, int snap_px, + int *out_x, int *out_y) { + int sx = raw_x; + int sy = raw_y; + if (!outs || idx < 0 || idx >= n || snap_px <= 0) { + if (out_x) *out_x = sx; + if (out_y) *out_y = sy; + return; + } + + int ew = 0, eh = 0; + anode_disp_eff_size(outs[idx].w, outs[idx].h, outs[idx].rot, &ew, &eh); + int best_dx = snap_px + 1; + int best_dy = snap_px + 1; + + for (int j = 0; j < n; j++) { + if (j == idx || !outs[j].enabled || outs[j].w <= 0 || outs[j].h <= 0) continue; + int ow = 0, oh = 0; + anode_disp_eff_size(outs[j].w, outs[j].h, outs[j].rot, &ow, &oh); + int ox = outs[j].x; + int oy = outs[j].y; + + int x_cands[4] = {ox + ow, ox - ew, ox, ox + ow - ew}; + for (int k = 0; k < 4; k++) { + int d = raw_x - x_cands[k]; + if (d < 0) d = -d; + if (d <= snap_px && d < best_dx) { + best_dx = d; + sx = x_cands[k]; + } + } + + int y_cands[4] = {oy + oh, oy - eh, oy, oy + oh - eh}; + for (int k = 0; k < 4; k++) { + int d = raw_y - y_cands[k]; + if (d < 0) d = -d; + if (d <= snap_px && d < best_dy) { + best_dy = d; + sy = y_cands[k]; + } + } + } + + if (out_x) *out_x = sx; + if (out_y) *out_y = sy; +} + +static inline void anode_disp_apply_preset(anode_disp_out_t *outs, int n, int focus_idx, + anode_disp_preset_t preset) { + if (!outs || n <= 0) return; + int anchor = -1; + for (int i = 0; i < n; i++) { + if (outs[i].enabled && outs[i].primary) { anchor = i; break; } + } + if (anchor < 0 && focus_idx >= 0 && focus_idx < n) anchor = focus_idx; + if (anchor < 0) anchor = 0; + + if (preset == ANODE_DISP_PRESET_PRIMARY_ONLY) { + for (int i = 0; i < n; i++) { + outs[i].enabled = (i == anchor); + outs[i].primary = (i == anchor); + if (i == anchor) { outs[i].x = 0; outs[i].y = 0; } + } + return; + } + + for (int i = 0; i < n; i++) { + if (outs[i].w > 0 && outs[i].h > 0) outs[i].enabled = true; + outs[i].primary = (i == anchor); + } + + if (preset == ANODE_DISP_PRESET_MIRROR) { + for (int i = 0; i < n; i++) { + if (outs[i].enabled) { outs[i].x = 0; outs[i].y = 0; } + } + anode_disp_normalize(outs, n); + return; + } + + int order[ANODE_DISP_MAX_OUTS]; + int cnt = 0; + order[cnt++] = anchor; + for (int i = 0; i < n && cnt < ANODE_DISP_MAX_OUTS; i++) { + if (i != anchor && outs[i].enabled) order[cnt++] = i; + } + + int cx = 0, cy = 0; + for (int oi = 0; oi < cnt; oi++) { + int idx = order[oi]; + int ew = 0, eh = 0; + anode_disp_eff_size(outs[idx].w, outs[idx].h, outs[idx].rot, &ew, &eh); + if (preset == ANODE_DISP_PRESET_RIGHT) { + outs[idx].x = cx; + outs[idx].y = 0; + cx += ew; + } else if (preset == ANODE_DISP_PRESET_LEFT) { + if (oi == 0) { + outs[idx].x = 0; + outs[idx].y = 0; + cx = 0; + } else { + cx -= ew; + outs[idx].x = cx; + outs[idx].y = 0; + } + } else if (preset == ANODE_DISP_PRESET_BELOW) { + outs[idx].x = 0; + outs[idx].y = cy; + cy += eh; + } else if (preset == ANODE_DISP_PRESET_ABOVE) { + if (oi == 0) { + outs[idx].x = 0; + outs[idx].y = 0; + cy = 0; + } else { + cy -= eh; + outs[idx].x = 0; + outs[idx].y = cy; + } + } + } + anode_disp_normalize(outs, n); +} + +static inline void anode_disp_signature(const anode_disp_out_t *outs, int n, char *out, size_t sz) { + if (!out || sz == 0) return; + out[0] = '\0'; + if (!outs || n <= 0) return; + + const char *names[ANODE_DISP_MAX_OUTS]; + int m = 0; + for (int i = 0; i < n && m < ANODE_DISP_MAX_OUTS; i++) { + if (anode_disp_safe_token(outs[i].name)) names[m++] = outs[i].name; + } + for (int a = 0; a < m; a++) { + for (int b = a + 1; b < m; b++) { + if (strcmp(names[b], names[a]) < 0) { + const char *tmp = names[a]; + names[a] = names[b]; + names[b] = tmp; + } + } + } + size_t off = 0; + for (int i = 0; i < m; i++) { + int wrote = snprintf(out + off, sz - off, "%s%s", i > 0 ? "," : "", names[i]); + if (wrote < 0 || (size_t)wrote >= sz - off) { + out[sz - 1] = '\0'; + break; + } + off += (size_t)wrote; + } +} + +static inline int anode_disp_load_profile(const char *conf_path, const char *sig, + anode_disp_out_t *outs, int max_n) { + if (!conf_path || !sig || !sig[0] || !outs || max_n <= 0) return 0; + FILE *f = fopen(conf_path, "r"); + if (!f) return 0; + + char hdr[288]; + snprintf(hdr, sizeof(hdr), "[profile:%s]", sig); + + bool in_sec = false; + int count = 0; + char line[512]; + while (fgets(line, sizeof(line), f)) { + size_t len = strlen(line); + while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) line[--len] = '\0'; + char *s = line; + while (*s == ' ' || *s == '\t') s++; + if (!s[0] || s[0] == '#' || s[0] == ';') continue; + if (s[0] == '[') { + if (in_sec) break; + in_sec = (strcmp(s, hdr) == 0); + continue; + } + if (!in_sec || strncmp(s, "output=", 7) != 0 || count >= max_n) continue; + + char copy[512]; + snprintf(copy, sizeof(copy), "%s", s + 7); + char *toks[8] = {0}; + int nt = 0; + char *p = copy; + while (nt < 8) { + toks[nt++] = p; + char *comma = strchr(p, ','); + if (!comma) break; + *comma = '\0'; + p = comma + 1; + } + if (nt < 8 || !anode_disp_safe_token(toks[0])) continue; + + anode_disp_out_t o; + memset(&o, 0, sizeof(o)); + snprintf(o.name, sizeof(o.name), "%s", toks[0]); + o.enabled = (atoi(toks[1]) != 0); + o.primary = (atoi(toks[2]) != 0); + int pw = 0, ph = 0; + if (sscanf(toks[3], "%dx%d", &pw, &ph) != 2) { pw = 0; ph = 0; } + o.w = pw; + o.h = ph; + o.hz = strtod(toks[4], NULL); + o.x = atoi(toks[5]); + o.y = atoi(toks[6]); + o.rot = anode_disp_parse_rot(toks[7]); + outs[count++] = o; + } + fclose(f); + if (count > 0) anode_disp_normalize(outs, count); + return count; +} + +static inline bool anode_disp_save_profile(const char *conf_path, + const anode_disp_out_t *outs, int n) { + if (!conf_path || !conf_path[0] || !outs || n <= 0) return false; + anode_disp_out_t copy[ANODE_DISP_MAX_OUTS]; + int cnt = n > ANODE_DISP_MAX_OUTS ? ANODE_DISP_MAX_OUTS : n; + memcpy(copy, outs, (size_t)cnt * sizeof(copy[0])); + anode_disp_normalize(copy, cnt); + + bool any_en = false; + for (int i = 0; i < cnt; i++) { + if (copy[i].enabled) { any_en = true; break; } + } + if (!any_en) return false; + + char sig[256]; + anode_disp_signature(copy, cnt, sig, sizeof(sig)); + if (!sig[0]) return false; + + char hdr[288]; + snprintf(hdr, sizeof(hdr), "[profile:%s]", sig); + + char tmp_path[576]; + snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", conf_path); + FILE *out = fopen(tmp_path, "w"); + if (!out) return false; + + fprintf(out, "# Managed by anode-display\n"); + FILE *in = fopen(conf_path, "r"); + if (in) { + char line[512]; + bool skip_sec = false; + bool prev_comment_hdr = true; + while (fgets(line, sizeof(line), in)) { + char trimmed[512]; + snprintf(trimmed, sizeof(trimmed), "%s", line); + size_t tl = strlen(trimmed); + while (tl > 0 && (trimmed[tl - 1] == '\n' || trimmed[tl - 1] == '\r')) trimmed[--tl] = '\0'; + if (prev_comment_hdr && strcmp(trimmed, "# Managed by anode-display") == 0) { + prev_comment_hdr = false; + continue; + } + prev_comment_hdr = false; + char *s = trimmed; + while (*s == ' ' || *s == '\t') s++; + if (s[0] == '[') { + skip_sec = (strcmp(s, hdr) == 0); + } + if (!skip_sec) { + fputs(line, out); + } + } + fclose(in); + } + + fprintf(out, "%s\n", hdr); + for (int i = 0; i < cnt; i++) { + fprintf(out, "output=%s,%d,%d,%dx%d,%.2f,%d,%d,%s\n", + copy[i].name, + copy[i].enabled ? 1 : 0, + copy[i].primary ? 1 : 0, + copy[i].w, copy[i].h, + copy[i].hz > 0.0 ? copy[i].hz : 60.0, + copy[i].x, copy[i].y, + anode_disp_rot_name(copy[i].rot)); + } + if (fclose(out) != 0) { + remove(tmp_path); + return false; + } + if (rename(tmp_path, conf_path) != 0) { + remove(tmp_path); + return false; + } + return true; +} + +static inline int anode_disp_build_xrandr_argv(const anode_disp_out_t *outs, int n, + const char **argv, int max_args, + char *tokbuf, size_t tok_cap) { + if (!outs || n <= 0 || !argv || max_args < 4 || !tokbuf || tok_cap < 64) return -1; + bool any_en = false; + for (int i = 0; i < n; i++) { + if (!anode_disp_safe_token(outs[i].name)) return -1; + if (outs[i].enabled) any_en = true; + } + if (!any_en) return -1; + + int ac = 0; + size_t off = 0; + argv[ac++] = "xrandr"; + + for (int i = 0; i < n; i++) { + if (ac + 11 >= max_args) return -1; + argv[ac++] = "--output"; + argv[ac++] = outs[i].name; + if (!outs[i].enabled) { + argv[ac++] = "--off"; + continue; + } + if (outs[i].w > 0 && outs[i].h > 0) { + char *mode_tok = tokbuf + off; + int mw = snprintf(mode_tok, tok_cap - off, "%dx%d", outs[i].w, outs[i].h); + if (mw < 0 || (size_t)mw >= tok_cap - off) return -1; + off += (size_t)mw + 1; + argv[ac++] = "--mode"; + argv[ac++] = mode_tok; + if (outs[i].hz > 0.0) { + char *rate_tok = tokbuf + off; + int rw = snprintf(rate_tok, tok_cap - off, "%.2f", outs[i].hz); + if (rw < 0 || (size_t)rw >= tok_cap - off) return -1; + off += (size_t)rw + 1; + argv[ac++] = "--rate"; + argv[ac++] = rate_tok; + } + } else { + argv[ac++] = "--auto"; + } + char *pos_tok = tokbuf + off; + int pw = snprintf(pos_tok, tok_cap - off, "%dx%d", outs[i].x, outs[i].y); + if (pw < 0 || (size_t)pw >= tok_cap - off) return -1; + off += (size_t)pw + 1; + argv[ac++] = "--pos"; + argv[ac++] = pos_tok; + argv[ac++] = "--rotate"; + argv[ac++] = anode_disp_rot_name(outs[i].rot); + if (outs[i].primary) argv[ac++] = "--primary"; + } + + argv[ac] = NULL; + return ac; +} + +#endif /* ANODE_DISPLAY_CFG_H */ diff --git a/src/common/anode_plat.c b/src/common/anode_plat.c index c69c443..b209d01 100644 --- a/src/common/anode_plat.c +++ b/src/common/anode_plat.c @@ -140,7 +140,7 @@ void anode_themes_sys_dir(char *buf, size_t sz) { } void anode_default_xth_path(char *buf, size_t sz) { - snprintf(buf, sz, "%s/share/anode/themes/AnodeDefault.xth", ANODE_PREFIX); + snprintf(buf, sz, "%s/share/anode/themes/Anodized.xth", ANODE_PREFIX); } bool anode_have_cmd(const char *cmd) { diff --git a/src/common/anode_power_policy.h b/src/common/anode_power_policy.h index c2959a4..bac023e 100644 --- a/src/common/anode_power_policy.h +++ b/src/common/anode_power_policy.h @@ -1,11 +1,15 @@ /* - * ANODE Power Policy State Machine (shared across anode-powerd and tests) + * ANODE Power Policy State Machine & Configuration Persistence + * (shared across anode-powerd, anode-power, anode-display, and unit tests) */ #ifndef ANODE_POWER_POLICY_H #define ANODE_POWER_POLICY_H #include #include +#include +#include +#include typedef enum { ANODE_PWR_ACTIVE = 0, @@ -67,9 +71,16 @@ static inline void anode_power_policy_step(const anode_power_cfg_t *cfg, } } - /* User activity resumes from dimmed/locked/suspended */ - uint32_t resume_thresh = cfg->dim_ms > 0 ? cfg->dim_ms : (cfg->lock_ms > 0 ? cfg->lock_ms : cfg->suspend_ms); - if (resume_thresh == 0 || idle_ms < resume_thresh) { + /* User activity resumes from dimmed/locked/suspended before the earliest enabled timeout */ + uint32_t eff_susp_ms = (cfg->suspend_ms > 0U && (cfg->suspend_on_ac || !on_ac)) ? cfg->suspend_ms : 0U; + uint32_t resume_thresh = 0U; + uint32_t cands[3] = {cfg->dim_ms, cfg->lock_ms, eff_susp_ms}; + for (int i = 0; i < 3; i++) { + if (cands[i] > 0U && (resume_thresh == 0U || cands[i] < resume_thresh)) { + resume_thresh = cands[i]; + } + } + if (resume_thresh == 0U || idle_ms < resume_thresh) { if (*state == ANODE_PWR_DIMMED || *state == ANODE_PWR_LOCKED || *state == ANODE_PWR_SUSPENDED) { a.restore_brightness = true; } @@ -105,4 +116,141 @@ static inline void anode_power_policy_step(const anode_power_cfg_t *cfg, if (out) *out = a; } +static inline int anode_power_policy_next_wake_ms(const anode_power_cfg_t *cfg, + uint32_t idle_ms, + bool on_ac, + bool is_dimmed) { + int timeout_ms = 15000; + if (cfg) { + uint32_t eff_susp_ms = (cfg->suspend_ms > 0U && (cfg->suspend_on_ac || !on_ac)) ? cfg->suspend_ms : 0U; + uint32_t cands[3] = {cfg->dim_ms, cfg->lock_ms, eff_susp_ms}; + for (int i = 0; i < 3; i++) { + if (cands[i] > 0U && idle_ms < cands[i]) { + uint32_t rem = cands[i] - idle_ms; + if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; + } + } + } + if (timeout_ms < 1000) timeout_ms = 1000; + if (is_dimmed && timeout_ms > 500) timeout_ms = 500; + return timeout_ms; +} + +static inline bool anode_power_cfg_load(const char *path, anode_power_cfg_t *cfg) { + if (!cfg) return false; + *cfg = anode_power_cfg_default(); + if (!path || !path[0]) return false; + FILE *f = fopen(path, "r"); + if (!f) return false; + + char line[256]; + while (fgets(line, sizeof(line), f)) { + char *s = line; + while (*s == ' ' || *s == '\t') s++; + if (*s == '\0' || *s == '#' || *s == '\n' || *s == '\r') continue; + char *eq = strchr(s, '='); + if (!eq) continue; + *eq = '\0'; + + char *kend = eq; + while (kend > s && (kend[-1] == ' ' || kend[-1] == '\t')) { + *--kend = '\0'; + } + const char *k = s; + const char *v = eq + 1; + while (*v == ' ' || *v == '\t') v++; + if (!*v) continue; + + char *endp = NULL; + long val = strtol(v, &endp, 10); + if (endp == v) continue; + + if (strcmp(k, "DIM_SEC") == 0 || strcmp(k, "LOCK_SEC") == 0 || strcmp(k, "SUSPEND_SEC") == 0) { + long clamped = val < 0 ? 0L : (val > 86400L ? 86400L : val); + uint32_t ms = (uint32_t)clamped * 1000U; + if (strcmp(k, "DIM_SEC") == 0) cfg->dim_ms = ms; + else if (strcmp(k, "LOCK_SEC") == 0) cfg->lock_ms = ms; + else cfg->suspend_ms = ms; + } else if (strcmp(k, "SUSPEND_ON_AC") == 0) { + cfg->suspend_on_ac = (val != 0); + } else if (strcmp(k, "CRIT_BATT_PCT") == 0) { + if (val >= 1 && val <= 30) cfg->crit_batt_pct = (int)val; + } + } + fclose(f); + return true; +} + +static inline bool anode_power_cfg_save(const char *path, const anode_power_cfg_t *cfg) { + if (!path || !path[0] || !cfg) return false; + char tmp[1088]; + int tn = snprintf(tmp, sizeof(tmp), "%s.tmp", path); + if (tn <= 0 || (size_t)tn >= sizeof(tmp)) return false; + + FILE *f = fopen(tmp, "w"); + if (!f) return false; + int wn = fprintf( + f, + "# ANODE idle power policy (0 disables dim/lock/suspend)\n" + "DIM_SEC=%u\n" + "LOCK_SEC=%u\n" + "SUSPEND_SEC=%u\n" + "SUSPEND_ON_AC=%d\n" + "CRIT_BATT_PCT=%d\n", + (unsigned)(cfg->dim_ms / 1000U), + (unsigned)(cfg->lock_ms / 1000U), + (unsigned)(cfg->suspend_ms / 1000U), + cfg->suspend_on_ac ? 1 : 0, + cfg->crit_batt_pct); + bool bad = (wn < 0) || ferror(f); + if (fclose(f) != 0) bad = true; + if (bad || rename(tmp, path) != 0) { + remove(tmp); + return false; + } + return true; +} + +static inline uint32_t anode_power_step_presets(uint32_t cur_ms, int dir, const uint32_t *presets, size_t count) { + if (!presets || count == 0) return cur_ms; + uint32_t cur_sec = cur_ms / 1000U; + if (dir > 0) { + for (size_t i = 0; i < count; i++) { + if (presets[i] > cur_sec) return presets[i] * 1000U; + } + return presets[count - 1] * 1000U; + } + if (dir < 0) { + for (size_t i = count; i > 0; i--) { + if (presets[i - 1] < cur_sec) return presets[i - 1] * 1000U; + } + return presets[0] * 1000U; + } + return cur_ms; +} + +static inline uint32_t anode_power_step_screen_timeout_ms(uint32_t cur_ms, int dir) { + static const uint32_t PRESETS_SEC[] = {0U, 30U, 60U, 120U, 180U, 300U, 600U, 900U, 1200U, 1800U, 3600U}; + return anode_power_step_presets(cur_ms, dir, PRESETS_SEC, sizeof(PRESETS_SEC) / sizeof(PRESETS_SEC[0])); +} + +static inline uint32_t anode_power_step_suspend_timeout_ms(uint32_t cur_ms, int dir) { + static const uint32_t PRESETS_SEC[] = {0U, 300U, 600U, 900U, 1200U, 1800U, 2700U, 3600U, 7200U}; + return anode_power_step_presets(cur_ms, dir, PRESETS_SEC, sizeof(PRESETS_SEC) / sizeof(PRESETS_SEC[0])); +} + +static inline void anode_power_format_timeout(uint32_t ms, char *out, size_t sz) { + if (!out || sz == 0) return; + uint32_t sec = ms / 1000U; + if (sec == 0U) { + snprintf(out, sz, "Off"); + } else if (sec >= 3600U && (sec % 3600U) == 0U) { + snprintf(out, sz, "%uh", (unsigned)(sec / 3600U)); + } else if (sec >= 60U && (sec % 60U) == 0U) { + snprintf(out, sz, "%um", (unsigned)(sec / 60U)); + } else { + snprintf(out, sz, "%us", (unsigned)sec); + } +} + #endif /* ANODE_POWER_POLICY_H */ diff --git a/src/common/anode_xth.h b/src/common/anode_xth.h new file mode 100644 index 0000000..b878cd4 --- /dev/null +++ b/src/common/anode_xth.h @@ -0,0 +1,522 @@ +/* + * ANODE Unified .xth Theme Parser, Validator & Atomic Writer (header-only POSIX C99/C11) + */ +#ifndef ANODE_XTH_H +#define ANODE_XTH_H + +#include +#include +#include +#include +#include +#include + +enum { + ANODE_XTH_BG_MAIN = 0, + ANODE_XTH_BG_BAR, + ANODE_XTH_BG_HEADER, + ANODE_XTH_BG_FOOTER, + ANODE_XTH_BG_OVERLAY, + ANODE_XTH_BG_ALT_EVEN, + ANODE_XTH_BG_ALT_ODD, + ANODE_XTH_BG_INPUT, + ANODE_XTH_BG_INPUT_FOCUS, + ANODE_XTH_BG_BUTTON, + ANODE_XTH_BG_SEARCH, + ANODE_XTH_BG_BUBBLE_IN, + ANODE_XTH_BG_BUBBLE_OUT, + ANODE_XTH_BG_TOAST, + ANODE_XTH_FG_MAIN, + ANODE_XTH_FG_BRIGHT, + ANODE_XTH_FG_MUTED, + ANODE_XTH_SEL_BG, + ANODE_XTH_SEL_FG, + ANODE_XTH_ACCENT, + ANODE_XTH_ACCENT_ALT, + ANODE_XTH_HIGHLIGHT, + ANODE_XTH_BORDER, + ANODE_XTH_DIVIDER, + ANODE_XTH_SUCCESS, + ANODE_XTH_INFO, + ANODE_XTH_WARNING, + ANODE_XTH_DANGER, + ANODE_XTH_DANGER_BG, + ANODE_XTH_DWM_NORM_BG, + ANODE_XTH_DWM_NORM_FG, + ANODE_XTH_DWM_NORM_BD, + ANODE_XTH_DWM_SEL_BG, + ANODE_XTH_DWM_SEL_FG, + ANODE_XTH_DWM_SEL_BD, + ANODE_XTH_DMENU_BG, + ANODE_XTH_DMENU_FG, + ANODE_XTH_DMENU_SEL_BG, + ANODE_XTH_DMENU_SEL_FG, + ANODE_XTH_DMENU_OUT_BG, + ANODE_XTH_DMENU_OUT_FG, + ANODE_XTH_ST_BG, + ANODE_XTH_ST_FG, + ANODE_XTH_ST_CURSOR, + ANODE_XTH_ST_REVCURSOR, + ANODE_XTH_ST_COLOR0, + ANODE_XTH_ST_COLOR15 = ANODE_XTH_ST_COLOR0 + 15, + ANODE_XTH_COLOR_COUNT +}; + +#define ANODE_XTH_MAX_EXTRA 64 + +typedef struct { + const char *key; + const char *label; + const char *def_hex; +} anode_xth_slot_t; + +typedef struct { + char name[64]; + int is_dark; + char font_face[96]; + char ui_font_face[96]; + char icon_font_face[96]; + char icon_theme[64]; + char qt_theme[64]; + int base_font_size; + int dwm_borderpx; + char colors[ANODE_XTH_COLOR_COUNT][16]; + char extra_keys[ANODE_XTH_MAX_EXTRA][64]; + char extra_vals[ANODE_XTH_MAX_EXTRA][256]; + int n_extra; +} anode_xth_t; + +static const anode_xth_slot_t ANODE_XTH_SLOTS[ANODE_XTH_COLOR_COUNT] = { + {"theme.bgMain", "Main background", "#08090b"}, + {"theme.bgBar", "Bar background", "#0e1014"}, + {"theme.bgHeader", "Header background", "#12151a"}, + {"theme.bgFooter", "Footer background", "#0b0d11"}, + {"theme.bgOverlay", "Overlay / Popup", "#171b22"}, + {"theme.bgAltEven", "Row even", "#101318"}, + {"theme.bgAltOdd", "Row odd", "#14181f"}, + {"theme.bgInput", "Input background", "#161a21"}, + {"theme.bgInputFocus", "Input focused bg", "#1e232c"}, + {"theme.bgButton", "Button background", "#1c212a"}, + {"theme.bgSearch", "Search background", "#191e27"}, + {"theme.bgBubbleIn", "Bubble in", "#181d25"}, + {"theme.bgBubbleOut", "Bubble out", "#252c38"}, + {"theme.bgToast", "Toast background", "#1c222b"}, + {"theme.fgMain", "Main text", "#e4e8ee"}, + {"theme.fgBright", "Bright text", "#f5f7fa"}, + {"theme.fgMuted", "Muted text", "#89929f"}, + {"theme.selBg", "Selection bg", "#38414f"}, + {"theme.selFg", "Selection text", "#f5f7fa"}, + {"theme.accent", "Primary accent", "#cfd6e0"}, + {"theme.accentAlt", "Secondary accent", "#e5eaf0"}, + {"theme.highlight", "Focus / Highlight", "#e2bc72"}, + {"theme.border", "Border", "#2d3440"}, + {"theme.divider", "Divider", "#20252f"}, + {"theme.success", "Success", "#79cf9c"}, + {"theme.info", "Info", "#9eb3c8"}, + {"theme.warning", "Warning", "#e2bc72"}, + {"theme.danger", "Danger", "#e07a7a"}, + {"theme.dangerBg", "Danger background", "#3f1d20"}, + {"dwm.normbgcolor", "DWM bar normal bg", "#0e1014"}, + {"dwm.normfgcolor", "DWM bar normal text", "#e4e8ee"}, + {"dwm.normbordercolor", "DWM inactive border", "#2d3440"}, + {"dwm.selbgcolor", "DWM bar selected bg", "#38414f"}, + {"dwm.selfgcolor", "DWM bar selected text", "#f5f7fa"}, + {"dwm.selbordercolor", "DWM active border", "#cfd6e0"}, + {"dmenu.background", "dmenu background", "#12151a"}, + {"dmenu.foreground", "dmenu text", "#e4e8ee"}, + {"dmenu.selbackground", "dmenu selected bg", "#38414f"}, + {"dmenu.selforeground", "dmenu selected text", "#f5f7fa"}, + {"dmenu.outbackground", "dmenu marked bg", "#191e27"}, + {"dmenu.outforeground", "dmenu marked text", "#cfd6e0"}, + {"st.background", "st background", "#08090b"}, + {"st.foreground", "st foreground", "#e4e8ee"}, + {"st.cursorColor", "st cursor", "#cfd6e0"}, + {"st.revCursorColor", "st reverse cursor", "#08090b"}, + {"st.color0", "ANSI 0 (Black)", "#08090b"}, + {"st.color1", "ANSI 1 (Red)", "#d97878"}, + {"st.color2", "ANSI 2 (Green)", "#79cf9c"}, + {"st.color3", "ANSI 3 (Yellow)", "#e2bc72"}, + {"st.color4", "ANSI 4 (Blue)", "#8ba6c4"}, + {"st.color5", "ANSI 5 (Magenta)", "#b39bc8"}, + {"st.color6", "ANSI 6 (Cyan)", "#84b8be"}, + {"st.color7", "ANSI 7 (White)", "#d5dce4"}, + {"st.color8", "ANSI 8 (Bright Black)", "#5b6370"}, + {"st.color9", "ANSI 9 (Bright Red)", "#eb9494"}, + {"st.color10", "ANSI 10 (Bright Green)","#96deb3"}, + {"st.color11", "ANSI 11 (Bright Yel)", "#edd092"}, + {"st.color12", "ANSI 12 (Bright Blue)", "#a6bdd6"}, + {"st.color13", "ANSI 13 (Bright Mag)", "#cab5dc"}, + {"st.color14", "ANSI 14 (Bright Cyan)", "#a2cdd2"}, + {"st.color15", "ANSI 15 (Bright White)","#f5f7fa"} +}; + +static inline int anode_xth_hex_nibble(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +static inline bool anode_xth_parse_hex(const char *s, int *r, int *g, int *b) { + if (!s) return false; + while (*s == ' ' || *s == '\t') s++; + if (*s == '#') s++; + size_t len = strlen(s); + while (len > 0 && (s[len - 1] == ' ' || s[len - 1] == '\t' || s[len - 1] == '\r' || s[len - 1] == '\n')) len--; + if (len == 6) { + int d[6]; + for (int i = 0; i < 6; i++) { + d[i] = anode_xth_hex_nibble(s[i]); + if (d[i] < 0) return false; + } + if (r) *r = (d[0] << 4) | d[1]; + if (g) *g = (d[2] << 4) | d[3]; + if (b) *b = (d[4] << 4) | d[5]; + return true; + } + if (len == 3) { + int d[3]; + for (int i = 0; i < 3; i++) { + d[i] = anode_xth_hex_nibble(s[i]); + if (d[i] < 0) return false; + } + if (r) *r = (d[0] << 4) | d[0]; + if (g) *g = (d[1] << 4) | d[1]; + if (b) *b = (d[2] << 4) | d[2]; + return true; + } + return false; +} + +static inline void anode_xth_format_hex(int r, int g, int b, char *out, size_t sz) { + if (r < 0) r = 0; + if (r > 255) r = 255; + if (g < 0) g = 0; + if (g > 255) g = 255; + if (b < 0) b = 0; + if (b > 255) b = 255; + snprintf(out, sz, "#%02x%02x%02x", r, g, b); +} + +static inline double anode_xth_rel_lum(const char *hex) { + int r = 0, g = 0, b = 0; + if (!anode_xth_parse_hex(hex, &r, &g, &b)) return 0.0; + double ch[3] = {r / 255.0, g / 255.0, b / 255.0}; + for (int i = 0; i < 3; i++) { + ch[i] = (ch[i] <= 0.03928) ? (ch[i] / 12.92) : pow((ch[i] + 0.055) / 1.055, 2.4); + } + return 0.2126 * ch[0] + 0.7152 * ch[1] + 0.0722 * ch[2]; +} + +static inline double anode_xth_contrast_ratio(const char *hex_a, const char *hex_b) { + double l1 = anode_xth_rel_lum(hex_a); + double l2 = anode_xth_rel_lum(hex_b); + if (l1 < l2) { + double tmp = l1; + l1 = l2; + l2 = tmp; + } + return (l1 + 0.05) / (l2 + 0.05); +} + +static inline void anode_xth_sanitize_name(const char *raw, char *out, size_t sz) { + if (!out || sz == 0) return; + out[0] = '\0'; + if (!raw) return; + size_t j = 0; + for (const char *p = raw; *p && j + 1 < sz; p++) { + unsigned char ch = (unsigned char)*p; + if (isalnum(ch) || ch == '-' || ch == '_') { + out[j++] = (char)ch; + } else if (ch == ' ' || ch == '.') { + if (j > 0 && out[j - 1] != '_') out[j++] = '_'; + } + } + while (j > 0 && out[j - 1] == '_') j--; + out[j] = '\0'; + if (strcmp(out, ".") == 0 || strcmp(out, "..") == 0) out[0] = '\0'; +} + +static inline void anode_xth_init_anodized(anode_xth_t *x) { + if (!x) return; + memset(x, 0, sizeof(*x)); + snprintf(x->name, sizeof(x->name), "Anodized"); + x->is_dark = 1; + snprintf(x->font_face, sizeof(x->font_face), "Fira Code"); + snprintf(x->ui_font_face, sizeof(x->ui_font_face), "Roboto"); + snprintf(x->icon_font_face, sizeof(x->icon_font_face), "DejaVuSansM Nerd Font"); + snprintf(x->icon_theme, sizeof(x->icon_theme), "Adwaita"); + snprintf(x->qt_theme, sizeof(x->qt_theme), "Fusion"); + x->base_font_size = 15; + x->dwm_borderpx = 2; + for (int i = 0; i < ANODE_XTH_COLOR_COUNT; i++) { + snprintf(x->colors[i], sizeof(x->colors[i]), "%s", ANODE_XTH_SLOTS[i].def_hex); + } +} + +static inline void anode_xth_sync_derived(anode_xth_t *x) { + if (!x) return; + snprintf(x->colors[ANODE_XTH_DWM_NORM_BG], 16, "%s", x->colors[ANODE_XTH_BG_BAR]); + snprintf(x->colors[ANODE_XTH_DWM_NORM_FG], 16, "%s", x->colors[ANODE_XTH_FG_MAIN]); + snprintf(x->colors[ANODE_XTH_DWM_NORM_BD], 16, "%s", x->colors[ANODE_XTH_BORDER]); + snprintf(x->colors[ANODE_XTH_DWM_SEL_BG], 16, "%s", x->colors[ANODE_XTH_SEL_BG]); + snprintf(x->colors[ANODE_XTH_DWM_SEL_FG], 16, "%s", x->colors[ANODE_XTH_SEL_FG]); + snprintf(x->colors[ANODE_XTH_DWM_SEL_BD], 16, "%s", x->colors[ANODE_XTH_ACCENT]); + + snprintf(x->colors[ANODE_XTH_DMENU_BG], 16, "%s", x->colors[ANODE_XTH_BG_HEADER]); + snprintf(x->colors[ANODE_XTH_DMENU_FG], 16, "%s", x->colors[ANODE_XTH_FG_MAIN]); + snprintf(x->colors[ANODE_XTH_DMENU_SEL_BG], 16, "%s", x->colors[ANODE_XTH_SEL_BG]); + snprintf(x->colors[ANODE_XTH_DMENU_SEL_FG], 16, "%s", x->colors[ANODE_XTH_SEL_FG]); + snprintf(x->colors[ANODE_XTH_DMENU_OUT_BG], 16, "%s", x->colors[ANODE_XTH_BG_SEARCH]); + snprintf(x->colors[ANODE_XTH_DMENU_OUT_FG], 16, "%s", x->colors[ANODE_XTH_ACCENT]); + + snprintf(x->colors[ANODE_XTH_ST_BG], 16, "%s", x->colors[ANODE_XTH_BG_MAIN]); + snprintf(x->colors[ANODE_XTH_ST_FG], 16, "%s", x->colors[ANODE_XTH_FG_MAIN]); + snprintf(x->colors[ANODE_XTH_ST_CURSOR], 16, "%s", x->colors[ANODE_XTH_ACCENT]); + snprintf(x->colors[ANODE_XTH_ST_REVCURSOR], 16, "%s", x->colors[ANODE_XTH_BG_MAIN]); +} + +static inline int anode_xth_find_slot(const char *key) { + if (!key) return -1; + for (int i = 0; i < ANODE_XTH_COLOR_COUNT; i++) { + if (strcmp(ANODE_XTH_SLOTS[i].key, key) == 0) return i; + } + return -1; +} + +static inline char *anode_xth_trim(char *s) { + while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n') s++; + size_t len = strlen(s); + while (len > 0 && (s[len - 1] == ' ' || s[len - 1] == '\t' || s[len - 1] == '\r' || s[len - 1] == '\n')) { + s[--len] = '\0'; + } + return s; +} + +static inline bool anode_xth_load_file(const char *path, anode_xth_t *out) { + if (!path || !path[0] || !out) return false; + FILE *f = fopen(path, "rb"); + if (!f) return false; + + unsigned char probe[512]; + size_t nread = fread(probe, 1, sizeof(probe), f); + if (nread == 0) { + fclose(f); + return false; + } + for (size_t i = 0; i < nread; i++) { + if (probe[i] == '\0') { + fclose(f); + return false; + } + } + rewind(f); + + anode_xth_t tmp; + anode_xth_init_anodized(&tmp); + tmp.name[0] = '\0'; + int has_is_dark = -1; + int kv_count = 0; + bool has_theme_key = false; + + char line[512]; + while (fgets(line, sizeof(line), f)) { + char *s = anode_xth_trim(line); + if (!s[0] || s[0] == '!' || s[0] == '#') continue; + char *colon = strchr(s, ':'); + if (!colon || colon == s) continue; + *colon = '\0'; + char *k = anode_xth_trim(s); + char *v = anode_xth_trim(colon + 1); + if (!k[0] || !v[0]) continue; + kv_count++; + + if (strncmp(k, "theme.", 6) == 0) has_theme_key = true; + + int slot = anode_xth_find_slot(k); + if (slot >= 0) { + int r = 0, g = 0, b = 0; + if (anode_xth_parse_hex(v, &r, &g, &b)) { + anode_xth_format_hex(r, g, b, tmp.colors[slot], sizeof(tmp.colors[slot])); + } + continue; + } + + if (strcmp(k, "theme.name") == 0) { + snprintf(tmp.name, sizeof(tmp.name), "%s", v); + } else if (strcmp(k, "theme.isDark") == 0) { + has_is_dark = (atoi(v) != 0) ? 1 : 0; + } else if (strcmp(k, "theme.fontFace") == 0) { + snprintf(tmp.font_face, sizeof(tmp.font_face), "%s", v); + } else if (strcmp(k, "theme.uiFontFace") == 0) { + snprintf(tmp.ui_font_face, sizeof(tmp.ui_font_face), "%s", v); + } else if (strcmp(k, "theme.iconFontFace") == 0) { + snprintf(tmp.icon_font_face, sizeof(tmp.icon_font_face), "%s", v); + } else if (strcmp(k, "theme.iconTheme") == 0) { + snprintf(tmp.icon_theme, sizeof(tmp.icon_theme), "%s", v); + } else if (strcmp(k, "theme.qtTheme") == 0) { + snprintf(tmp.qt_theme, sizeof(tmp.qt_theme), "%s", v); + } else if (strcmp(k, "theme.baseFontSize") == 0) { + int sz = atoi(v); + if (sz >= 8 && sz <= 28) tmp.base_font_size = sz; + } else if (strcmp(k, "dwm.borderpx") == 0) { + int bw = atoi(v); + if (bw >= 1 && bw <= 6) tmp.dwm_borderpx = bw; + } else if (strcmp(k, "dwm.background") == 0 || strcmp(k, "dwm.foreground") == 0 || + strcmp(k, "dwm.border") == 0 || strcmp(k, "dwm.selbackground") == 0 || + strcmp(k, "dwm.selforeground") == 0 || strcmp(k, "dwm.selborder") == 0) { + int r = 0, g = 0, b = 0; + if (anode_xth_parse_hex(v, &r, &g, &b)) { + int alias_idx = (strcmp(k, "dwm.background") == 0) ? ANODE_XTH_DWM_NORM_BG + : (strcmp(k, "dwm.foreground") == 0) ? ANODE_XTH_DWM_NORM_FG + : (strcmp(k, "dwm.border") == 0) ? ANODE_XTH_DWM_NORM_BD + : (strcmp(k, "dwm.selbackground") == 0) ? ANODE_XTH_DWM_SEL_BG + : (strcmp(k, "dwm.selforeground") == 0) ? ANODE_XTH_DWM_SEL_FG + : ANODE_XTH_DWM_SEL_BD; + anode_xth_format_hex(r, g, b, tmp.colors[alias_idx], 16); + } + } else if (strcmp(k, "theme.gtkTheme") == 0 || strcmp(k, "*TkTheme") == 0 || + strcmp(k, "Xft.dpi") == 0 || strcmp(k, "Xcursor.size") == 0 || + strcmp(k, "dwm.font") == 0 || strcmp(k, "dmenu.font") == 0 || + strcmp(k, "st.font") == 0) { + /* Managed automatically when serialized */ + } else if (tmp.n_extra < ANODE_XTH_MAX_EXTRA) { + bool dup = false; + for (int ei = 0; ei < tmp.n_extra; ei++) { + if (strcmp(tmp.extra_keys[ei], k) == 0) { + snprintf(tmp.extra_vals[ei], sizeof(tmp.extra_vals[ei]), "%s", v); + dup = true; + break; + } + } + if (!dup) { + snprintf(tmp.extra_keys[tmp.n_extra], sizeof(tmp.extra_keys[0]), "%s", k); + snprintf(tmp.extra_vals[tmp.n_extra], sizeof(tmp.extra_vals[0]), "%s", v); + tmp.n_extra++; + } + } + } + fclose(f); + + if (kv_count == 0 || !has_theme_key) return false; + + if (!tmp.name[0]) { + const char *slash = strrchr(path, '/'); + const char *base = slash ? slash + 1 : path; + char raw_name[64]; + snprintf(raw_name, sizeof(raw_name), "%s", base); + size_t bl = strlen(raw_name); + if (bl > 4 && strcmp(raw_name + bl - 4, ".xth") == 0) raw_name[bl - 4] = '\0'; + anode_xth_sanitize_name(raw_name, tmp.name, sizeof(tmp.name)); + if (!tmp.name[0]) snprintf(tmp.name, sizeof(tmp.name), "Custom"); + } + + if (has_is_dark >= 0) { + tmp.is_dark = has_is_dark; + } else { + tmp.is_dark = (anode_xth_rel_lum(tmp.colors[ANODE_XTH_BG_MAIN]) < 0.20) ? 1 : 0; + } + + *out = tmp; + return true; +} + +static inline bool anode_xth_save_file(const char *path, const anode_xth_t *x) { + if (!path || !path[0] || !x) return false; + char safe_name[64]; + anode_xth_sanitize_name(x->name, safe_name, sizeof(safe_name)); + if (!safe_name[0]) return false; + + char tmp_path[576]; + snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", path); + FILE *f = fopen(tmp_path, "w"); + if (!f) return false; + + fprintf(f, "! ANODE unified .xth theme: %s (%s)\n", safe_name, x->is_dark ? "Dark" : "Light"); + fprintf(f, "theme.name: %s\n", safe_name); + fprintf(f, "theme.isDark: %d\n", x->is_dark ? 1 : 0); + fprintf(f, "theme.fontFace: %s\n", x->font_face[0] ? x->font_face : "Fira Code"); + fprintf(f, "theme.uiFontFace: %s\n", x->ui_font_face[0] ? x->ui_font_face : "Roboto"); + fprintf(f, "theme.iconFontFace: %s\n", x->icon_font_face[0] ? x->icon_font_face : "DejaVuSansM Nerd Font"); + fprintf(f, "theme.baseFontSize: %d\n", x->base_font_size >= 8 ? x->base_font_size : 15); + fprintf(f, "theme.gtkTheme: ANODE-%s\n", safe_name); + fprintf(f, "theme.qtTheme: %s\n", x->qt_theme[0] ? x->qt_theme : "Fusion"); + fprintf(f, "theme.iconTheme: %s\n", x->icon_theme[0] ? x->icon_theme : "Adwaita"); + fprintf(f, "*TkTheme: gtkTtk\n\n"); + + fprintf(f, "Xft.dpi: 96\n"); + fprintf(f, "Xft.antialias: 1\n"); + fprintf(f, "Xft.hinting: 1\n"); + fprintf(f, "Xcursor.size: 24\n\n"); + + for (int i = 0; i <= ANODE_XTH_DANGER_BG; i++) { + fprintf(f, "%s: %s\n", ANODE_XTH_SLOTS[i].key, x->colors[i]); + } + fprintf(f, "\ndwm.borderpx: %d\n", x->dwm_borderpx >= 1 ? x->dwm_borderpx : 2); + fprintf(f, "dwm.font: %s, %s %dpx\n", + x->font_face[0] ? x->font_face : "Fira Code", + x->icon_font_face[0] ? x->icon_font_face : "DejaVuSansM Nerd Font", + x->base_font_size >= 8 ? x->base_font_size : 15); + for (int i = ANODE_XTH_DWM_NORM_BG; i <= ANODE_XTH_DWM_SEL_BD; i++) { + fprintf(f, "%s: %s\n", ANODE_XTH_SLOTS[i].key, x->colors[i]); + } + + fprintf(f, "\ndmenu.font: %s, %s %dpx\n", + x->font_face[0] ? x->font_face : "Fira Code", + x->icon_font_face[0] ? x->icon_font_face : "DejaVuSansM Nerd Font", + x->base_font_size >= 8 ? x->base_font_size : 15); + for (int i = ANODE_XTH_DMENU_BG; i <= ANODE_XTH_DMENU_OUT_FG; i++) { + fprintf(f, "%s: %s\n", ANODE_XTH_SLOTS[i].key, x->colors[i]); + } + + fprintf(f, "\nst.font: %s:size=13:style=Regular:antialias=true:autohint=true\n", + x->font_face[0] ? x->font_face : "Fira Code"); + for (int i = ANODE_XTH_ST_BG; i <= ANODE_XTH_ST_COLOR15; i++) { + fprintf(f, "%s: %s\n", ANODE_XTH_SLOTS[i].key, x->colors[i]); + } + + if (x->n_extra > 0) { + fprintf(f, "\n"); + for (int i = 0; i < x->n_extra; i++) { + fprintf(f, "%s: %s\n", x->extra_keys[i], x->extra_vals[i]); + } + } + + if (fclose(f) != 0) { + remove(tmp_path); + return false; + } + if (rename(tmp_path, path) != 0) { + remove(tmp_path); + return false; + } + return true; +} + +static inline bool anode_xth_import_file(const char *src_path, const char *dest_dir, + const char *override_name, + char *dest_out, size_t dest_sz) { + if (!src_path || !dest_dir || !dest_dir[0]) return false; + anode_xth_t x; + if (!anode_xth_load_file(src_path, &x)) return false; + + char safe_name[64]; + anode_xth_sanitize_name((override_name && override_name[0]) ? override_name : x.name, + safe_name, sizeof(safe_name)); + if (!safe_name[0]) return false; + snprintf(x.name, sizeof(x.name), "%s", safe_name); + + char dest[600]; + int dn = snprintf(dest, sizeof(dest), "%s/%s.xth", dest_dir, safe_name); + if (dn <= 0 || (size_t)dn >= sizeof(dest)) return false; + if (!anode_xth_save_file(dest, &x)) return false; + if (dest_out && dest_sz > 0) { + size_t dlen = strlen(dest); + if (dlen >= dest_sz) dlen = dest_sz - 1; + memcpy(dest_out, dest, dlen); + dest_out[dlen] = '\0'; + } + return true; +} + +#endif /* ANODE_XTH_H */ diff --git a/src/daemons/anode-powerd.c b/src/daemons/anode-powerd.c index c1d9c6b..ae06b99 100644 --- a/src/daemons/anode-powerd.c +++ b/src/daemons/anode-powerd.c @@ -55,37 +55,11 @@ static bool lock_running(void) { } static void load_power_cfg(anode_power_cfg_t *cfg) { - *cfg = anode_power_cfg_default(); char cdir[512]; anode_config_dir(cdir, sizeof(cdir)); char p[576]; snprintf(p, sizeof(p), "%s/power.conf", cdir); - FILE *f = fopen(p, "r"); - if (!f) return; - char line[256]; - while (fgets(line, sizeof(line), f)) { - char *s = line; - while (*s == ' ' || *s == '\t') s++; - if (*s == '\0' || *s == '#' || *s == '\n') continue; - char *eq = strchr(s, '='); - if (!eq) continue; - *eq = '\0'; - const char *k = s; - const char *v = eq + 1; - long val = atol(v); - if (strcmp(k, "DIM_SEC") == 0) { - cfg->dim_ms = val > 0 ? (uint32_t)val * 1000U : 0U; - } else if (strcmp(k, "LOCK_SEC") == 0) { - cfg->lock_ms = val > 0 ? (uint32_t)val * 1000U : 0U; - } else if (strcmp(k, "SUSPEND_SEC") == 0) { - cfg->suspend_ms = val > 0 ? (uint32_t)val * 1000U : 0U; - } else if (strcmp(k, "SUSPEND_ON_AC") == 0) { - cfg->suspend_on_ac = (val != 0); - } else if (strcmp(k, "CRIT_BATT_PCT") == 0) { - if (val >= 1 && val <= 30) cfg->crit_batt_pct = (int)val; - } - } - fclose(f); + anode_power_cfg_load(p, cfg); } int main(void) { @@ -159,19 +133,7 @@ int main(void) { } } - int timeout_ms = 15000; - if (cfg.dim_ms > 0 && idle_ms < cfg.dim_ms) { - uint32_t rem = cfg.dim_ms - idle_ms; - if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; - } else if (cfg.lock_ms > 0 && idle_ms < cfg.lock_ms) { - uint32_t rem = cfg.lock_ms - idle_ms; - if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; - } else if (cfg.suspend_ms > 0 && !bat.on_ac && idle_ms < cfg.suspend_ms) { - uint32_t rem = cfg.suspend_ms - idle_ms; - if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; - } - if (timeout_ms < 1000) timeout_ms = 1000; - if (is_dimmed && timeout_ms > 500) timeout_ms = 500; + int timeout_ms = anode_power_policy_next_wake_ms(&cfg, idle_ms, bat.on_ac, is_dimmed); struct pollfd pfds[2]; nfds_t nfds = 0; diff --git a/src/dmenu/config.def.h b/src/dmenu/config.def.h index 9ee7c98..c685ddf 100644 --- a/src/dmenu/config.def.h +++ b/src/dmenu/config.def.h @@ -9,9 +9,9 @@ static const char *fonts[] = { static const char *prompt = NULL; static const char *colors[SchemeLast][2] = { /* fg bg */ - [SchemeNorm] = { "#e6e1cf", "#0b0e14" }, - [SchemeSel] = { "#ffffff", "#2b5278" }, - [SchemeOut] = { "#ffffff", "#243040" }, + [SchemeNorm] = { "#e4e8ee", "#12151a" }, + [SchemeSel] = { "#f5f7fa", "#38414f" }, + [SchemeOut] = { "#cfd6e0", "#191e27" }, }; static unsigned int lines = 12; static unsigned int lineheight = 36; diff --git a/src/dmenu/config.h b/src/dmenu/config.h index 9ee7c98..c685ddf 100644 --- a/src/dmenu/config.h +++ b/src/dmenu/config.h @@ -9,9 +9,9 @@ static const char *fonts[] = { static const char *prompt = NULL; static const char *colors[SchemeLast][2] = { /* fg bg */ - [SchemeNorm] = { "#e6e1cf", "#0b0e14" }, - [SchemeSel] = { "#ffffff", "#2b5278" }, - [SchemeOut] = { "#ffffff", "#243040" }, + [SchemeNorm] = { "#e4e8ee", "#12151a" }, + [SchemeSel] = { "#f5f7fa", "#38414f" }, + [SchemeOut] = { "#cfd6e0", "#191e27" }, }; static unsigned int lines = 12; static unsigned int lineheight = 36; diff --git a/src/dwm/config.def.h b/src/dwm/config.def.h index 8cb0695..8d1d7b8 100644 --- a/src/dwm/config.def.h +++ b/src/dwm/config.def.h @@ -17,12 +17,12 @@ static unsigned int systrayspacing = 4; static const int systraypinningfailfirst = 1; static const int showsystray = 1; static const char *font = "Fira Code, DejaVuSansM Nerd Font 15px"; -static char normbgcolor[64] = "#0b0e14"; -static char normbordercolor[64] = "#283444"; -static char normfgcolor[64] = "#e6e1cf"; -static char selbgcolor[64] = "#2b5278"; -static char selbordercolor[64] = "#59c2ff"; -static char selfgcolor[64] = "#ffffff"; +static char normbgcolor[64] = "#0e1014"; +static char normbordercolor[64] = "#2d3440"; +static char normfgcolor[64] = "#e4e8ee"; +static char selbgcolor[64] = "#38414f"; +static char selbordercolor[64] = "#cfd6e0"; +static char selfgcolor[64] = "#f5f7fa"; static char *colors[][3] = { /* fg bg border */ [SchemeNorm] = { normfgcolor, normbgcolor, normbordercolor }, diff --git a/src/dwm/config.h b/src/dwm/config.h index 8cb0695..8d1d7b8 100644 --- a/src/dwm/config.h +++ b/src/dwm/config.h @@ -17,12 +17,12 @@ static unsigned int systrayspacing = 4; static const int systraypinningfailfirst = 1; static const int showsystray = 1; static const char *font = "Fira Code, DejaVuSansM Nerd Font 15px"; -static char normbgcolor[64] = "#0b0e14"; -static char normbordercolor[64] = "#283444"; -static char normfgcolor[64] = "#e6e1cf"; -static char selbgcolor[64] = "#2b5278"; -static char selbordercolor[64] = "#59c2ff"; -static char selfgcolor[64] = "#ffffff"; +static char normbgcolor[64] = "#0e1014"; +static char normbordercolor[64] = "#2d3440"; +static char normfgcolor[64] = "#e4e8ee"; +static char selbgcolor[64] = "#38414f"; +static char selbordercolor[64] = "#cfd6e0"; +static char selfgcolor[64] = "#f5f7fa"; static char *colors[][3] = { /* fg bg border */ [SchemeNorm] = { normfgcolor, normbgcolor, normbordercolor }, diff --git a/src/dwm/drw.c b/src/dwm/drw.c index f9300a4..862610e 100644 --- a/src/dwm/drw.c +++ b/src/dwm/drw.c @@ -146,6 +146,10 @@ int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, buf[len] = '\0'; drw_font_getexts(drw->font, buf, (unsigned int)len, &ew, &eh, markup); } + if (ew > w) { + len = 0; + buf[0] = '\0'; + } if (render && d) { if (markup) diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c index 4645716..9acdedf 100644 --- a/src/dwm/dwm.c +++ b/src/dwm/dwm.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -24,11 +25,13 @@ #ifdef XINERAMA #include #endif +#include #include #include "drw.h" #include "util.h" #include "anode_scale.h" +#include "anode_bar_fmt.h" /* macros */ #define BUTTONMASK (ButtonPressMask|ButtonReleaseMask) @@ -60,9 +63,12 @@ enum { SchemeNorm, SchemeSel }; enum { NetSupported, NetWMName, NetWMState, NetWMCheck, NetSystemTray, NetSystemTrayOP, NetSystemTrayOrientation, NetSystemTrayOrientationHorz, NetSystemTrayVisual, - NetWMFullscreen, NetWMFocused, NetActiveWindow, NetWorkarea, + NetWMFullscreen, NetWMFocused, NetWMStateSticky, NetWMStateAbove, NetWMStateHidden, + NetActiveWindow, NetWorkarea, + NetNumberOfDesktops, NetCurrentDesktop, NetDesktopNames, NetWMDesktop, NetWMWindowType, NetWMWindowTypeDialog, NetWMWindowTypeDock, NetWMStrutPartial, NetWMStrut, NetClientList, NetWMPid, NetLast }; +enum { AnodeWMState, AnodeMonState, AnodeLast }; enum { Manager, Xembed, XembedInfo, XLast }; enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMChangeState, WMLast }; enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkLauncher, @@ -214,6 +220,8 @@ static Client *nexttiled(Client *c); static unsigned long long now_ms(void); static void pop(Client *c); static void propertynotify(XEvent *e); +static void publish_desktop_names(void); +static unsigned long read_cardinal_prop(Window w, Atom prop, unsigned long *out, unsigned long max_items); static void quit(const Arg *arg); static Monitor *recttomon(int x, int y, int w, int h); static void reloadxres(const Arg *arg); @@ -228,6 +236,7 @@ static void resizemouse(const Arg *arg); static void resizerequest(XEvent *e); static void restack(Monitor *m); static void run(void); +static void save_all_wm_state(void); static void scan(void); static int sendevent(Window w, Atom proto, int m, long d0, long d1, long d2, long d3, long d4); static void sendmon(Client *c, Monitor *m); @@ -243,7 +252,10 @@ static void showhide(Client *c); static void sigchld_handler(int sig); static void sighup_handler(int sig); static void sigusr1_handler(int sig); +static void snapshot_pre_replace_state(void); static void spawn(const Arg *arg); +static void sync_client_props(Client *c); +static void sync_root_desktop_props(void); static Monitor *systraytomon(Monitor *m); static void tag(const Arg *arg); static void tagmon(const Arg *arg); @@ -297,10 +309,14 @@ static const char broken[] = "broken"; static char stext[512]; static char xres_font[256] = ""; static double ui_scale = 1.0; -static int launcher_w = 42; -static int closebtn_w = 38; +static int ui_touch = 0; +static int launcher_w = 30; +static int closebtn_w = 26; +static int tagpad = 10; +static int statpad = 6; static int screen; static int sw, sh; +static int rr_event_base = -1, rr_error_base = -1; static int bh; static int lrpad; static int (*xerrorxlib)(Display *, XErrorEvent *); @@ -337,8 +353,36 @@ static void (*handler[LASTEvent])(XEvent *) = { [SelectionClear] = selectionclear, [UnmapNotify] = unmapnotify }; -static Atom wmatom[WMLast], netatom[NetLast], xatom[XLast]; +static Atom wmatom[WMLast], netatom[NetLast], anodeatom[AnodeLast], xatom[XLast]; static Atom utf8string = None, wmselatom = None; + +#define MAX_SNAP_CLIENTS 256 +#define MAX_SNAP_MONS 16 + +typedef struct { + Window win; + int from_client_list; + int has_anode_state; + unsigned long astate[12]; + int has_desktop; + unsigned long desktop; + int is_fullscreen; + int is_sticky; + int is_above; + int has_geom; + int rx, ry, rw, rh; +} SnapClient; + +static SnapClient snap_clients[MAX_SNAP_CLIENTS]; +static int snap_nclients = 0; +static int snap_has_cur_desk = 0; +static unsigned long snap_cur_desk = 0; +static Window snap_active_win = None; +static int snap_has_mon_state = 0; +static unsigned long snap_mon_nvals = 0; +static unsigned long snap_mon_vals[3 + MAX_SNAP_MONS * 7]; +static int in_scan = 0; +static int handoff_exit = 0; static int running = 1; static Cur *cursor[CurLast]; static Clr **scheme; @@ -459,6 +503,56 @@ static void attachstack(Client *c) { c->mon->stack = c; } +static int bar_tag_w(unsigned int idx) { + return (int)drw_font_getwidth(drw, tags[idx], False) + tagpad; +} + +static int bar_lt_w(const Monitor *m) { + return (int)drw_font_getwidth(drw, m->ltsymbol, False) + tagpad; +} + +static int bar_left_w(const Monitor *m) { + int x = launcher_w; + for (unsigned int i = 0; i < LENGTH(tags); i++) + x += bar_tag_w(i); + x += bar_lt_w(m); + return x; +} + +static int bar_close_visible(int avail) { + return avail > closebtn_w + anode_scale_px(48, ui_scale); +} + +static int bar_pick_status(const Monitor *m, int left_x, int stw, char *out, size_t out_sz) { + if (!out || out_sz == 0) return 0; + out[0] = '\0'; + if (m != selmon) return 0; + int free_w = m->ww - stw - left_x; + if (free_w <= 0) return 0; + + int min_title = 0; + if (m->sel) { + int min_status = anode_scale_px(84, ui_scale); + min_title = MAX(m->ww / 3, anode_scale_px(260, ui_scale)) + closebtn_w; + if (min_title > free_w - min_status) + min_title = MAX(0, free_w - min_status); + } + int status_budget = free_w - min_title; + + char chosen[512] = ""; + int chosen_w = 0; + for (int tier = 0; tier <= 3; tier++) { + char cand[512]; + anode_bar_compact_status(stext, tier, cand, sizeof(cand)); + int cw = cand[0] ? ((int)drw_font_getwidth(drw, cand, False) + statpad * 2) : 0; + snprintf(chosen, sizeof(chosen), "%s", cand); + chosen_w = cw; + if (cw <= status_budget) break; + } + snprintf(out, out_sz, "%s", chosen); + return MIN(chosen_w, status_budget); +} + static void buttonpress(XEvent *e) { unsigned int i, x, click; Arg arg = {0}; @@ -475,23 +569,26 @@ static void buttonpress(XEvent *e) { if (ev->window == selmon->barwin) { int stw = (showsystray && selmon == systraytomon(selmon) && !systrayonleft) ? (int)getsystraywidth() : 0; - int tw = (int)TEXTW(stext) - lrpad + 4; + int left_x = bar_left_w(selmon); + char sbuf[512]; + int tw = bar_pick_status(selmon, left_x, stw, sbuf, sizeof(sbuf)); + int avail = selmon->ww - tw - stw - left_x; if (ev->x < launcher_w) { click = ClkLauncher; } else { i = 0; x = (unsigned int)launcher_w; do { - x += (int)TEXTW(tags[i]); + x += (unsigned int)bar_tag_w(i); } while (ev->x >= (int)x && ++i < LENGTH(tags)); if (i < LENGTH(tags)) { click = ClkTagBar; arg.ui = 1U << i; - } else if (ev->x < (int)x + (int)TEXTW(selmon->ltsymbol)) { + } else if (ev->x < (int)x + bar_lt_w(selmon)) { click = ClkLtSymbol; - } else if (ev->x > selmon->ww - tw - stw) { + } else if (tw > 0 && ev->x >= selmon->ww - tw - stw) { click = ClkStatusText; - } else if (selmon->sel && ev->x > selmon->ww - tw - stw - closebtn_w) { + } else if (selmon->sel && bar_close_visible(avail) && ev->x >= left_x + (avail - closebtn_w)) { click = ClkCloseBtn; } else { click = ClkWinTitle; @@ -634,13 +731,287 @@ static void acquirewm(void) { } } +static unsigned long read_cardinal_prop(Window w, Atom prop, unsigned long *out, unsigned long max_items) { + int di; + unsigned long dl, n = 0, copied = 0; + unsigned char *p = NULL; + Atom da = None; + if (!dpy || w == None || prop == None || !out || max_items == 0) + return 0; + if (XGetWindowProperty(dpy, w, prop, 0L, (long)max_items, False, AnyPropertyType, + &da, &di, &n, &dl, &p) == Success && p) { + if (di == 32 && n > 0) { + unsigned long *vals = (unsigned long *)p; + copied = MIN(n, max_items); + for (unsigned long i = 0; i < copied; i++) + out[i] = vals[i]; + } + XFree(p); + } + return copied; +} + +static unsigned long tags_to_desktop(unsigned int t) { + if ((t & TAGMASK) == TAGMASK) return 0xFFFFFFFFUL; + for (unsigned int i = 0; i < LENGTH(tags); i++) { + if (t & (1U << i)) return (unsigned long)i; + } + return 0UL; +} + +static unsigned int desktop_to_tags(unsigned long d) { + if (d == 0xFFFFFFFFUL) return TAGMASK; + if (d >= LENGTH(tags)) d = LENGTH(tags) - 1; + return 1U << d; +} + +static unsigned long layout_to_index(const Layout *lt) { + for (unsigned int i = 0; i < LENGTH(layouts); i++) { + if (lt == &layouts[i]) return (unsigned long)i; + } + return 0UL; +} + +static Monitor *mon_by_num(int num) { + for (Monitor *m = mons; m; m = m->next) { + if (m->num == num) return m; + } + return mons; +} + +static SnapClient *find_snap_client(Window w) { + for (int i = 0; i < snap_nclients; i++) { + if (snap_clients[i].win == w) return &snap_clients[i]; + } + return NULL; +} + +static void sync_client_props(Client *c) { + if (!dpy || !c) return; + if (netatom[NetWMDesktop] != None) { + unsigned long desk = tags_to_desktop(c->tags); + XChangeProperty(dpy, c->win, netatom[NetWMDesktop], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&desk, 1); + } + if (anodeatom[AnodeWMState] != None) { + unsigned long flags = 0; + if (c->isfloating) flags |= 1UL; + if (c->isfullscreen) flags |= 2UL; + if (c->isurgent) flags |= 4UL; + if (c->oldstate) flags |= 8UL; + unsigned long st[12]; + st[0] = 0x414E4431UL; + st[1] = (unsigned long)(c->tags & TAGMASK); + st[2] = flags; + st[3] = (unsigned long)(uint32_t)(int32_t)(c->mon ? c->mon->num : 0); + st[4] = (unsigned long)(uint32_t)(int32_t)c->x; + st[5] = (unsigned long)(uint32_t)(int32_t)c->y; + st[6] = (unsigned long)(uint32_t)(int32_t)c->w; + st[7] = (unsigned long)(uint32_t)(int32_t)c->h; + st[8] = (unsigned long)(uint32_t)(int32_t)c->oldx; + st[9] = (unsigned long)(uint32_t)(int32_t)c->oldy; + st[10] = (unsigned long)(uint32_t)(int32_t)c->oldw; + st[11] = (unsigned long)(uint32_t)(int32_t)c->oldh; + XChangeProperty(dpy, c->win, anodeatom[AnodeWMState], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)st, 12); + } +} + +static void sync_root_desktop_props(void) { + if (!dpy || !selmon) return; + if (netatom[NetNumberOfDesktops] != None) { + unsigned long ndesk = (unsigned long)LENGTH(tags); + XChangeProperty(dpy, root, netatom[NetNumberOfDesktops], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&ndesk, 1); + } + if (netatom[NetCurrentDesktop] != None) { + unsigned long cur = tags_to_desktop(selmon->tagset[selmon->seltags] & TAGMASK); + if (cur == 0xFFFFFFFFUL) cur = 0UL; + XChangeProperty(dpy, root, netatom[NetCurrentDesktop], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&cur, 1); + } + if (anodeatom[AnodeMonState] != None) { + unsigned long vals[3 + MAX_SNAP_MONS * 7]; + unsigned long n_mons = 0; + for (Monitor *m = mons; m && n_mons < MAX_SNAP_MONS; m = m->next) { + unsigned long base = 3 + n_mons * 7; + vals[base + 0] = (unsigned long)(m->tagset[m->seltags] & TAGMASK); + vals[base + 1] = (unsigned long)(m->tagset[m->seltags ^ 1] & TAGMASK); + vals[base + 2] = layout_to_index(m->lt[m->sellt]); + vals[base + 3] = layout_to_index(m->lt[m->sellt ^ 1]); + vals[base + 4] = (unsigned long)(long)lroundf(m->mfact * 10000.0f); + vals[base + 5] = (unsigned long)MAX(0, m->nmaster); + vals[base + 6] = m->showbar ? 1UL : 0UL; + n_mons++; + } + vals[0] = 0x414E4D31UL; + vals[1] = (unsigned long)MAX(0, selmon->num); + vals[2] = n_mons; + XChangeProperty(dpy, root, anodeatom[AnodeMonState], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)vals, (int)(3 + n_mons * 7)); + } +} + +static void publish_desktop_names(void) { + if (!dpy || netatom[NetDesktopNames] == None || utf8string == None) return; + char buf[256]; + size_t pos = 0; + for (unsigned int i = 0; i < LENGTH(tags); i++) { + size_t tl = strlen(tags[i]); + if (pos + tl + 1 >= sizeof(buf)) break; + memcpy(buf + pos, tags[i], tl + 1); + pos += tl + 1; + } + XChangeProperty(dpy, root, netatom[NetDesktopNames], utf8string, 8, + PropModeReplace, (unsigned char *)buf, (int)pos); +} + +static void save_all_wm_state(void) { + for (Monitor *m = mons; m; m = m->next) { + for (Client *c = m->clients; c; c = c->next) + sync_client_props(c); + } + sync_root_desktop_props(); + if (selmon && selmon->sel && netatom[NetActiveWindow] != None) { + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&(selmon->sel->win), 1); + } + XSync(dpy, False); +} + +static void snapshot_pre_replace_state(void) { + int (*prev_err)(Display *, XErrorEvent *) = XSetErrorHandler(xerrordummy); + Window sroot = DefaultRootWindow(dpy); + + Atom a_clist = XInternAtom(dpy, "_NET_CLIENT_LIST", False); + Atom a_cur = XInternAtom(dpy, "_NET_CURRENT_DESKTOP", False); + Atom a_act = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False); + Atom a_wmdesk = XInternAtom(dpy, "_NET_WM_DESKTOP", False); + Atom a_wmst = XInternAtom(dpy, "_NET_WM_STATE", False); + Atom a_fs = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); + Atom a_sticky = XInternAtom(dpy, "_NET_WM_STATE_STICKY", False); + Atom a_above = XInternAtom(dpy, "_NET_WM_STATE_ABOVE", False); + Atom a_ast = XInternAtom(dpy, "_ANODE_WM_STATE", False); + Atom a_mon = XInternAtom(dpy, "_ANODE_MON_STATE", False); + + snap_nclients = 0; + snap_has_cur_desk = 0; + snap_cur_desk = 0; + snap_active_win = None; + snap_has_mon_state = 0; + snap_mon_nvals = 0; + + unsigned long tmp = 0; + if (read_cardinal_prop(sroot, a_cur, &tmp, 1) >= 1) { + snap_has_cur_desk = 1; + snap_cur_desk = tmp; + } + if (read_cardinal_prop(sroot, a_act, &tmp, 1) >= 1) { + snap_active_win = (Window)tmp; + } + unsigned long mn = read_cardinal_prop(sroot, a_mon, snap_mon_vals, LENGTH(snap_mon_vals)); + if (mn >= 3 && snap_mon_vals[0] == 0x414E4D31UL) { + snap_has_mon_state = 1; + snap_mon_nvals = mn; + } + + Window cand[MAX_SNAP_CLIENTS]; + int from_clist[MAX_SNAP_CLIENTS]; + int ncand = 0; + + unsigned long clist[MAX_SNAP_CLIENTS]; + unsigned long ncl = read_cardinal_prop(sroot, a_clist, clist, MAX_SNAP_CLIENTS); + if (ncl > 0) { + for (unsigned long i = 0; i < ncl && ncand < MAX_SNAP_CLIENTS; i++) { + if ((Window)clist[i] != None) { + cand[ncand] = (Window)clist[i]; + from_clist[ncand] = 1; + ncand++; + } + } + } else { + Window d1, d2, *wins = NULL; + unsigned int num = 0; + if (XQueryTree(dpy, sroot, &d1, &d2, &wins, &num)) { + for (unsigned int i = 0; i < num && ncand < MAX_SNAP_CLIENTS; i++) { + XWindowAttributes wa; + if (!XGetWindowAttributes(dpy, wins[i], &wa) || wa.override_redirect) + continue; + cand[ncand] = wins[i]; + from_clist[ncand] = 0; + ncand++; + } + if (wins) XFree(wins); + } + } + + for (int i = 0; i < ncand && snap_nclients < MAX_SNAP_CLIENTS; i++) { + Window w = cand[i]; + SnapClient sc; + memset(&sc, 0, sizeof(sc)); + sc.win = w; + sc.from_client_list = from_clist[i]; + + if (read_cardinal_prop(w, a_ast, sc.astate, 12) == 12 && + sc.astate[0] == 0x414E4431UL) { + sc.has_anode_state = 1; + } + if (read_cardinal_prop(w, a_wmdesk, &sc.desktop, 1) >= 1) { + sc.has_desktop = 1; + } + + int di; + unsigned long dl, n = 0; + unsigned char *p = NULL; + Atom da = None; + if (XGetWindowProperty(dpy, w, a_wmst, 0L, 32L, False, XA_ATOM, + &da, &di, &n, &dl, &p) == Success && p) { + if (di == 32 && da == XA_ATOM) { + Atom *atoms = (Atom *)p; + for (unsigned long ai = 0; ai < n; ai++) { + if (atoms[ai] == a_fs) sc.is_fullscreen = 1; + if (atoms[ai] == a_sticky) sc.is_sticky = 1; + if (atoms[ai] == a_above) sc.is_above = 1; + } + } + XFree(p); + } + + Window gr = None, ch = None; + int gx = 0, gy = 0, rx = 0, ry = 0; + unsigned int gw = 0, gh = 0, gbw = 0, gdepth = 0; + if (XGetGeometry(dpy, w, &gr, &gx, &gy, &gw, &gh, &gbw, &gdepth) && gw > 0 && gh > 0) { + if (XTranslateCoordinates(dpy, w, sroot, 0, 0, &rx, &ry, &ch)) { + sc.has_geom = 1; + sc.rx = rx; + sc.ry = ry; + sc.rw = (int)gw; + sc.rh = (int)gh; + } + } + snap_clients[snap_nclients++] = sc; + } + + XSync(dpy, False); + XSetErrorHandler(prev_err); +} + static void cleanup(void) { - Arg a = {.ui = ~0U}; Layout foo = { "", NULL }; Monitor *m; size_t i; - view(&a); + handoff_exit = (replaced_by_other || restart_dwm) ? 1 : 0; + if (handoff_exit) { + save_all_wm_state(); + for (m = mons; m; m = m->next) { + for (Client *c = m->clients; c; c = c->next) + XMoveWindow(dpy, c->win, c->x, c->y); + } + } else { + Arg a = {.ui = ~0U}; + view(&a); + } selmon->lt[selmon->sellt] = &foo; for (m = mons; m; m = m->next) while (m->stack) unmanage(m->stack, 0); @@ -680,7 +1051,12 @@ static void cleanup(void) { wmcheckwin = None; drw_free(drw); XSync(dpy, False); - XDeleteProperty(dpy, root, netatom[NetActiveWindow]); + if (!handoff_exit) { + XDeleteProperty(dpy, root, netatom[NetActiveWindow]); + XDeleteProperty(dpy, root, netatom[NetCurrentDesktop]); + XDeleteProperty(dpy, root, anodeatom[AnodeMonState]); + } + handoff_exit = 0; } static void cleanupmon(Monitor *mon) { @@ -750,7 +1126,19 @@ static void clientmessage(XEvent *e) { return; } + if (cme->window == root && cme->message_type == netatom[NetCurrentDesktop]) { + Arg a = {.ui = desktop_to_tags((unsigned long)cme->data.l[0])}; + view(&a); + return; + } + if (!c) return; + if (cme->message_type == netatom[NetWMDesktop]) { + c->tags = desktop_to_tags((unsigned long)cme->data.l[0]); + sync_client_props(c); + focusarranged(c->mon); + return; + } if (cme->message_type == netatom[NetWMState]) { int was_fs = c->isfullscreen; if ((Atom)cme->data.l[1] == netatom[NetWMFullscreen] || @@ -806,41 +1194,51 @@ static void configure(Client *c) { XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce); } -static void configurenotify(XEvent *e) { +static void apply_screen_geom_change(int force_dirty) { Monitor *m; Client *c; - XConfigureEvent *ev = &e->xconfigure; - int dirty; - - if (ev->window == root) { - dirty = (sw != ev->width || sh != ev->height); - sw = ev->width; - sh = ev->height; - if (updategeom() || dirty) { - drw_resize(drw, (unsigned int)sw, (unsigned int)bh); - updatebars(); - for (m = mons; m; m = m->next) { - for (c = m->clients; c; c = c->next) { - if (c->isfullscreen) { - if (ISVISIBLE(c)) { - resizeclient(c, m->mx, m->my, m->mw, m->mh); - } else { - c->oldx = c->x; c->oldy = c->y; - c->oldw = c->w; c->oldh = c->h; - c->x = m->mx; c->y = m->my; - c->w = m->mw; c->h = m->mh; - } + int nsw = DisplayWidth(dpy, screen); + int nsh = DisplayHeight(dpy, screen); + int dirty = force_dirty || (sw != nsw || sh != nsh); + sw = nsw; + sh = nsh; + if (updategeom() || dirty) { + drw_resize(drw, (unsigned int)sw, (unsigned int)bh); + updatebars(); + for (m = mons; m; m = m->next) { + for (c = m->clients; c; c = c->next) { + if (c->isfullscreen) { + if (ISVISIBLE(c)) { + resizeclient(c, m->mx, m->my, m->mw, m->mh); + } else { + c->oldx = c->x; c->oldy = c->y; + c->oldw = c->w; c->oldh = c->h; + c->x = m->mx; c->y = m->my; + c->w = m->mw; c->h = m->mh; } + } else if (c->isfloating) { + if (c->x + c->w > m->wx + m->ww) c->x = m->wx + MAX(0, m->ww - WIDTH(c)); + if (c->y + c->h > m->wy + m->wh) c->y = m->wy + MAX(0, m->wh - HEIGHT(c)); + if (c->x < m->wx) c->x = m->wx; + if (c->y < m->wy) c->y = m->wy; } - resizebarwin(m); } - updatesystray(1); - updateworkarea(); - arrange(NULL); - for (m = mons; m; m = m->next) - restack(m); - focus(NULL); + resizebarwin(m); } + updatesystray(1); + updateworkarea(); + arrange(NULL); + for (m = mons; m; m = m->next) + restack(m); + focus(NULL); + } +} + +static void configurenotify(XEvent *e) { + XConfigureEvent *ev = &e->xconfigure; + if (ev->window == root) { + int dirty = (sw != ev->width || sh != ev->height); + apply_screen_geom_change(dirty); } } @@ -859,14 +1257,16 @@ static void configurerequest(XEvent *e) { } else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) { int ox = c->x, oy = c->y, ow = c->w, oh = c->h; m = c->mon; - if (ev->value_mask & CWX) { c->oldx = c->x; c->x = m->mx + ev->x; } - if (ev->value_mask & CWY) { c->oldy = c->y; c->y = m->my + ev->y; } + if (ev->value_mask & CWX) { c->oldx = c->x; c->x = ev->x; } + if (ev->value_mask & CWY) { c->oldy = c->y; c->y = ev->y; } if (ev->value_mask & CWWidth) { c->oldw = c->w; c->w = ev->width; } if (ev->value_mask & CWHeight) { c->oldh = c->h; c->h = ev->height; } - if ((c->x + c->w) > m->mx + m->mw && c->isfloating) - c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); - if ((c->y + c->h) > m->my + m->mh && c->isfloating) - c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); + if (c->isfloating) { + if ((c->x + c->w) > sw || c->x + c->w <= 0) + c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); + if ((c->y + c->h) > sh || c->y + c->h <= 0) + c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); + } if (ISVISIBLE(c) && (c->x != ox || c->y != oy || c->w != ow || c->h != oh)) { XMoveResizeWindow(dpy, c->win, c->x, c->y, (unsigned int)c->w, (unsigned int)c->h); if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight))) @@ -951,6 +1351,7 @@ static void drawbar(Monitor *m) { int boxw = (int)drw->font->h / 6 + 2; unsigned int i, occ = 0, urg = 0; Client *c; + char sbuf[512]; if (!m->showbar) return; @@ -960,10 +1361,11 @@ static void drawbar(Monitor *m) { drw_setscheme(drw, scheme[SchemeNorm]); drw_rect(drw, 0, 0, (unsigned int)m->ww, (unsigned int)bh, 1, 1); - if (m == selmon) { + int left_x = bar_left_w(m); + tw = bar_pick_status(m, left_x, stw, sbuf, sizeof(sbuf)); + if (tw > 0) { drw_setscheme(drw, scheme[SchemeNorm]); - tw = (int)TEXTW(stext) - lrpad / 2 + 2; - drw_text(drw, m->ww - tw - stw, 0, (unsigned int)tw, (unsigned int)bh, lrpad / 2 - 2, stext, 0, False); + drw_text(drw, m->ww - tw - stw, 0, (unsigned int)tw, (unsigned int)bh, (unsigned int)statpad, sbuf, 0, False); } for (c = m->clients; c; c = c->next) { @@ -975,7 +1377,7 @@ static void drawbar(Monitor *m) { drw_setscheme(drw, scheme[SchemeSel]); drw_rect(drw, 0, 0, (unsigned int)launcher_w, (unsigned int)bh, 1, 1); { - int iw = anode_scale_px(16, ui_scale); + int iw = anode_scale_px(14, ui_scale); int ih = MAX(anode_scale_px(2, ui_scale), 2); int ig = MAX(anode_scale_px(3, ui_scale), 3); if (iw > launcher_w - 8) iw = MAX(launcher_w - 8, 6); @@ -988,9 +1390,9 @@ static void drawbar(Monitor *m) { x = launcher_w; for (i = 0; i < LENGTH(tags); i++) { - w = (int)TEXTW(tags[i]); + w = bar_tag_w(i); drw_setscheme(drw, scheme[m->tagset[m->seltags] & (1U << i) ? SchemeSel : SchemeNorm]); - drw_text(drw, x, 0, (unsigned int)w, (unsigned int)bh, lrpad / 2, tags[i], (urg & (1U << i)) != 0, False); + drw_text(drw, x, 0, (unsigned int)w, (unsigned int)bh, (unsigned int)(tagpad / 2), tags[i], (urg & (1U << i)) != 0, False); if (occ & (1U << i)) drw_rect(drw, x + boxs, boxs, (unsigned int)boxw, (unsigned int)boxw, (m == selmon && selmon->sel && (selmon->sel->tags & (1U << i))), @@ -998,19 +1400,25 @@ static void drawbar(Monitor *m) { x += w; } - w = (int)TEXTW(m->ltsymbol); + w = bar_lt_w(m); drw_setscheme(drw, scheme[SchemeNorm]); - x = drw_text(drw, x, 0, (unsigned int)w, (unsigned int)bh, lrpad / 2, m->ltsymbol, 0, False); + x = drw_text(drw, x, 0, (unsigned int)w, (unsigned int)bh, (unsigned int)(tagpad / 2), m->ltsymbol, 0, False); int avail = m->ww - tw - stw - x; - if (avail > bh) { + if (avail > anode_scale_px(16, ui_scale)) { if (m->sel) { - int title_w = avail > closebtn_w + 24 ? avail - closebtn_w : avail; + int show_close = bar_close_visible(avail); + int title_w = show_close ? avail - closebtn_w : avail; + int tpad = anode_scale_px(8, ui_scale); + int rpad = (title_w > tpad * 2) ? anode_scale_px(6, ui_scale) : 0; drw_setscheme(drw, scheme[m == selmon ? SchemeSel : SchemeNorm]); - drw_text(drw, x, 0, (unsigned int)title_w, (unsigned int)bh, lrpad / 2, m->sel->name, 0, False); - if (m->sel->isfloating) - drw_rect(drw, x + boxs, boxs, (unsigned int)boxw, (unsigned int)boxw, m->sel->isfixed, 0); - if (avail > closebtn_w + 24) { + if (rpad > 0) + drw_rect(drw, x + title_w - rpad, 0, (unsigned int)rpad, (unsigned int)bh, 1, 1); + drw_text(drw, x, 0, (unsigned int)(title_w - rpad), (unsigned int)bh, (unsigned int)tpad, m->sel->name, 0, False); + int fboxs = MAX(boxs, 1); + if (m->sel->isfloating && title_w > fboxs + boxw) + drw_rect(drw, x + fboxs, fboxs, (unsigned int)boxw, (unsigned int)boxw, m->sel->isfixed, 0); + if (show_close) { int cpad = (closebtn_w - (int)drw_font_getwidth(drw, "\xc3\x97", False)) / 2; drw_setscheme(drw, scheme[SchemeNorm]); drw_text(drw, x + title_w, 0, (unsigned int)closebtn_w, (unsigned int)bh, (unsigned int)MAX(cpad, 4), "\xc3\x97", 0, False); @@ -1045,6 +1453,7 @@ static void enternotify(XEvent *e) { resizebarwin(m); updatesystray(1); } + updateworkarea(); } else if (!c || c == selmon->sel) { return; } @@ -1056,7 +1465,7 @@ static void expose(XEvent *e) { XExposeEvent *ev = &e->xexpose; if (ev->count == 0 && (m = wintomon(ev->window))) { drawbar(m); - if (m == selmon) updatesystray(0); + if (showsystray && m == systraytomon(m)) updatesystray(0); } } @@ -1135,6 +1544,8 @@ static void focusmon(const Arg *arg) { resizebarwin(m); updatesystray(1); } + updateworkarea(); + sync_root_desktop_props(); focus(NULL); } @@ -1406,6 +1817,7 @@ static void grid(Monitor *m) { static void incnmaster(const Arg *arg) { selmon->nmaster = MAX(selmon->nmaster + arg->i, 0); arrange(selmon); + sync_root_desktop_props(); } static void keypress(XEvent *e) { @@ -1525,11 +1937,14 @@ static void loadxres(void) { int touch_i = 0; anode_read_xres_scale_from_db(db, dpy, &dpi, &ui_scale, &touch_i); + ui_touch = touch_i ? 1 : 0; borderpx = (unsigned int)anode_scale_px((int)base_borderpx, ui_scale); snap = (unsigned int)anode_scale_px((int)base_snap, ui_scale); systrayspacing = (unsigned int)anode_scale_px((int)base_systrayspacing, ui_scale); - launcher_w = anode_scale_px(42, ui_scale); - closebtn_w = anode_scale_px(38, ui_scale); + launcher_w = anode_scale_px(ui_touch ? 38 : 30, ui_scale); + closebtn_w = anode_scale_px(ui_touch ? 34 : 26, ui_scale); + tagpad = anode_scale_px(ui_touch ? 14 : 10, ui_scale); + statpad = anode_scale_px(6, ui_scale); const char *v; if (db && (v = xrm_lookup(db, "dwm.font", NULL, NULL))) { @@ -1548,12 +1963,12 @@ static void loadxres(void) { } int cur_sz = 0; - snprintf(normbgcolor, sizeof(normbgcolor), "#0b0e14"); - snprintf(normbordercolor, sizeof(normbordercolor), "#283444"); - snprintf(normfgcolor, sizeof(normfgcolor), "#e6e1cf"); - snprintf(selbgcolor, sizeof(selbgcolor), "#2b5278"); - snprintf(selbordercolor, sizeof(selbordercolor), "#59c2ff"); - snprintf(selfgcolor, sizeof(selfgcolor), "#ffffff"); + snprintf(normbgcolor, sizeof(normbgcolor), "#0e1014"); + snprintf(normbordercolor, sizeof(normbordercolor), "#2d3440"); + snprintf(normfgcolor, sizeof(normfgcolor), "#e4e8ee"); + snprintf(selbgcolor, sizeof(selbgcolor), "#38414f"); + snprintf(selbordercolor, sizeof(selbordercolor), "#cfd6e0"); + snprintf(selfgcolor, sizeof(selfgcolor), "#f5f7fa"); if (db) { if ((v = xrm_lookup(db, "dwm.normbgcolor", "dwm.background", "theme.bgBar"))) snprintf(normbgcolor, sizeof(normbgcolor), "%s", v); @@ -1695,6 +2110,27 @@ static void manage(Window w, XWindowAttributes *wa) { Client *c, *t = NULL; Window trans = None; XWindowChanges wc; + SnapClient *sc = in_scan ? find_snap_client(w) : NULL; + unsigned long astate[12] = {0}; + int has_astate = 0; + unsigned long desk = 0; + int has_desk = 0; + + if (in_scan) { + if (read_cardinal_prop(w, anodeatom[AnodeWMState], astate, 12) == 12 && + astate[0] == 0x414E4431UL) { + has_astate = 1; + } else if (sc && sc->has_anode_state) { + memcpy(astate, sc->astate, sizeof(astate)); + has_astate = 1; + } + } + if (read_cardinal_prop(w, netatom[NetWMDesktop], &desk, 1) >= 1) { + has_desk = 1; + } else if (sc && sc->has_desktop) { + desk = sc->desktop; + has_desk = 1; + } c = ecalloc(1, sizeof(Client)); c->win = w; @@ -1705,34 +2141,106 @@ static void manage(Window w, XWindowAttributes *wa) { c->oldbw = wa->border_width; updatetitle(c); - if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) { - c->mon = t->mon; - c->tags = t->tags; + + if (has_astate) { + unsigned long flags = astate[2]; + c->mon = mon_by_num((int)(int32_t)(uint32_t)astate[3]); + c->tags = (unsigned int)(astate[1] & TAGMASK); + if (!c->tags) c->tags = c->mon->tagset[c->mon->seltags]; + c->isfloating = (flags & 1UL) ? 1 : 0; + c->oldstate = (flags & 8UL) ? 1 : 0; + if (flags & 4UL) c->isurgent = 1; + int rx = (int)(int32_t)(uint32_t)astate[4]; + int ry = (int)(int32_t)(uint32_t)astate[5]; + int rw = (int)(int32_t)(uint32_t)astate[6]; + int rh = (int)(int32_t)(uint32_t)astate[7]; + if (rw > 0 && rh > 0) { + c->x = rx; c->y = ry; c->w = rw; c->h = rh; + } + int ox = (int)(int32_t)(uint32_t)astate[8]; + int oy = (int)(int32_t)(uint32_t)astate[9]; + int ow = (int)(int32_t)(uint32_t)astate[10]; + int oh = (int)(int32_t)(uint32_t)astate[11]; + if (ow > 0 && oh > 0) { + c->oldx = ox; c->oldy = oy; c->oldw = ow; c->oldh = oh; + } + int is_fs = ((flags & 2UL) != 0) || + hasatomprop(c, netatom[NetWMState], netatom[NetWMFullscreen]); + if (is_fs) { + c->isfullscreen = 1; + c->oldbw = (int)borderpx; + c->bw = 0; + c->isfloating = 1; + c->x = c->mon->mx; + c->y = c->mon->my; + c->w = c->mon->mw; + c->h = c->mon->mh; + addwmstate(c, netatom[NetWMFullscreen]); + } else { + c->bw = (int)borderpx; + } } else { - c->mon = selmon; - applyrules(c); + if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) { + c->mon = t->mon; + c->tags = t->tags; + } else { + if (in_scan && sc && sc->has_geom && sc->rw > 0 && sc->rh > 0) + c->mon = recttomon(sc->rx, sc->ry, sc->rw, sc->rh); + else if (in_scan) + c->mon = recttomon(wa->x, wa->y, wa->width, wa->height); + else + c->mon = selmon; + applyrules(c); + } + if (has_desk) { + c->tags = desktop_to_tags(desk); + } else if (in_scan && ((sc && sc->is_sticky) || + hasatomprop(c, netatom[NetWMState], netatom[NetWMStateSticky]))) { + c->tags = TAGMASK; + } + c->bw = (int)borderpx; } - if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) - c->x = c->mon->wx + c->mon->ww - WIDTH(c); - if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh) - c->y = c->mon->wy + c->mon->wh - HEIGHT(c); - c->x = MAX(c->x, c->mon->wx); - c->y = MAX(c->y, c->mon->wy); - c->bw = (int)borderpx; + if (!c->isfullscreen) { + if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) + c->x = c->mon->wx + MAX(0, c->mon->ww - WIDTH(c)); + if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh) + c->y = c->mon->wy + MAX(0, c->mon->wh - HEIGHT(c)); + c->x = MAX(c->x, c->mon->wx); + c->y = MAX(c->y, c->mon->wy); + } wc.border_width = c->bw; XConfigureWindow(dpy, w, CWBorderWidth, &wc); XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel); configure(c); - updatewindowtype(c); + if (!has_astate) { + updatewindowtype(c); + if (in_scan && ((sc && sc->is_above) || + hasatomprop(c, netatom[NetWMState], netatom[NetWMStateAbove]))) { + c->isfloating = 1; + } + if (in_scan && c->isfloating && !c->isfullscreen && sc && sc->has_geom && + sc->rw > 0 && sc->rh > 0) { + 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) + c->x = c->mon->wx + MAX(0, c->mon->ww - WIDTH(c)); + if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh) + c->y = c->mon->wy + MAX(0, c->mon->wh - HEIGHT(c)); + c->x = MAX(c->x, c->mon->wx); + c->y = MAX(c->y, c->mon->wy); + } + if (in_scan && !c->isfullscreen && sc && sc->is_fullscreen) { + setfullscreen(c, 1); + } + } updatesizehints(c); updatewmhints(c); XSelectInput(dpy, w, EnterWindowMask | FocusChangeMask | PropertyChangeMask | StructureNotifyMask); grabbuttons(c, 0); - if (!c->isfloating) + if (!has_astate && !c->isfloating) c->isfloating = c->oldstate = (trans != None || c->isfixed); - if (c->isfloating && !c->isfullscreen && wa->x == 0 && wa->y == 0) { + if (!has_astate && !in_scan && c->isfloating && !c->isfullscreen && wa->x == 0 && wa->y == 0) { c->x = c->mon->wx + (c->mon->ww - WIDTH(c)) / 2; c->y = c->mon->wy + (c->mon->wh - HEIGHT(c)) / 2; if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) @@ -1746,15 +2254,23 @@ static void manage(Window w, XWindowAttributes *wa) { XRaiseWindow(dpy, c->win); attach(c); attachstack(c); - XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend, - (unsigned char *)&(c->win), 1); - XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, (unsigned int)c->w, (unsigned int)c->h); - setclientstate(c, NormalState); - if (c->mon == selmon) unfocus(selmon->sel, 0); - c->mon->sel = c; - arrange(c->mon); - XMapWindow(dpy, c->win); - focus(NULL); + sync_client_props(c); + if (in_scan) { + int tx = ISVISIBLE(c) ? c->x : (WIDTH(c) * -2); + XMoveResizeWindow(dpy, c->win, tx, c->y, (unsigned int)c->w, (unsigned int)c->h); + setclientstate(c, NormalState); + XMapWindow(dpy, c->win); + } else { + XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend, + (unsigned char *)&(c->win), 1); + XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, (unsigned int)c->w, (unsigned int)c->h); + setclientstate(c, NormalState); + if (c->mon == selmon) unfocus(selmon->sel, 0); + c->mon->sel = c; + arrange(c->mon); + XMapWindow(dpy, c->win); + focus(NULL); + } } static void mappingnotify(XEvent *e) { @@ -1849,6 +2365,7 @@ static void motionnotify(XEvent *e) { resizebarwin(m); updatesystray(1); } + updateworkarea(); focus(NULL); } mon = m; @@ -1903,6 +2420,7 @@ static void movemouse(const Arg *arg) { selmon = m; focus(NULL); } + sync_client_props(c); } static Client *nexttiled(Client *c) { @@ -2074,6 +2592,7 @@ static void resizemouse(const Arg *arg) { selmon = m; focus(NULL); } + sync_client_props(c); } static void resizerequest(XEvent *e) { @@ -2081,7 +2600,7 @@ static void resizerequest(XEvent *e) { Client *i; if ((i = wintosystrayicon(ev->window))) { updatesystrayicongeom(i, ev->width, ev->height); - resizebarwin(selmon); + resizebarwin(systraytomon(NULL)); updatesystray(0); } } @@ -2124,6 +2643,13 @@ static void run(void) { while (XPending(dpy) > 0) { Time evtime = CurrentTime; XNextEvent(dpy, &ev); + if (rr_event_base >= 0 && + (ev.type == rr_event_base + RRScreenChangeNotify || + ev.type == rr_event_base + RRNotify)) { + XRRUpdateConfiguration(&ev); + apply_screen_geom_change(1); + continue; + } if (extracteventtime(&ev, &evtime) && evtime != CurrentTime) last_event_time = evtime; if (handler[ev.type]) @@ -2140,6 +2666,7 @@ static void scan(void) { unsigned int i, num; Window d1, d2, *wins = NULL; XWindowAttributes wa; + in_scan = 1; if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) { for (i = 0; i < num; i++) { if (!XGetWindowAttributes(dpy, wins[i], &wa)) @@ -2151,17 +2678,48 @@ static void scan(void) { } if (wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1)) continue; - if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState) + SnapClient *sc = find_snap_client(wins[i]); + if (!isdockwin(wins[i]) && + (wa.map_state == IsViewable || getstate(wins[i]) == IconicState || + (sc && sc->from_client_list))) { manage(wins[i], &wa); + } } for (i = 0; i < num; i++) { if (!XGetWindowAttributes(dpy, wins[i], &wa)) continue; + SnapClient *sc = find_snap_client(wins[i]); if (!wa.override_redirect && XGetTransientForHint(dpy, wins[i], &d1) && - (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)) + !wintoclient(wins[i]) && + (wa.map_state == IsViewable || getstate(wins[i]) == IconicState || + (sc && sc->from_client_list))) { manage(wins[i], &wa); + } } if (wins) XFree(wins); } + in_scan = 0; + updateclientlist(); + arrange(NULL); + for (Monitor *m = mons; m; m = m->next) + restack(m); + if (snap_active_win != None) { + Client *ac = wintoclient(snap_active_win); + if (ac && ISVISIBLE(ac)) { + selmon = ac->mon; + focus(ac); + restack(selmon); + } else { + focus(NULL); + } + } else { + focus(NULL); + } + sync_root_desktop_props(); + drawbars(); + snap_nclients = 0; + snap_has_cur_desk = 0; + snap_has_mon_state = 0; + snap_active_win = None; } static void sendmon(Client *c, Monitor *m) { @@ -2173,10 +2731,38 @@ static void sendmon(Client *c, Monitor *m) { detachstack(c); c->mon = m; c->tags = m->tagset[m->seltags]; + if (c->isfullscreen) { + int ox_rel = c->oldx - oldm->mx; + int oy_rel = c->oldy - oldm->my; + int nw = MIN(c->oldw, MAX(64, m->ww - 2 * c->oldbw)); + int nh = MIN(c->oldh, MAX(64, m->wh - 2 * c->oldbw)); + c->oldx = m->wx + MAX(0, MIN(ox_rel, MAX(0, m->ww - nw))); + c->oldy = m->wy + MAX(0, MIN(oy_rel, MAX(0, m->wh - nh))); + c->oldw = nw; + c->oldh = nh; + c->x = m->mx; + c->y = m->my; + c->w = m->mw; + c->h = m->mh; + } else if (c->isfloating) { + int rx = c->x - oldm->mx; + int ry = c->y - oldm->my; + int nx = m->mx + rx; + int ny = m->my + ry; + if (nx + WIDTH(c) > m->wx + m->ww) nx = m->wx + MAX(0, m->ww - WIDTH(c)); + if (ny + HEIGHT(c) > m->wy + m->wh) ny = m->wy + MAX(0, m->wh - HEIGHT(c)); + if (nx < m->wx) nx = m->wx; + if (ny < m->wy) ny = m->wy; + c->x = nx; + c->y = ny; + } attach(c); attachstack(c); + sync_client_props(c); focusarranged(oldm); focusarranged(m); + if (ISVISIBLE(c) && (c->isfullscreen || c->isfloating)) + resizeclient(c, c->x, c->y, c->w, c->h); } static void setclientstate(Client *c, long state) { @@ -2260,6 +2846,7 @@ static void setfullscreen(Client *c, int fullscreen) { resizeclient(c, c->x, c->y, c->w, c->h); arrange(c->mon); } + sync_client_props(c); } static void setlayout(const Arg *arg) { @@ -2270,6 +2857,7 @@ static void setlayout(const Arg *arg) { snprintf(selmon->ltsymbol, sizeof selmon->ltsymbol, "%s", selmon->lt[selmon->sellt]->symbol); if (selmon->sel) arrange(selmon); else drawbar(selmon); + sync_root_desktop_props(); } static void setmfact(const Arg *arg) { @@ -2279,6 +2867,7 @@ static void setmfact(const Arg *arg) { if (f < 0.05 || f > 0.95) return; selmon->mfact = f; arrange(selmon); + sync_root_desktop_props(); } static void setup(void) { @@ -2312,6 +2901,10 @@ static void setup(void) { drw_setfont(drw, dwmfont); lrpad = (int)dwmfont->h + anode_scale_px(4, ui_scale); bh = MAX((int)dwmfont->h + anode_scale_px(6, ui_scale), anode_scale_px(24, ui_scale)); + if (XRRQueryExtension(dpy, &rr_event_base, &rr_error_base)) { + XRRSelectInput(dpy, root, + RRScreenChangeNotifyMask | RROutputChangeNotifyMask | RRCrtcChangeNotifyMask); + } updategeom(); { @@ -2336,7 +2929,14 @@ static void setup(void) { netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False); netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); netatom[NetWMFocused] = XInternAtom(dpy, "_NET_WM_STATE_FOCUSED", False); + netatom[NetWMStateSticky] = XInternAtom(dpy, "_NET_WM_STATE_STICKY", False); + netatom[NetWMStateAbove] = XInternAtom(dpy, "_NET_WM_STATE_ABOVE", False); + netatom[NetWMStateHidden] = XInternAtom(dpy, "_NET_WM_STATE_HIDDEN", False); netatom[NetWorkarea] = XInternAtom(dpy, "_NET_WORKAREA", False); + netatom[NetNumberOfDesktops] = XInternAtom(dpy, "_NET_NUMBER_OF_DESKTOPS", False); + netatom[NetCurrentDesktop] = XInternAtom(dpy, "_NET_CURRENT_DESKTOP", False); + netatom[NetDesktopNames] = XInternAtom(dpy, "_NET_DESKTOP_NAMES", False); + netatom[NetWMDesktop] = XInternAtom(dpy, "_NET_WM_DESKTOP", False); netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False); netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False); netatom[NetWMWindowTypeDock] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DOCK", False); @@ -2344,6 +2944,8 @@ static void setup(void) { netatom[NetWMStrut] = XInternAtom(dpy, "_NET_WM_STRUT", False); netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False); netatom[NetWMPid] = XInternAtom(dpy, "_NET_WM_PID", False); + anodeatom[AnodeWMState] = XInternAtom(dpy, "_ANODE_WM_STATE", False); + anodeatom[AnodeMonState] = XInternAtom(dpy, "_ANODE_MON_STATE", False); xatom[Manager] = XInternAtom(dpy, "MANAGER", False); xatom[Xembed] = XInternAtom(dpy, "_XEMBED", False); xatom[XembedInfo] = XInternAtom(dpy, "_XEMBED_INFO", False); @@ -2358,8 +2960,67 @@ static void setup(void) { updatesystray(0); updatebars(); + + { + unsigned long live_mon[3 + MAX_SNAP_MONS * 7]; + unsigned long mn = read_cardinal_prop(root, anodeatom[AnodeMonState], live_mon, LENGTH(live_mon)); + if (mn >= 3 && live_mon[0] == 0x414E4D31UL) { + snap_has_mon_state = 1; + snap_mon_nvals = mn; + memcpy(snap_mon_vals, live_mon, (size_t)mn * sizeof(unsigned long)); + } + unsigned long tmp = 0; + if (read_cardinal_prop(root, netatom[NetCurrentDesktop], &tmp, 1) >= 1) { + snap_has_cur_desk = 1; + snap_cur_desk = tmp; + } + if (read_cardinal_prop(root, netatom[NetActiveWindow], &tmp, 1) >= 1 && (Window)tmp != None) { + snap_active_win = (Window)tmp; + } + } + if (snap_has_mon_state && snap_mon_nvals >= 3) { + int sel_idx = (int)snap_mon_vals[1]; + unsigned long n_saved = snap_mon_vals[2]; + Monitor *m = mons; + for (unsigned long i = 0; i < n_saved && m && (3 + i * 7 + 6) < snap_mon_nvals; i++, m = m->next) { + unsigned long base = 3 + i * 7; + unsigned int t0 = (unsigned int)(snap_mon_vals[base + 0] & TAGMASK); + unsigned int t1 = (unsigned int)(snap_mon_vals[base + 1] & TAGMASK); + m->tagset[0] = t0 ? t0 : 1U; + m->tagset[1] = t1 ? t1 : 1U; + m->seltags = 0; + unsigned long l0 = snap_mon_vals[base + 2]; + unsigned long l1 = snap_mon_vals[base + 3]; + m->lt[0] = &layouts[l0 < LENGTH(layouts) ? l0 : 0]; + m->lt[1] = &layouts[l1 < LENGTH(layouts) ? l1 : (1 % LENGTH(layouts))]; + m->sellt = 0; + snprintf(m->ltsymbol, sizeof m->ltsymbol, "%s", m->lt[0]->symbol); + double mf = (double)snap_mon_vals[base + 4] / 10000.0; + if (mf >= 0.05 && mf <= 0.95) m->mfact = (float)mf; + m->nmaster = (int)snap_mon_vals[base + 5]; + if (m->nmaster < 0) m->nmaster = 1; + int want_bar = snap_mon_vals[base + 6] ? 1 : 0; + if (m->showbar != want_bar) { + m->showbar = want_bar; + updatebarpos(m); + resizebarwin(m); + } + } + selmon = mon_by_num(sel_idx); + if (showsystray && !systraypinning) { + for (m = mons; m; m = m->next) resizebarwin(m); + updatesystray(1); + } + } else if (snap_has_cur_desk && selmon) { + unsigned int ts = desktop_to_tags(snap_cur_desk); + if (ts) selmon->tagset[selmon->seltags] = ts; + } + updateworkarea(); updatestatus(); + publish_desktop_names(); + sync_root_desktop_props(); + drawbars(); { XSetWindowAttributes nwa; @@ -2479,6 +3140,7 @@ static Monitor *systraytomon(Monitor *m) { static void tag(const Arg *arg) { if (selmon->sel && (arg->ui & TAGMASK)) { selmon->sel->tags = arg->ui & TAGMASK; + sync_client_props(selmon->sel); focusarranged(selmon); } } @@ -2518,16 +3180,13 @@ static void togglebar(const Arg *arg) { selmon->showbar = !selmon->showbar; updatebarpos(selmon); resizebarwin(selmon); - if (showsystray && systray) { + if (showsystray && systray && selmon == systraytomon(selmon)) { XWindowChanges wc; - if (!selmon->showbar) wc.y = -bh; - else if (selmon->showbar) { - wc.y = 0; - if (!selmon->topbar) wc.y = selmon->mh - bh; - } + wc.y = selmon->showbar ? selmon->by : -bh; XConfigureWindow(dpy, systray->win, CWY, &wc); } arrange(selmon); + sync_root_desktop_props(); } static void togglefloating(const Arg *arg) { @@ -2536,6 +3195,7 @@ static void togglefloating(const Arg *arg) { selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed; if (selmon->sel->isfloating) resize(selmon->sel, selmon->sel->x, selmon->sel->y, selmon->sel->w, selmon->sel->h, 0); + sync_client_props(selmon->sel); arrange(selmon); } @@ -2545,6 +3205,7 @@ static void toggletag(const Arg *arg) { newtags = selmon->sel->tags ^ (arg->ui & TAGMASK); if (newtags) { selmon->sel->tags = newtags; + sync_client_props(selmon->sel); focusarranged(selmon); } } @@ -2553,6 +3214,7 @@ static void toggleview(const Arg *arg) { unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK); if (newtagset) { selmon->tagset[selmon->seltags] = newtagset; + sync_root_desktop_props(); focusarranged(selmon); } } @@ -2582,15 +3244,18 @@ static void unmanage(Client *c, int destroyed) { XSelectInput(dpy, c->win, NoEventMask); XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); XUngrabButton(dpy, AnyButton, AnyModifier, c->win); - setclientstate(c, WithdrawnState); + if (!handoff_exit) + setclientstate(c, WithdrawnState); XSync(dpy, False); XSetErrorHandler(xerror); XUngrabServer(dpy); } free(c); - focus(NULL); - updateclientlist(); - arrange(m); + if (!handoff_exit) { + focus(NULL); + updateclientlist(); + arrange(m); + } } static void unmapnotify(XEvent *e) { @@ -2726,27 +3391,61 @@ static int updategeom(void) { } XFree(info); nn = j; - if (n <= nn) { + + /* Put XRandR primary output at index 0, remaining screens sorted by (x_org, y_org) */ + int has_pri = 0, pri_x = 0, pri_y = 0, pri_w = 0, pri_h = 0; + if (rr_event_base >= 0) { + RROutput pri = XRRGetOutputPrimary(dpy, root); + if (pri != None) { + XRRScreenResources *sr = XRRGetScreenResourcesCurrent(dpy, root); + if (!sr) sr = XRRGetScreenResources(dpy, root); + if (sr) { + XRROutputInfo *oi = XRRGetOutputInfo(dpy, sr, pri); + if (oi && oi->connection == RR_Connected && oi->crtc != None) { + XRRCrtcInfo *ci = XRRGetCrtcInfo(dpy, sr, oi->crtc); + if (ci && ci->width > 0 && ci->height > 0) { + has_pri = 1; + pri_x = ci->x; pri_y = ci->y; + pri_w = (int)ci->width; pri_h = (int)ci->height; + } + if (ci) XRRFreeCrtcInfo(ci); + } + if (oi) XRRFreeOutputInfo(oi); + XRRFreeScreenResources(sr); + } + } + } + for (int a = 0; a < nn; a++) { + for (int b = a + 1; b < nn; b++) { + int a_pri = (has_pri && unique[a].x_org == pri_x && unique[a].y_org == pri_y && + unique[a].width == pri_w && unique[a].height == pri_h); + int b_pri = (has_pri && unique[b].x_org == pri_x && unique[b].y_org == pri_y && + unique[b].width == pri_w && unique[b].height == pri_h); + int do_swap = 0; + if (b_pri && !a_pri) do_swap = 1; + else if (a_pri == b_pri) { + if (unique[b].x_org < unique[a].x_org || + (unique[b].x_org == unique[a].x_org && unique[b].y_org < unique[a].y_org)) + do_swap = 1; + } + if (do_swap) { + XineramaScreenInfo tmp = unique[a]; + unique[a] = unique[b]; + unique[b] = tmp; + } + } + } + + if (n < nn) { for (i = 0; i < (nn - n); i++) { for (m = mons; m && m->next; m = m->next) ; if (m) m->next = createmon(); else mons = createmon(); } - for (i = 0, m = mons; i < nn && m; m = m->next, i++) { - if (i >= n || unique[i].x_org != m->mx || unique[i].y_org != m->my || - unique[i].width != m->mw || unique[i].height != m->mh) { - dirty = 1; - m->num = i; - m->mx = m->wx = unique[i].x_org; - m->my = m->wy = unique[i].y_org; - m->mw = m->ww = unique[i].width; - m->mh = m->wh = unique[i].height; - updatebarpos(m); - } - } - } else { + } else if (n > nn) { for (i = nn; i < n; i++) { for (m = mons; m && m->next; m = m->next) ; + if (!m || m == mons) break; while ((c = m->clients)) { dirty = 1; m->clients = c->next; @@ -2757,6 +3456,19 @@ static int updategeom(void) { } if (m == selmon) selmon = mons; cleanupmon(m); + dirty = 1; + } + } + for (i = 0, m = mons; i < nn && m; m = m->next, i++) { + if (i >= n || unique[i].x_org != m->mx || unique[i].y_org != m->my || + unique[i].width != m->mw || unique[i].height != m->mh) { + dirty = 1; + m->num = i; + m->mx = m->wx = unique[i].x_org; + m->my = m->wy = unique[i].y_org; + m->mw = m->ww = unique[i].width; + m->mh = m->wh = unique[i].height; + updatebarpos(m); } } free(unique); @@ -2774,6 +3486,7 @@ static int updategeom(void) { if (dirty) { selmon = mons; selmon = wintomon(root); + sync_root_desktop_props(); } return dirty; } @@ -3130,6 +3843,7 @@ static void view(const Arg *arg) { selmon->seltags ^= 1; if (arg->ui & TAGMASK) selmon->tagset[selmon->seltags] = arg->ui & TAGMASK; + sync_root_desktop_props(); focusarranged(selmon); } @@ -3215,6 +3929,7 @@ int main(int argc, char *argv[]) { fputs("warning: no locale support\n", stderr); if (!(dpy = XOpenDisplay(NULL))) die("dwm: cannot open display"); + snapshot_pre_replace_state(); acquirewm(); setup(); scan(); diff --git a/src/libgemui/gemui.c b/src/libgemui/gemui.c index c5bb06f..0949ecc 100644 --- a/src/libgemui/gemui.c +++ b/src/libgemui/gemui.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -52,11 +53,14 @@ struct gemui_app { int bh; int w; int h; + gemui_rect_t primary_mon; + int rr_event_base; Atom wm_delete; Atom net_wm_name; Atom utf8_string; Atom net_wm_state; Atom net_wm_state_fs; + Atom sel_prop; XIM xim; XIC xic; bool fullscreen_override; @@ -157,42 +161,42 @@ bool gemui_color_parse(const char *hex, gemui_color_t *out) { void gemui_theme_defaults(gemui_theme_t *t) { memset(t, 0, sizeof(*t)); - snprintf(t->name, sizeof(t->name), "AnodeDefault"); + snprintf(t->name, sizeof(t->name), "Anodized"); snprintf(t->font_face, sizeof(t->font_face), "Fira Code"); snprintf(t->icon_font_face, sizeof(t->icon_font_face), "DejaVuSansM Nerd Font"); t->base_font_size = 15; t->dpi = 96; t->scale = 1.0; t->touch_mode = false; - gemui_color_parse("#11141a", &t->bg_main); - gemui_color_parse("#161b23", &t->bg_bar); - gemui_color_parse("#1b212b", &t->bg_header); - gemui_color_parse("#141922", &t->bg_footer); - gemui_color_parse("#18202c", &t->bg_overlay); - gemui_color_parse("#1a202a", &t->bg_alt_even); - gemui_color_parse("#1e2531", &t->bg_alt_odd); - gemui_color_parse("#212936", &t->bg_input); - gemui_color_parse("#273244", &t->bg_input_focus); - gemui_color_parse("#232b38", &t->bg_button); - gemui_color_parse("#202835", &t->bg_search); - gemui_color_parse("#222b3a", &t->bg_bubble_in); - gemui_color_parse("#1f3a52", &t->bg_bubble_out); - gemui_color_parse("#233044", &t->bg_toast); - gemui_color_parse("#d8dee9", &t->fg_main); - gemui_color_parse("#eceff4", &t->fg_bright); - gemui_color_parse("#8a95a8", &t->fg_muted); - gemui_color_parse("#2f6feb", &t->sel_bg); - gemui_color_parse("#ffffff", &t->sel_fg); - gemui_color_parse("#58a6ff", &t->accent); - gemui_color_parse("#79c0ff", &t->accent_alt); - gemui_color_parse("#d2a8ff", &t->highlight); - gemui_color_parse("#30394a", &t->border); - gemui_color_parse("#262f3e", &t->divider); - gemui_color_parse("#3fb950", &t->success); - gemui_color_parse("#58a6ff", &t->info); - gemui_color_parse("#d29922", &t->warning); - gemui_color_parse("#f85149", &t->danger); - gemui_color_parse("#4d1c20", &t->danger_bg); + gemui_color_parse("#08090b", &t->bg_main); + gemui_color_parse("#0e1014", &t->bg_bar); + gemui_color_parse("#12151a", &t->bg_header); + gemui_color_parse("#0b0d11", &t->bg_footer); + gemui_color_parse("#171b22", &t->bg_overlay); + gemui_color_parse("#101318", &t->bg_alt_even); + gemui_color_parse("#14181f", &t->bg_alt_odd); + gemui_color_parse("#161a21", &t->bg_input); + gemui_color_parse("#1e232c", &t->bg_input_focus); + gemui_color_parse("#1c212a", &t->bg_button); + gemui_color_parse("#191e27", &t->bg_search); + gemui_color_parse("#181d25", &t->bg_bubble_in); + gemui_color_parse("#252c38", &t->bg_bubble_out); + gemui_color_parse("#1c222b", &t->bg_toast); + gemui_color_parse("#e4e8ee", &t->fg_main); + gemui_color_parse("#f5f7fa", &t->fg_bright); + gemui_color_parse("#89929f", &t->fg_muted); + gemui_color_parse("#38414f", &t->sel_bg); + gemui_color_parse("#f5f7fa", &t->sel_fg); + gemui_color_parse("#cfd6e0", &t->accent); + gemui_color_parse("#e5eaf0", &t->accent_alt); + gemui_color_parse("#e2bc72", &t->highlight); + gemui_color_parse("#2d3440", &t->border); + gemui_color_parse("#20252f", &t->divider); + gemui_color_parse("#79cf9c", &t->success); + gemui_color_parse("#9eb3c8", &t->info); + gemui_color_parse("#e2bc72", &t->warning); + gemui_color_parse("#e07a7a", &t->danger); + gemui_color_parse("#3f1d20", &t->danger_bg); } static void gemui_apply_xrm_db(XrmDatabase db, gemui_theme_t *t) { @@ -389,6 +393,40 @@ static void gemui_restore_prev_focus(gemui_app_t *app) { app->prev_focus_win = None; } +static gemui_rect_t gemui_compute_primary_mon(Display *dpy, int screen, Window root, + int fallback_x, int fallback_y, int fallback_w, int fallback_h) { + int sw = DisplayWidth(dpy, screen); + int sh = DisplayHeight(dpy, screen); + gemui_rect_t res_rect = {fallback_x, fallback_y, fallback_w > 0 ? fallback_w : sw, fallback_h > 0 ? fallback_h : sh}; + + int rr_ev = 0, rr_err = 0; + if (XRRQueryExtension(dpy, &rr_ev, &rr_err)) { + RROutput primary = XRRGetOutputPrimary(dpy, root); + if (primary != None) { + XRRScreenResources *sr = XRRGetScreenResourcesCurrent(dpy, root); + if (!sr) sr = XRRGetScreenResources(dpy, root); + if (sr) { + XRROutputInfo *oi = XRRGetOutputInfo(dpy, sr, primary); + if (oi && oi->connection == RR_Connected && oi->crtc != None) { + XRRCrtcInfo *ci = XRRGetCrtcInfo(dpy, sr, oi->crtc); + if (ci && ci->width > 0 && ci->height > 0) { + res_rect = (gemui_rect_t){ci->x, ci->y, (int)ci->width, (int)ci->height}; + } + if (ci) XRRFreeCrtcInfo(ci); + } + if (oi) XRRFreeOutputInfo(oi); + XRRFreeScreenResources(sr); + } + } + } + if (res_rect.x < 0) res_rect.x = 0; + if (res_rect.y < 0) res_rect.y = 0; + if (res_rect.x + res_rect.w > sw) res_rect.w = sw - res_rect.x; + if (res_rect.y + res_rect.h > sh) res_rect.h = sh - res_rect.y; + if (res_rect.w <= 0 || res_rect.h <= 0) res_rect = (gemui_rect_t){0, 0, sw, sh}; + return res_rect; +} + gemui_app_t *gemui_create(const char *res_name, const char *title, int w, int h, bool fullscreen_override) { setlocale(LC_CTYPE, ""); @@ -410,6 +448,7 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, app->screen = DefaultScreen(dpy); app->root = RootWindow(dpy, app->screen); app->fullscreen_override = fullscreen_override; + app->rr_event_base = -1; gemui_theme_reload(app); @@ -471,27 +510,35 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, } } - if (fullscreen_override || w <= 0) { - w = mw; + if (fullscreen_override) { + /* Cover full virtual desktop across all monitors so lockscreen never leaves any display exposed */ + w = sw; + h = sh; + app->primary_mon = gemui_compute_primary_mon(dpy, app->screen, app->root, mx, my, mw, mh); } else { - int scaled_w = gemui_scale_px(app, w); - int pad = gemui_scale_px(app, 24); - int max_w = (mw > pad * 2) ? (mw - pad) : mw; - int min_w = gemui_scale_px(app, 260); - if (scaled_w > max_w) scaled_w = max_w; - if (scaled_w < min_w && max_w >= min_w) scaled_w = min_w; - w = scaled_w; - } - if (fullscreen_override || h <= 0) { - h = mh; - } else { - int scaled_h = gemui_scale_px(app, h); - int pad = gemui_scale_px(app, 32); - int max_h = (mh > pad * 2) ? (mh - pad) : mh; - int min_h = gemui_scale_px(app, 180); - if (scaled_h > max_h) scaled_h = max_h; - if (scaled_h < min_h && max_h >= min_h) scaled_h = min_h; - h = scaled_h; + if (w <= 0) { + w = mw; + } else { + int scaled_w = gemui_scale_px(app, w); + int pad = gemui_scale_px(app, 24); + int max_w = (mw > pad * 2) ? (mw - pad) : mw; + int min_w = gemui_scale_px(app, 260); + if (scaled_w > max_w) scaled_w = max_w; + if (scaled_w < min_w && max_w >= min_w) scaled_w = min_w; + w = scaled_w; + } + if (h <= 0) { + h = mh; + } else { + int scaled_h = gemui_scale_px(app, h); + int pad = gemui_scale_px(app, 32); + int max_h = (mh > pad * 2) ? (mh - pad) : mh; + int min_h = gemui_scale_px(app, 180); + if (scaled_h > max_h) scaled_h = max_h; + if (scaled_h < min_h && max_h >= min_h) scaled_h = min_h; + h = scaled_h; + } + app->primary_mon = (gemui_rect_t){0, 0, w, h}; } app->w = w; app->h = h; @@ -545,14 +592,21 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, } XSelectInput(dpy, app->root, - fullscreen_override ? (PropertyChangeMask | SubstructureNotifyMask) + fullscreen_override ? (PropertyChangeMask | SubstructureNotifyMask | StructureNotifyMask) : PropertyChangeMask); + if (fullscreen_override) { + int rr_err = 0; + if (XRRQueryExtension(dpy, &app->rr_event_base, &rr_err)) { + XRRSelectInput(dpy, app->root, RRScreenChangeNotifyMask); + } + } app->wm_delete = XInternAtom(dpy, "WM_DELETE_WINDOW", False); app->net_wm_name = XInternAtom(dpy, "_NET_WM_NAME", False); app->utf8_string = XInternAtom(dpy, "UTF8_STRING", False); app->net_wm_state = XInternAtom(dpy, "_NET_WM_STATE", False); app->net_wm_state_fs = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); + app->sel_prop = XInternAtom(dpy, "GEMUI_CLIP_DATA", False); XSetWMProtocols(dpy, app->win, &app->wm_delete, 1); if (fullscreen_override) { @@ -571,7 +625,7 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, if (fullscreen_override) { XMapRaised(dpy, app->win); app->mapped = true; - XMoveResizeWindow(dpy, app->win, mx, my, (unsigned int)mw, (unsigned int)mh); + XMoveResizeWindow(dpy, app->win, 0, 0, (unsigned int)w, (unsigned int)h); gemui_save_prev_focus(app); XSetInputFocus(dpy, app->win, RevertToPointerRoot, CurrentTime); } @@ -615,6 +669,61 @@ const gemui_theme_t *gemui_theme(const gemui_app_t *app) { return app ? &app->th int gemui_width(const gemui_app_t *app) { return app ? app->w : 0; } int gemui_height(const gemui_app_t *app) { return app ? app->h : 0; } +gemui_rect_t gemui_primary_monitor_rect(const gemui_app_t *app) { + if (!app) return (gemui_rect_t){0, 0, 0, 0}; + if (app->primary_mon.w > 0 && app->primary_mon.h > 0) return app->primary_mon; + return (gemui_rect_t){0, 0, app->w, app->h}; +} + +static bool gemui_read_selection(gemui_app_t *app, Atom sel, Atom target, char *out, size_t out_sz) { + XDeleteProperty(app->dpy, app->win, app->sel_prop); + XConvertSelection(app->dpy, sel, target, app->sel_prop, app->win, CurrentTime); + XFlush(app->dpy); + + uint64_t deadline = gemui_now_ms() + 150ULL; + int xfd = ConnectionNumber(app->dpy); + XEvent nev; + bool got = false; + while (gemui_now_ms() < deadline) { + XEventsQueued(app->dpy, QueuedAfterReading); + if (XCheckTypedWindowEvent(app->dpy, app->win, SelectionNotify, &nev)) { + got = true; + break; + } + struct pollfd pfd = { .fd = xfd, .events = POLLIN }; + poll(&pfd, 1, 20); + } + if (!got || nev.xselection.property == None) return false; + + Atom da = None; + int di = 0; + unsigned long n = 0, after = 0; + unsigned char *prop = NULL; + bool ok = false; + if (XGetWindowProperty(app->dpy, app->win, app->sel_prop, 0L, (long)(out_sz / 4 + 16), + True, AnyPropertyType, &da, &di, &n, &after, &prop) == Success && prop) { + if (di == 8 && n > 0) { + size_t copy = n < out_sz - 1 ? n : out_sz - 1; + memcpy(out, prop, copy); + out[copy] = '\0'; + ok = true; + } + XFree(prop); + } + return ok; +} + +bool gemui_clipboard_get(gemui_app_t *app, char *out, size_t out_sz) { + if (!app || !out || out_sz == 0) return false; + out[0] = '\0'; + Atom clip = XInternAtom(app->dpy, "CLIPBOARD", False); + if (gemui_read_selection(app, clip, app->utf8_string, out, out_sz)) return true; + if (gemui_read_selection(app, clip, XA_STRING, out, out_sz)) return true; + if (gemui_read_selection(app, XA_PRIMARY, app->utf8_string, out, out_sz)) return true; + if (gemui_read_selection(app, XA_PRIMARY, XA_STRING, out, out_sz)) return true; + return false; +} + double gemui_scale(const gemui_app_t *app) { return app ? app->theme.scale : 1.0; } @@ -836,12 +945,34 @@ static void gemui_keep_fullscreen_on_top(gemui_app_t *app) { XSetErrorHandler(old_handler); } +static void gemui_sync_fullscreen_size(gemui_app_t *app) { + if (!app || !app->fullscreen_override) return; + int nsw = DisplayWidth(app->dpy, app->screen); + int nsh = DisplayHeight(app->dpy, app->screen); + app->primary_mon = gemui_compute_primary_mon(app->dpy, app->screen, app->root, 0, 0, nsw, nsh); + if (nsw != app->w || nsh != app->h) { + app->w = nsw; + app->h = nsh; + XMoveResizeWindow(app->dpy, app->win, 0, 0, (unsigned int)nsw, (unsigned int)nsh); + if (app->handlers.on_resize) { + app->handlers.on_resize(app, app->w, app->h, app->userdata); + } + } + app->need_redraw = true; +} + static void gemui_handle_x_events(gemui_app_t *app) { while (XPending(app->dpy) > 0 && app->running) { XEvent ev; XNextEvent(app->dpy, &ev); if (XFilterEvent(&ev, None)) continue; + if (app->rr_event_base >= 0 && ev.type == app->rr_event_base + RRScreenChangeNotify) { + XRRUpdateConfiguration(&ev); + gemui_sync_fullscreen_size(app); + continue; + } + switch (ev.type) { case Expose: if (ev.xexpose.count == 0) app->need_redraw = true; @@ -851,11 +982,16 @@ static void gemui_handle_x_events(gemui_app_t *app) { if (ev.xconfigure.width != app->w || ev.xconfigure.height != app->h) { app->w = ev.xconfigure.width; app->h = ev.xconfigure.height; + if (!app->fullscreen_override) { + app->primary_mon = (gemui_rect_t){0, 0, app->w, app->h}; + } if (app->handlers.on_resize) { app->handlers.on_resize(app, app->w, app->h, app->userdata); } app->need_redraw = true; } + } else if (ev.xconfigure.window == app->root && app->fullscreen_override) { + gemui_sync_fullscreen_size(app); } else if (app->fullscreen_override && !gemui_is_vkbd_win(app->dpy, ev.xconfigure.window)) { gemui_keep_fullscreen_on_top(app); } @@ -1095,6 +1231,7 @@ static int gemui_draw_pango(cairo_t *cr, const char *face, int px_size, pango_layout_set_font_description(layout, desc); pango_layout_set_width(layout, r.w * PANGO_SCALE); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END); + pango_layout_set_height(layout, 0); pango_layout_set_single_paragraph_mode(layout, True); if (align == GEMUI_ALIGN_CENTER) { pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER); @@ -1108,9 +1245,13 @@ static int gemui_draw_pango(cairo_t *cr, const char *face, int px_size, int tw = 0, th = 0; pango_layout_get_pixel_size(layout, &tw, &th); int dy = r.y + (r.h - th) / 2; + cairo_save(cr); + cairo_rectangle(cr, r.x, r.y - 4, r.w, r.h + 8); + cairo_clip(cr); gemui_set_source(cr, c); cairo_move_to(cr, r.x, dy); pango_cairo_show_layout(cr, layout); + cairo_restore(cr); pango_font_description_free(desc); if (!g_active_layout) g_object_unref(layout); @@ -1190,7 +1331,13 @@ void gemui_draw_button(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, if (!app) return; const gemui_theme_t *t = &app->theme; gemui_color_t bg = active ? t->sel_bg : (primary ? t->accent : t->bg_button); - gemui_color_t fg = (active || primary) ? t->sel_fg : t->fg_bright; + double bg_lum = 0.299 * bg.r + 0.587 * bg.g + 0.114 * bg.b; + double bgm_lum = 0.299 * t->bg_main.r + 0.587 * t->bg_main.g + 0.114 * t->bg_main.b; + double fgm_lum = 0.299 * t->fg_main.r + 0.587 * t->fg_main.g + 0.114 * t->fg_main.b; + gemui_color_t dark_ink = (bgm_lum < 0.35) ? t->bg_main + : (fgm_lum < 0.35) ? t->fg_main + : (gemui_color_t){0.031, 0.035, 0.043, 1.0, 0xff08090bU}; + gemui_color_t fg = (bg_lum > 0.58) ? dark_ink : ((active || primary) ? t->sel_fg : t->fg_bright); gemui_color_t bd = focused ? t->highlight : (active ? t->sel_bg : t->border); double rad = (double)gemui_scale_px(app, 6); double lw = focused ? (t->scale >= 1.5 ? 2.5 : 2.0) : (t->scale >= 1.5 ? 1.5 : 1.0); diff --git a/src/libgemui/gemui.h b/src/libgemui/gemui.h index c254ae8..09736f1 100644 --- a/src/libgemui/gemui.h +++ b/src/libgemui/gemui.h @@ -26,7 +26,7 @@ extern "C" { #define GEMUI_PTR_SCROLL_UP 3 #define GEMUI_PTR_SCROLL_DOWN 4 -#define GEMUI_MAX_HITS 192 +#define GEMUI_MAX_HITS 256 #define GEMUI_MAX_FDS 16 typedef struct { @@ -117,6 +117,8 @@ Window gemui_window(const gemui_app_t *app); const gemui_theme_t *gemui_theme(const gemui_app_t *app); int gemui_width(const gemui_app_t *app); int gemui_height(const gemui_app_t *app); +gemui_rect_t gemui_primary_monitor_rect(const gemui_app_t *app); +bool gemui_clipboard_get(gemui_app_t *app, char *out, size_t out_sz); double gemui_scale(const gemui_app_t *app); bool gemui_touch_mode(const gemui_app_t *app); int gemui_scale_px(const gemui_app_t *app, int logical_px); diff --git a/src/st/config.def.h b/src/st/config.def.h index d446665..e73e40b 100644 --- a/src/st/config.def.h +++ b/src/st/config.def.h @@ -118,10 +118,10 @@ static const char *colorname[] = { [255] = 0, /* more colors can be added after 255 to use with DefaultXX */ - "#161616", - "#dddddd", - "#f4d03f", - "#555555", + "#08090b", + "#e4e8ee", + "#cfd6e0", + "#08090b", }; diff --git a/src/st/config.h b/src/st/config.h index d446665..e73e40b 100644 --- a/src/st/config.h +++ b/src/st/config.h @@ -118,10 +118,10 @@ static const char *colorname[] = { [255] = 0, /* more colors can be added after 255 to use with DefaultXX */ - "#161616", - "#dddddd", - "#f4d03f", - "#555555", + "#08090b", + "#e4e8ee", + "#cfd6e0", + "#08090b", }; diff --git a/tests/test_posix_make.py b/tests/test_posix_make.py index 41596d4..f3569f8 100755 --- a/tests/test_posix_make.py +++ b/tests/test_posix_make.py @@ -51,6 +51,7 @@ def check_scripts() -> None: script_files = [ "scripts/detect-env.sh", "scripts/anode-apply-scale", + "scripts/anode-apply-display", "scripts/anode-apply-theme", "scripts/anode-sync-gtk-theme", "scripts/anode-sync-dunst-theme", @@ -91,7 +92,56 @@ def check_scripts() -> None: assert not re.search(pat, code), f"{rel}:{lineno}: {desc}: {line}" +def test_optional_touchd_staged_install() -> None: + import tempfile + with tempfile.TemporaryDirectory() as tmp: + dest0 = os.path.join(tmp, "d0") + res0 = subprocess.run( + ["make", "install", f"DESTDIR={dest0}", "PREFIX=/usr/local", "XSESSIONSDIR=/usr/share/xsessions"], + cwd=ROOT, capture_output=True, text=True, + ) + assert res0.returncode == 0, f"default install failed: {res0.stderr}" + assert not os.path.exists(os.path.join(dest0, "usr", "local", "bin", "anode-touchd")) + assert os.path.isfile(os.path.join(dest0, "usr", "local", "bin", "anode-vkbd")) + assert os.path.isfile(os.path.join(dest0, "usr", "local", "bin", "anode-apply-display")) + assert os.path.isfile(os.path.join(dest0, "usr", "local", "share", "anode", "themes", "Anodized.xth")) + assert not os.path.exists(os.path.join(dest0, "usr", "local", "share", "anode", "themes", "AnodeDefault.xth")) + + dest1 = os.path.join(tmp, "d1") + res1 = subprocess.run( + ["make", "WITH_TOUCHD=1", "install", f"DESTDIR={dest1}", "PREFIX=/usr/local", "XSESSIONSDIR=/usr/share/xsessions"], + cwd=ROOT, capture_output=True, text=True, + ) + assert res1.returncode == 0, f"WITH_TOUCHD=1 install failed: {res1.stderr}" + assert os.path.isfile(os.path.join(dest1, "usr", "local", "bin", "anode-touchd")) + assert os.path.isfile(os.path.join(dest1, "usr", "local", "bin", "anode-vkbd")) + + hres = subprocess.run(["make", "help"], cwd=ROOT, capture_output=True, text=True) + assert hres.returncode == 0, f"make help failed: {hres.stderr}" + for kw in ("rebuild", "install-touch", "install-system", "WITH_TOUCHD"): + assert kw in hres.stdout, f"make help missing {kw!r}: {hres.stdout}" + + dest2 = os.path.join(tmp, "d2") + res2 = subprocess.run( + ["make", "install-touch", f"DESTDIR={dest2}", "PREFIX=/usr/local"], + cwd=ROOT, capture_output=True, text=True, + ) + assert res2.returncode == 0, f"install-touch failed: {res2.stderr}" + assert os.path.isfile(os.path.join(dest2, "usr", "local", "bin", "anode-touchd")) + assert os.path.isfile(os.path.join(dest2, "usr", "local", "bin", "anode-vkbd")) + + dest3 = os.path.join(tmp, "d3") + res3 = subprocess.run( + ["make", "install-system", f"DESTDIR={dest3}", "PREFIX=/usr/local"], + cwd=ROOT, capture_output=True, text=True, + ) + assert res3.returncode == 0, f"install-system failed: {res3.stderr}" + assert os.path.isfile(os.path.join(dest3, "usr", "share", "xsessions", "anode.desktop")) + assert not os.path.exists(os.path.join(dest3, "usr", "local", "bin", "anode-touchd")) + + if __name__ == "__main__": check_makefile() check_scripts() + test_optional_touchd_staged_install() print("test_posix_make: OK") diff --git a/tests/test_replace.py b/tests/test_replace.py index 829eb52..5d50526 100755 --- a/tests/test_replace.py +++ b/tests/test_replace.py @@ -69,12 +69,61 @@ X11.XCreateSimpleWindow.argtypes = [ ] X11.XCreateSimpleWindow.restype = Window X11.XMapWindow.argtypes = [Display_p, Window] +X11.XUnmapWindow.argtypes = [Display_p, Window] +X11.XMoveResizeWindow.argtypes = [Display_p, Window, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint] +X11.XChangeProperty.argtypes = [ + Display_p, Window, Atom, Atom, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, +] +X11.XSendEvent.argtypes = [Display_p, Window, ctypes.c_int, ctypes.c_long, ctypes.c_void_p] X11.XDestroyWindow.argtypes = [Display_p, Window] X11.XGetWindowAttributes.argtypes = [Display_p, Window, ctypes.POINTER(XWindowAttributes)] X11.XGetWindowAttributes.restype = ctypes.c_int X11.XSync.argtypes = [Display_p, ctypes.c_int] +def get_win_prop_ulong_list(dpy, win, atom_name, max_items=64): + atom = X11.XInternAtom(dpy, atom_name.encode(), 0) + da = Atom() + di = ctypes.c_int() + n = ctypes.c_ulong() + dl = ctypes.c_ulong() + prop = ctypes.POINTER(ctypes.c_ubyte)() + rc = X11.XGetWindowProperty( + dpy, win, atom, 0, max_items, 0, 0, + ctypes.byref(da), ctypes.byref(di), ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop), + ) + vals = [] + if rc == 0 and prop and di.value == 32 and n.value >= 1: + arr = ctypes.cast(prop, ctypes.POINTER(ctypes.c_ulong)) + vals = [int(arr[i]) for i in range(n.value)] + if prop: + X11.XFree(prop) + return vals + + +def send_ewmh_msg(dpy, root, win, atom_name, data_l): + class CMData(ctypes.Union): + _fields_ = [("b", ctypes.c_char * 20), ("s", ctypes.c_short * 10), ("l", ctypes.c_long * 5)] + + class CMEvent(ctypes.Structure): + _fields_ = [ + ("type", ctypes.c_int), ("serial", ctypes.c_ulong), ("send_event", ctypes.c_int), + ("display", Display_p), ("window", Window), ("message_type", Atom), + ("format", ctypes.c_int), ("data", CMData), + ] + + ev = CMEvent() + ev.type = 33 # ClientMessage + ev.display = dpy + ev.window = win + ev.message_type = X11.XInternAtom(dpy, atom_name.encode(), 0) + ev.format = 32 + for i, val in enumerate(data_l[:5]): + ev.data.l[i] = val + X11.XSendEvent(dpy, root, 0, (1 << 19) | (1 << 20), ctypes.byref(ev)) + X11.XSync(dpy, 0) + + 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}"): @@ -898,6 +947,256 @@ def test_replace_display_scoped_daemon_cleanup(): terminate(xvfb) +def test_replace_preserves_workspaces_and_states(): + # Subtest A: ANODE -> ANODE replace preserves desktops, focus, floating geometry, and fullscreen + disp = pick_display() + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp) + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", "1280x720x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dwm1 = None + dpy = None + new_pid = None + wins = [] + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode()), timeout=5.0) + assert dpy + root = X11.XDefaultRootWindow(dpy) + + dwm1 = subprocess.Popen([DWM_BIN], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + wm1 = wait_until(lambda: get_win_prop_ulong(dpy, root, "_NET_SUPPORTING_WM_CHECK"), timeout=5.0) + assert wm1 + + a_type = X11.XInternAtom(dpy, b"_NET_WM_WINDOW_TYPE", 0) + a_dlg = X11.XInternAtom(dpy, b"_NET_WM_WINDOW_TYPE_DIALOG", 0) + a_atom = X11.XInternAtom(dpy, b"ATOM", 0) + a_fs = X11.XInternAtom(dpy, b"_NET_WM_STATE_FULLSCREEN", 0) + + w1 = X11.XCreateSimpleWindow(dpy, root, 10, 40, 300, 200, 0, 0, 0xffffff) + w2 = X11.XCreateSimpleWindow(dpy, root, 120, 140, 420, 300, 0, 0, 0xffffff) + dlg_val = ctypes.c_ulong(a_dlg) + X11.XChangeProperty(dpy, w2, a_type, a_atom, 32, 0, ctypes.byref(dlg_val), 1) + w3 = X11.XCreateSimpleWindow(dpy, root, 20, 50, 300, 200, 0, 0, 0xffffff) + w4 = X11.XCreateSimpleWindow(dpy, root, 30, 60, 300, 200, 0, 0, 0xffffff) + wins = [w1, w2, w3, w4] + for w in wins: + X11.XMapWindow(dpy, w) + X11.XSync(dpy, 0) + + assert wait_until(lambda: all(w in get_win_prop_ulong_list(dpy, root, "_NET_CLIENT_LIST") for w in wins), timeout=5.0) + + send_ewmh_msg(dpy, root, w2, "_NET_WM_DESKTOP", [1, 2, 0, 0, 0]) + send_ewmh_msg(dpy, root, w3, "_NET_WM_DESKTOP", [2, 2, 0, 0, 0]) + send_ewmh_msg(dpy, root, w4, "_NET_WM_DESKTOP", [1, 2, 0, 0, 0]) + send_ewmh_msg(dpy, root, w3, "_NET_WM_STATE", [1, a_fs, 0, 2, 0]) + send_ewmh_msg(dpy, root, root, "_NET_CURRENT_DESKTOP", [1, 0, 0, 0, 0]) + send_ewmh_msg(dpy, root, w4, "_NET_ACTIVE_WINDOW", [2, 0, 0, 0, 0]) + + def pre_state_ready(): + return ( + get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") == 1 + and get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") == w4 + and get_win_prop_ulong(dpy, w1, "_NET_WM_DESKTOP") == 0 + and get_win_prop_ulong(dpy, w2, "_NET_WM_DESKTOP") == 1 + and get_win_prop_ulong(dpy, w3, "_NET_WM_DESKTOP") == 2 + and get_win_prop_ulong(dpy, w4, "_NET_WM_DESKTOP") == 1 + and a_fs in get_win_prop_ulong_list(dpy, w3, "_NET_WM_STATE") + ) + + assert wait_until(pre_state_ready, timeout=5.0), "Pre-replace EWMH states did not settle" + X11.XMoveResizeWindow(dpy, w2, 120, 140, 420, 300) + X11.XSync(dpy, 0) + time.sleep(0.15) + + rep = subprocess.run( + [REPLACE_BIN, "--no-autostart", "--keep-panels"], + env=env, capture_output=True, text=True, + ) + assert rep.returncode == 0, f"anode-replace failed: stdout={rep.stdout} stderr={rep.stderr}" + assert wait_until(lambda: dwm1.poll() is not None, timeout=5.0) + assert dwm1.returncode == 75 + 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 post_state_ready(): + if get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") != 1: + return False + if get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") != w4: + return False + if get_win_prop_ulong(dpy, w1, "_NET_WM_DESKTOP") != 0: + return False + if get_win_prop_ulong(dpy, w2, "_NET_WM_DESKTOP") != 1: + return False + if get_win_prop_ulong(dpy, w3, "_NET_WM_DESKTOP") != 2: + return False + if get_win_prop_ulong(dpy, w4, "_NET_WM_DESKTOP") != 1: + return False + return a_fs in get_win_prop_ulong_list(dpy, w3, "_NET_WM_STATE") + + assert wait_until(post_state_ready, timeout=5.0), ( + f"Post-replace EWMH mismatch: cur={get_win_prop_ulong(dpy, root, '_NET_CURRENT_DESKTOP')} " + f"act={get_win_prop_ulong(dpy, root, '_NET_ACTIVE_WINDOW')} " + f"desks={[get_win_prop_ulong(dpy, w, '_NET_WM_DESKTOP') for w in wins]}" + ) + + attrs = {} + for w in wins: + a = XWindowAttributes() + assert X11.XGetWindowAttributes(dpy, w, ctypes.byref(a)) != 0 + attrs[w] = (a.x, a.y, a.width, a.height) + assert attrs[w1][0] < 0 and attrs[w3][0] < 0, f"Hidden desktop windows not offscreen: {attrs}" + assert attrs[w2][0] >= 0 and attrs[w4][0] >= 0, f"Active desktop windows offscreen: {attrs}" + assert attrs[w2] == (120, 140, 420, 300), f"Floating geometry lost across replace: {attrs[w2]}" + finally: + if dpy: + for w in wins: + X11.XDestroyWindow(dpy, w) + terminate(dwm1) + kill_pid_and_wait(new_pid) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + # Subtest B: Third-party EWMH WM -> ANODE replace preserves desktops even when old WM unmaps & strips props + disp2 = pick_display() + cc = os.environ.get("CC", "cc") + with tempfile.TemporaryDirectory() as tmp: + env = make_env(tmp, disp2) + ewmh_c = os.path.join(tmp, "mock_ewmh.c") + ewmh_bin = os.path.join(tmp, "bin", "mock_ewmh") + with open(ewmh_c, "w", encoding="utf-8") as f: + f.write( + "#define _POSIX_C_SOURCE 200809L\n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" + "static volatile sig_atomic_t alive = 1;\n" + "static void on_sig(int s) { (void)s; alive = 0; }\n" + "int main(void) {\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 acl = XInternAtom(d, \"_NET_CLIENT_LIST\", False);\n" + " Atom acd = XInternAtom(d, \"_NET_CURRENT_DESKTOP\", False);\n" + " Atom aact = XInternAtom(d, \"_NET_ACTIVE_WINDOW\", False);\n" + " unsigned long pid = (unsigned long)getpid();\n" + " XChangeProperty(d, wmc, ac, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmc, 1);\n" + " XChangeProperty(d, wmc, an, au, 8, PropModeReplace, (unsigned char *)\"MockEWMH\", 8);\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" + " XSync(d, False);\n" + " while (alive) { struct timespec ts = {0, 50000000L}; nanosleep(&ts, NULL); }\n" + " XDeleteProperty(d, root, acd);\n" + " XDeleteProperty(d, root, acl);\n" + " XDeleteProperty(d, root, aact);\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_atom = X11.XInternAtom(dpy, b"ATOM", 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) + a_wms = X11.XInternAtom(dpy, b"_NET_WM_STATE", 0) + a_fs = X11.XInternAtom(dpy, b"_NET_WM_STATE_FULLSCREEN", 0) + + wa = X11.XCreateSimpleWindow(dpy, root, 10, 40, 280, 180, 0, 0, 0xffffff) + wb = X11.XCreateSimpleWindow(dpy, root, 0, 0, 1280, 720, 0, 0, 0xffffff) + wc = X11.XCreateSimpleWindow(dpy, root, 50, 60, 320, 220, 0, 0, 0xffffff) + app_wins = [wa, wb, wc] + X11.XMapWindow(dpy, wc) + 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) + fs_v = ctypes.c_ulong(a_fs) + X11.XChangeProperty(dpy, wb, a_wms, a_atom, 32, 0, ctypes.byref(fs_v), 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(2) + X11.XChangeProperty(dpy, root, a_cd, a_card, 32, 0, ctypes.byref(cd_v), 1) + act_v = ctypes.c_ulong(wc) + X11.XChangeProperty(dpy, root, a_act, a_win, 32, 0, ctypes.byref(act_v), 1) + X11.XSync(dpy, 0) + + mwm = subprocess.Popen([ewmh_bin], 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"3rd-party 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 third_party_ok(): + clist = get_win_prop_ulong_list(dpy, root, "_NET_CLIENT_LIST") + return ( + get_win_prop_ulong(dpy, root, "_NET_CURRENT_DESKTOP") == 2 + and all(w in clist for w in (wa, wb, wc)) + and get_win_prop_ulong(dpy, root, "_NET_ACTIVE_WINDOW") == wc + and get_win_prop_ulong(dpy, wa, "_NET_WM_DESKTOP") == 0 + and get_win_prop_ulong(dpy, wb, "_NET_WM_DESKTOP") == 1 + and get_win_prop_ulong(dpy, wc, "_NET_WM_DESKTOP") == 2 + and a_fs in get_win_prop_ulong_list(dpy, wb, "_NET_WM_STATE") + ) + + assert wait_until(third_party_ok, timeout=5.0), ( + f"3rd-party preserve mismatch: cur={get_win_prop_ulong(dpy, root, '_NET_CURRENT_DESKTOP')} " + f"clist={get_win_prop_ulong_list(dpy, root, '_NET_CLIENT_LIST')} " + f"act={get_win_prop_ulong(dpy, root, '_NET_ACTIVE_WINDOW')}" + ) + for w, expect_vis in ((wa, False), (wb, False), (wc, True)): + a = XWindowAttributes() + assert X11.XGetWindowAttributes(dpy, w, ctypes.byref(a)) != 0 + if expect_vis: + assert a.x >= 0, f"Active desktop window {w} offscreen: {a.x}" + else: + assert a.x < 0, f"Hidden desktop window {w} not offscreen: {a.x}" + 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(): if not shutil.which("Xvfb"): print("test_replace: Xvfb not installed (skipping)") @@ -911,6 +1210,7 @@ def main(): test_switch_session_xprofile_handoff() test_switch_session_stale_i3sock_fallback() test_replace_display_scoped_daemon_cleanup() + test_replace_preserves_workspaces_and_states() print("test_replace: OK") return 0 diff --git a/tests/test_theme_scale.py b/tests/test_theme_scale.py index fb81c12..9f29f91 100755 --- a/tests/test_theme_scale.py +++ b/tests/test_theme_scale.py @@ -121,9 +121,9 @@ def test_fractional_scales(): assert f'gtk-font-name="{exp_ui} 10"' in gtk2, gtk2 assert f"gtk-cursor-theme-size={exp_cur}" in gtk2, gtk2 - assert os.path.isfile(os.path.join(tmp, ".themes", "ANODE-AnodeDefault", "index.theme")) - assert os.path.islink(os.path.join(tmp, ".local", "share", "themes", "ANODE-AnodeDefault")) - with open(os.path.join(tmp, ".themes", "ANODE-AnodeDefault", "gtk-2.0", "gtkrc"), "r", encoding="utf-8") as f: + assert os.path.isfile(os.path.join(tmp, ".themes", "ANODE-Anodized", "index.theme")) + assert os.path.islink(os.path.join(tmp, ".local", "share", "themes", "ANODE-Anodized")) + with open(os.path.join(tmp, ".themes", "ANODE-Anodized", "gtk-2.0", "gtkrc"), "r", encoding="utf-8") as f: gtk2rc = f.read() assert "GtkButton::inner-border" in gtk2rc, gtk2rc assert "GtkEntry::inner-border" in gtk2rc, gtk2rc @@ -140,7 +140,7 @@ def test_fractional_scales(): for bad in ("min-height:", "min-width:", "padding:", "margin:", "font-family:"): assert bad not in gcss, f"Unexpected {bad} in .config/{gver}/gtk.css" - tcss_p = os.path.join(tmp, ".themes", "ANODE-AnodeDefault", gver, "gtk.css") + tcss_p = os.path.join(tmp, ".themes", "ANODE-Anodized", gver, "gtk.css") with open(tcss_p, "r", encoding="utf-8") as f: tcss = f.read() exp_imp = ( @@ -253,8 +253,8 @@ def test_st_overrides_and_xresources_local(): f.write("St.alpha: 0.95\n") # Repeated theme applications must preserve St.* cleanly without duplication - run_env(env, [APPLY_THEME, "AnodeDefault"]) - run_env(env, [APPLY_THEME, "AnodeDefault"]) + run_env(env, [APPLY_THEME, "Anodized"]) + run_env(env, [APPLY_THEME, "Anodized"]) with open(xres_p, "r", encoding="utf-8") as f: content = f.read() assert content.count("St.font:") == 1, content @@ -267,8 +267,8 @@ def test_st_overrides_and_xresources_local(): f.write("St.font: Fira Code:size=16:antialias=true\n") f.write("*.cursorBlink: true\n") - run_env(env, [APPLY_THEME, "AnodeDefault"]) - run_env(env, [APPLY_THEME, "AnodeDefault"]) + run_env(env, [APPLY_THEME, "Anodized"]) + run_env(env, [APPLY_THEME, "Anodized"]) with open(xres_p, "r", encoding="utf-8") as f: content2 = f.read() assert content2.count("St.font:") == 1, content2 @@ -343,7 +343,7 @@ def test_stale_env_does_not_override_scale_conf(): assert "gtk-cursor-theme-size=24" in f.read() # Re-applying theme with stale ANODE_SCALE/ANODE_TOUCH still honors scale.conf - run_env(stale_env, [APPLY_THEME, "AnodeDefault"]) + run_env(stale_env, [APPLY_THEME, "Anodized"]) xres2 = parse_xres(os.path.join(tmp, ".Xresources")) assert xres2["theme.scale"] == "1.25" and xres2["Xft.dpi"] == "120" and xres2["theme.touchMode"] == "0" @@ -372,8 +372,8 @@ def test_gtk_theme_light_dark_detection_and_css_parse(): assert txt3.splitlines()[0] == '@import url("resource:///org/gtk/libgtk/theme/Adwaita/gtk-contained.css");' assert txt4.splitlines()[0] == '@import url("resource:///org/gtk/libgtk/theme/Default/Default-light.css");' - run_env(env, [APPLY_THEME, "AnodeDefault"]) - t3_dark = os.path.join(tmp, ".themes", "ANODE-AnodeDefault", "gtk-3.0", "gtk.css") + run_env(env, [APPLY_THEME, "Anodized"]) + t3_dark = os.path.join(tmp, ".themes", "ANODE-Anodized", "gtk-3.0", "gtk.css") with open(t3_dark, "r", encoding="utf-8") as f: t3_txt = f.read() assert "menu separator" in t3_txt, t3_txt @@ -412,8 +412,8 @@ def test_gtk_theme_light_dark_detection_and_css_parse(): sys.executable, "-c", gtk4_check, - os.path.join(tmp, ".themes", "ANODE-AnodeDefault", "gtk-4.0", "gtk.css"), - os.path.join(tmp, ".themes", "ANODE-AnodeDefault", "gtk-4.0", "gtk-dark.css"), + os.path.join(tmp, ".themes", "ANODE-Anodized", "gtk-4.0", "gtk.css"), + os.path.join(tmp, ".themes", "ANODE-Anodized", "gtk-4.0", "gtk-dark.css"), os.path.join(tmp, ".config", "gtk-4.0", "gtk.css"), ], env=env, @@ -472,6 +472,93 @@ def test_ui_font_fallback_roboto_to_noto_sans(): assert aliases.get("monospace") == ["Fira Code"], aliases +def test_deprecated_anodedefault_fallback_and_install(): + assert not os.path.exists(os.path.join(THEMES_DIR, "AnodeDefault.xth")) + assert os.path.isfile(os.path.join(THEMES_DIR, "Anodized.xth")) + + with tempfile.TemporaryDirectory() as tmp: + env = dict(os.environ) + env.pop("DISPLAY", None) + env["HOME"] = tmp + env["XDG_CONFIG_HOME"] = os.path.join(tmp, ".config") + env["XDG_DATA_HOME"] = os.path.join(tmp, ".local", "share") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["ANODE_NO_DBUS"] = "1" + + res = run_env(env, [APPLY_THEME, "AnodeDefault"]) + assert "deprecated" in res.stderr.lower(), res.stderr + with open(os.path.join(tmp, ".config", "anode", "theme.conf"), "r", encoding="utf-8") as f: + assert "THEME=Anodized" in f.read() + + dl_dir = os.path.join(tmp, "custom_downloads") + os.makedirs(dl_dir) + custom_src = os.path.join(dl_dir, "SteelMint.xth") + with open(custom_src, "w", encoding="utf-8") as f: + f.write("theme.name: SteelMint\ntheme.bgMain: #0c1012\ntheme.fgMain: #dce4e8\ntheme.accent: #90c8b8\n") + run_env(env, [APPLY_THEME, "--install", custom_src, "InstalledMint"]) + dest_p = os.path.join(tmp, ".config", "anode", "themes", "InstalledMint.xth") + assert os.path.isfile(dest_p) + xres = parse_xres(os.path.join(tmp, ".Xresources")) + assert xres["theme.name"] == "InstalledMint" + + +def test_primary_edid_and_apply_display(): + APPLY_DISP = os.path.join(ROOT, "scripts", "anode-apply-display") + with tempfile.TemporaryDirectory() as tmp: + fbin = os.path.join(tmp, "bin") + os.makedirs(fbin) + calls_log = os.path.join(tmp, "xrandr.calls") + xr_p = os.path.join(fbin, "xrandr") + with open(xr_p, "w", encoding="utf-8") as f: + f.write( + "#!/bin/sh\n" + "if [ \"$1\" = \"--query\" ]; then\n" + " cat <<'EOF'\n" + "Screen 0: minimum 320 x 200, current 4480 x 1440, maximum 16384 x 16384\n" + "DP-1 connected 2560x1440+0+0 (normal left inverted right x axis y axis) 600mm x 340mm\n" + " 2560x1440 59.95*+\n" + " 1920x1080 60.00\n" + "eDP-1 connected primary 1920x1200+2560+0 (normal left inverted right x axis y axis) 301mm x 188mm\n" + " 1920x1200 60.00*+\n" + "EOF\n" + "else\n" + f" printf '%s\\n' \"$*\" >> {calls_log!r}\n" + "fi\n" + ) + os.chmod(xr_p, 0o755) + + env = dict(os.environ) + env["DISPLAY"] = ":99" + env["HOME"] = tmp + env["XDG_CONFIG_HOME"] = os.path.join(tmp, ".config") + env["XDG_DATA_HOME"] = os.path.join(tmp, ".local", "share") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["ANODE_NO_DBUS"] = "1" + env["PATH"] = fbin + ":" + env.get("PATH", "") + + # Without xdpyinfo overriding DPI, auto scale must pick connected primary eDP-1 (~162 DPI -> 1.70x) + run_env(env, [APPLY_SCALE, "auto", "--no-apply"]) + with open(os.path.join(tmp, ".config", "anode", "scale.conf"), "r", encoding="utf-8") as f: + sconf = f.read() + assert "SCALE=1.70" in sconf, sconf + + # Saved multi-monitor profile restores matching signature via atomic xrandr call + os.makedirs(os.path.join(tmp, ".config", "anode"), exist_ok=True) + with open(os.path.join(tmp, ".config", "anode", "displays.conf"), "w", encoding="utf-8") as f: + f.write( + "[profile:DP-1,eDP-1]\n" + "output=eDP-1,1,1,1920x1200,60.00,0,0,normal\n" + "output=DP-1,1,0,2560x1440,59.95,1920,0,left\n" + ) + run_env(env, [APPLY_DISP]) + with open(calls_log, "r", encoding="utf-8") as f: + applied = f.read().strip() + assert "--output eDP-1 --mode 1920x1200 --rate 60.00 --pos 0x0 --rotate normal --primary" in applied, applied + assert "--output DP-1 --mode 2560x1440 --rate 59.95 --pos 1920x0 --rotate left" in applied, applied + + if __name__ == "__main__": with open(os.path.join(ROOT, "data", "env.sh"), "r", encoding="utf-8") as f: env_sh = f.read() @@ -485,4 +572,6 @@ if __name__ == "__main__": test_stale_env_does_not_override_scale_conf() test_gtk_theme_light_dark_detection_and_css_parse() test_ui_font_fallback_roboto_to_noto_sans() - print("test_theme_scale: ALL PASSED (7 fractional scales, 22 themes, legacy 192-DPI import, St overrides, auto DPI, scale.conf precedence, GTK light/dark, Roboto->Noto Sans fallback)") + test_deprecated_anodedefault_fallback_and_install() + test_primary_edid_and_apply_display() + print("test_theme_scale: ALL PASSED (7 fractional scales, 22 themes, legacy 192-DPI import, St overrides, auto DPI, scale.conf precedence, GTK light/dark, Roboto->Noto Sans fallback, AnodeDefault fallback/install, primary/displays.conf)") diff --git a/tests/test_units.c b/tests/test_units.c index adeafda..02741d8 100644 --- a/tests/test_units.c +++ b/tests/test_units.c @@ -2,7 +2,9 @@ #include #include #include +#include #include +#include #include "anode_scale.h" #include "anode_plat.h" @@ -14,6 +16,9 @@ #include "anode_power_policy.h" #include "anode_xkb_parse.h" #include "anode_sys_parse.h" +#include "anode_xth.h" +#include "anode_display_cfg.h" +#include "anode_bar_fmt.h" #include "anode-touch-gesture.h" static void test_scale_math(void) { @@ -174,6 +179,62 @@ static void test_power_policy_and_gestures(void) { anode_power_policy_step(&cfg, &st, 1000, false, 2, true, false, &act); assert(act.warn_low_batt && act.suspend_now); + /* lock_ms < dim_ms ordering must still trigger lock */ + cfg = anode_power_cfg_default(); + cfg.dim_ms = 600000U; + cfg.lock_ms = 300000U; + cfg.suspend_ms = 1800000U; + st = ANODE_PWR_ACTIVE; + anode_power_policy_step(&cfg, &st, 310000U, true, 90, true, false, &act); + assert(st == ANODE_PWR_LOCKED && act.lock_now); + assert(anode_power_policy_next_wake_ms(&cfg, 1000U, true, false) == 15000); + assert(anode_power_policy_next_wake_ms(&cfg, 295000U, true, false) == 5000); + + /* Dim and lock disabled, battery-only suspend */ + cfg.dim_ms = 0U; + cfg.lock_ms = 0U; + cfg.suspend_ms = 1800000U; + cfg.suspend_on_ac = false; + st = ANODE_PWR_ACTIVE; + anode_power_policy_step(&cfg, &st, 1900000U, true, 90, true, false, &act); + assert(st == ANODE_PWR_ACTIVE && !act.suspend_now && !act.lock_now && !act.dim_now); + anode_power_policy_step(&cfg, &st, 1900000U, false, 90, true, false, &act); + assert(st == ANODE_PWR_SUSPENDED && act.suspend_now); + + cfg.suspend_on_ac = true; + assert(anode_power_policy_next_wake_ms(&cfg, 1796000U, true, false) == 4000); + + /* Preset stepping & timeout formatting */ + char tfmt[16]; + anode_power_format_timeout(0U, tfmt, sizeof(tfmt)); + assert(strcmp(tfmt, "Off") == 0); + anode_power_format_timeout(30000U, tfmt, sizeof(tfmt)); + assert(strcmp(tfmt, "30s") == 0); + anode_power_format_timeout(300000U, tfmt, sizeof(tfmt)); + assert(strcmp(tfmt, "5m") == 0); + anode_power_format_timeout(3600000U, tfmt, sizeof(tfmt)); + assert(strcmp(tfmt, "1h") == 0); + assert(anode_power_step_screen_timeout_ms(0U, 1) == 30000U); + assert(anode_power_step_screen_timeout_ms(45000U, 1) == 60000U); + assert(anode_power_step_screen_timeout_ms(45000U, -1) == 30000U); + assert(anode_power_step_suspend_timeout_ms(1800000U, 1) == 2700000U); + assert(anode_power_step_suspend_timeout_ms(0U, -1) == 0U); + + /* Atomic power.conf save/load round-trip */ + char ptmpl[] = "/tmp/anode-u-pwr-XXXXXX"; + char *pdir = mkdtemp(ptmpl); + assert(pdir != NULL); + char pconf[256]; + snprintf(pconf, sizeof(pconf), "%s/power.conf", pdir); + anode_power_cfg_t wcfg = {0U, 180000U, 900000U, 10, true}; + assert(anode_power_cfg_save(pconf, &wcfg)); + anode_power_cfg_t rcfg; + assert(anode_power_cfg_load(pconf, &rcfg)); + assert(rcfg.dim_ms == 0U && rcfg.lock_ms == 180000U && rcfg.suspend_ms == 900000U && + rcfg.crit_batt_pct == 10 && rcfg.suspend_on_ac == true); + remove(pconf); + rmdir(pdir); + /* Gestures at 1.0x and 2.0x scales */ anode_touch_track_t tr = {0}; anode_touch_begin(&tr, 1, 500, 1070, 1000); @@ -292,6 +353,156 @@ static void test_platform_probe(void) { assert(buf[0] == '/'); } +static void test_xth_editor_and_import(void) { + anode_xth_t x; + anode_xth_init_anodized(&x); + assert(strcmp(x.name, "Anodized") == 0); + assert(strcmp(x.colors[ANODE_XTH_BG_MAIN], "#08090b") == 0); + assert(strcmp(x.colors[ANODE_XTH_ACCENT], "#cfd6e0") == 0); + assert(anode_xth_contrast_ratio("#08090b", "#cfd6e0") > 12.0); + + char sname[64]; + anode_xth_sanitize_name(" My Cool Theme! 2.0 ", sname, sizeof(sname)); + assert(strcmp(sname, "My_Cool_Theme_2_0") == 0); + anode_xth_sanitize_name("../..", sname, sizeof(sname)); + assert(sname[0] == '\0'); + + snprintf(x.name, sizeof(x.name), "SilverCustom"); + snprintf(x.colors[ANODE_XTH_BG_BAR], 16, "#101216"); + snprintf(x.colors[ANODE_XTH_SEL_BG], 16, "#445566"); + anode_xth_sync_derived(&x); + assert(strcmp(x.colors[ANODE_XTH_DWM_NORM_BG], "#101216") == 0); + assert(strcmp(x.colors[ANODE_XTH_DMENU_SEL_BG], "#445566") == 0); + assert(strcmp(x.colors[ANODE_XTH_ST_CURSOR], "#cfd6e0") == 0); + + char dir_tmpl[] = "/tmp/anode-u-xth-XXXXXX"; + char *tdir = mkdtemp(dir_tmpl); + assert(tdir != NULL); + + char p1[256], p2[256], badp[256], dest[512]; + snprintf(p1, sizeof(p1), "%s/src.xth", tdir); + snprintf(badp, sizeof(badp), "%s/bad.bin", tdir); + assert(anode_xth_save_file(p1, &x)); + + anode_xth_t loaded; + assert(anode_xth_load_file(p1, &loaded)); + assert(strcmp(loaded.name, "SilverCustom") == 0); + assert(strcmp(loaded.colors[ANODE_XTH_DWM_NORM_BG], "#101216") == 0); + + assert(anode_xth_import_file(p1, tdir, "ImportedSilver!", dest, sizeof(dest))); + assert(anode_xth_load_file(dest, &loaded)); + assert(strcmp(loaded.name, "ImportedSilver") == 0); + + FILE *bf = fopen(badp, "wb"); + assert(bf != NULL); + unsigned char zeros[8] = {0, 1, 2, 0, 3, 4, 5, 6}; + fwrite(zeros, 1, sizeof(zeros), bf); + fclose(bf); + assert(!anode_xth_load_file(badp, &loaded)); + + snprintf(p2, sizeof(p2), "%s/empty.xth", tdir); + FILE *ef = fopen(p2, "w"); + assert(ef != NULL); + fclose(ef); + assert(!anode_xth_load_file(p2, &loaded)); + + remove(p1); + remove(dest); + remove(badp); + remove(p2); + rmdir(tdir); +} + +static void test_display_cfg_and_snap(void) { + int ew = 0, eh = 0; + anode_disp_eff_size(1920, 1080, 1, &ew, &eh); + assert(ew == 1080 && eh == 1920); + anode_disp_eff_size(1920, 1080, 0, &ew, &eh); + assert(ew == 1920 && eh == 1080); + + anode_disp_out_t outs[2]; + memset(outs, 0, sizeof(outs)); + snprintf(outs[0].name, 32, "eDP-1"); + outs[0].enabled = true; outs[0].primary = true; + outs[0].w = 1920; outs[0].h = 1080; outs[0].hz = 60.0; + snprintf(outs[1].name, 32, "HDMI-1"); + outs[1].enabled = true; outs[1].primary = false; + outs[1].w = 2560; outs[1].h = 1440; outs[1].hz = 60.0; + + anode_disp_apply_preset(outs, 2, 0, ANODE_DISP_PRESET_RIGHT); + assert(outs[0].x == 0 && outs[0].y == 0 && outs[1].x == 1920 && outs[1].y == 0); + + anode_disp_apply_preset(outs, 2, 0, ANODE_DISP_PRESET_LEFT); + assert(outs[1].x == 0 && outs[0].x == 2560); + + anode_disp_apply_preset(outs, 2, 0, ANODE_DISP_PRESET_ABOVE); + assert(outs[1].y == 0 && outs[0].y == 1440); + + anode_disp_apply_preset(outs, 2, 0, ANODE_DISP_PRESET_RIGHT); + int sx = 0, sy = 0; + anode_disp_snap(outs, 2, 1, 1900, 18, 32, &sx, &sy); + assert(sx == 1920 && sy == 0); + + char sig[128]; + anode_disp_signature(outs, 2, sig, sizeof(sig)); + assert(strcmp(sig, "HDMI-1,eDP-1") == 0); + + char dir_tmpl[] = "/tmp/anode-u-disp-XXXXXX"; + char *tdir = mkdtemp(dir_tmpl); + assert(tdir != NULL); + char conf[256]; + snprintf(conf, sizeof(conf), "%s/displays.conf", tdir); + assert(anode_disp_save_profile(conf, outs, 2)); + + anode_disp_out_t loaded[4]; + int nl = anode_disp_load_profile(conf, sig, loaded, 4); + assert(nl == 2); + assert(strcmp(loaded[0].name, "eDP-1") == 0 && loaded[0].primary); + assert(strcmp(loaded[1].name, "HDMI-1") == 0 && loaded[1].x == 1920 && loaded[1].w == 2560); + + const char *av[64]; + char tokbuf[512]; + int ac = anode_disp_build_xrandr_argv(loaded, nl, av, 64, tokbuf, sizeof(tokbuf)); + assert(ac > 8 && strcmp(av[0], "xrandr") == 0); + + anode_disp_apply_preset(outs, 2, 0, ANODE_DISP_PRESET_PRIMARY_ONLY); + assert(outs[0].enabled && outs[0].primary && !outs[1].enabled); + + outs[0].enabled = false; + assert(anode_disp_build_xrandr_argv(outs, 2, av, 64, tokbuf, sizeof(tokbuf)) == -1); + + remove(conf); + rmdir(tdir); +} + +static void test_bar_status_compaction(void) { + const char *full = " VOL 75% | CPU 12% | RAM 45% | BAT 85%+ | us | 2026-11-27 08:02 "; + char out[256]; + + anode_bar_compact_status(full, 0, out, sizeof(out)); + assert(strcmp(out, "VOL 75% | CPU 12% | RAM 45% | BAT 85%+ | us | 2026-11-27 08:02") == 0); + + anode_bar_compact_status(full, 1, out, sizeof(out)); + assert(strcmp(out, "V:75% C:12% R:45% B:85%+ us 11-27 08:02") == 0); + + anode_bar_compact_status(full, 2, out, sizeof(out)); + assert(strcmp(out, "V:75% B:85%+ us 08:02") == 0); + + anode_bar_compact_status(full, 3, out, sizeof(out)); + assert(strcmp(out, "us 08:02") == 0); + + const char *desk = " VOL MUTE | CPU 5% | RAM 30% | AC | de | 2026-11-27 08:02 "; + anode_bar_compact_status(desk, 1, out, sizeof(out)); + assert(strcmp(out, "V:M C:5% R:30% AC de 11-27 08:02") == 0); + anode_bar_compact_status(desk, 2, out, sizeof(out)); + assert(strcmp(out, "V:M de 08:02") == 0); + anode_bar_compact_status(desk, 3, out, sizeof(out)); + assert(strcmp(out, "de 08:02") == 0); + + anode_bar_compact_status("custom bar text", 2, out, sizeof(out)); + assert(strcmp(out, "custom bar text") == 0); +} + int main(void) { test_scale_math(); test_dns_validation(); @@ -302,6 +513,9 @@ int main(void) { test_xkb_layout_parser(); test_sys_parsers(); test_platform_probe(); + test_xth_editor_and_import(); + test_display_cfg_and_snap(); + test_bar_status_compaction(); printf("test_units: ALL PASSED\n"); return 0; } diff --git a/tests/test_x11_xvfb.py b/tests/test_x11_xvfb.py index 7d88620..ff03f1b 100755 --- a/tests/test_x11_xvfb.py +++ b/tests/test_x11_xvfb.py @@ -647,6 +647,11 @@ def test_lockscreen_overlaps_systray(): lock_win = wait_until(find_lock_win) assert lock_win, "anode-lock window did not map" + la = XWindowAttributes() + assert X11.XGetWindowAttributes(dpy, lock_win, ctypes.byref(la)) + assert la.x == 0 and la.y == 0 and la.width == 1280 and la.height == 800, ( + la.x, la.y, la.width, la.height + ) # Trigger systray updates while locked: dock a 2nd icon and reload dwm via SIGUSR1 dock_dummy_icon() @@ -1183,7 +1188,7 @@ def test_wine_take_focus_workspace_switch(): env=env, check=True) time.sleep(0.25) - # Phase 2: switch away to Tag 2 via Super_L + 2, wait, then return via bar Tag 1 click (x=50, y=10) + # Phase 2: switch away to Tag 2 via Super_L + 2, wait, then return via bar Tag 1 click (x=38, y=10) subprocess.run(["xdotool", "keydown", "Super_L"], env=env, check=True) time.sleep(0.06) subprocess.run(["xdotool", "key", "2"], env=env, check=True) @@ -1192,7 +1197,7 @@ def test_wine_take_focus_workspace_switch(): time.sleep(0.25) subprocess.run(["xdotool", "mousemove", "400", "400", "click", "1"], env=env, check=True) time.sleep(0.2) - subprocess.run(["xdotool", "mousemove", "50", "10", "click", "1"], env=env, check=True) + subprocess.run(["xdotool", "mousemove", "38", "10", "click", "1"], env=env, check=True) time.sleep(0.3) subprocess.run(["xdotool", "mousemove", "520", "480", "click", "1", "mousemove", "720", "320", "key", "b"], env=env, check=True) @@ -1711,7 +1716,7 @@ def test_live_theme_reload_and_bar_artifacts(): env.get("PATH", "") ) subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), "1.00", "--touch=0"], env=env, check=True) - subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-theme"), "AnodeDefault"], env=env, check=True) + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-theme"), "Anodized"], env=env, check=True) xvfb = subprocess.Popen( ["Xvfb", disp, "-noreset", "-screen", "0", "1280x800x24", "-nolisten", "tcp"], @@ -1816,8 +1821,8 @@ def test_live_theme_reload_and_bar_artifacts(): ) return res - # Phase 1: Initial AnodeDefault - check_palette("AnodeDefault", {0x11161F, 0x2B5278}, 0x0B0E14, 0x0B0E14) + # Phase 1: Initial Anodized + check_palette("Anodized", {0x0E1014, 0x38414F}, 0x08090B, 0x08090B) # Phase 2: Switch to SolarizedLight via anode-apply-theme with ANODE_NO_SIGNAL=1 # (must propagate purely via xrdb -load + live XA_RESOURCE_MANAGER lookup!) @@ -1851,6 +1856,50 @@ def test_live_theme_reload_and_bar_artifacts(): terminate(xvfb) +def test_themes_cli_install_and_arrange_smoke(): + disp = pick_display() + with tempfile.TemporaryDirectory() as home: + env = dict(os.environ) + env["DISPLAY"] = disp + env["HOME"] = home + env["XDG_CONFIG_HOME"] = os.path.join(home, ".config") + env["ANODE_PREFIX"] = ROOT + env["LD_LIBRARY_PATH"] = os.path.join(BUILD, "libgemui") + (":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "") + + src_xth = os.path.join(home, "NonStandardDir", "SilverSmoke.xth") + os.makedirs(os.path.dirname(src_xth)) + with open(src_xth, "w", encoding="utf-8") as f: + f.write("theme.name: SilverSmoke\ntheme.bgMain: #0a0b0e\ntheme.fgMain: #e0e5ec\ntheme.accent: #cfd6e0\n") + + inst = subprocess.run( + [os.path.join(BUILD, "apps", "anode-themes"), "--install", src_xth, "SmokeCustom"], + env=env, capture_output=True, text=True, check=True, + ) + installed_p = os.path.join(home, ".config", "anode", "themes", "SmokeCustom.xth") + assert os.path.isfile(installed_p), inst.stdout + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-noreset", "-screen", "0", "1440x900x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dpy = None + proc = None + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode())) + assert dpy, f"Failed to open Xvfb {disp}" + proc = subprocess.Popen( + [os.path.join(BUILD, "apps", "anode-display"), "--arrange"], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + time.sleep(0.4) + assert proc.poll() is None, f"anode-display --arrange exited with {proc.returncode}" + finally: + terminate(proc) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + def main(): if not shutil.which("Xvfb"): print("test_x11_xvfb: Xvfb not installed (skipping)") @@ -1879,6 +1928,8 @@ def main(): print("test_x11_xvfb: systray XEmbed dock/map race OK") test_live_theme_reload_and_bar_artifacts() print("test_x11_xvfb: live theme reload & bar artifact check OK") + test_themes_cli_install_and_arrange_smoke() + print("test_x11_xvfb: anode-themes --install & anode-display --arrange smoke OK") return 0