commit 65bfe3c65a43c3ed7231b5b678a1598932d37b5e Author: Luxferre Date: Thu Nov 26 11:34:53 2026 +0200 feat: initial ANODE desktop environment adapted from Geminux diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..62a307e --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/build/ +*.o +*.so +*.tmp.* +__pycache__/ +*.py[cod] +.DS_Store diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..41e976a --- /dev/null +++ b/Makefile @@ -0,0 +1,411 @@ +# ANODE (A Nicely Optimized Desktop Environment) +# Strict POSIX-compatible Makefile for Linux, FreeBSD, OpenBSD, NetBSD, and Unix-likes. + +.POSIX: + +PREFIX = /usr/local +MANPREFIX = $(PREFIX)/share/man +DESTDIR = +CC = cc +CXX = c++ +PKG_CONFIG = pkg-config +WITH_GTKTTK = auto +CFLAGS = -O2 +CXXFLAGS = -O2 +LDFLAGS = + +VERSION = 1.0.0 +DWM_VERSION = 6.5-anode +DMENU_VERSION = 5.3-anode +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 + +build/flags.sh: scripts/detect-env.sh + CC="$(CC)" CXX="$(CXX)" PKG_CONFIG="$(PKG_CONFIG)" WITH_GTKTTK="$(WITH_GTKTTK)" sh scripts/detect-env.sh build/flags.sh + +# --- Common platform abstraction --- +build/common/anode_plat.o: src/common/anode_plat.c src/common/anode_plat.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -Wextra -fPIC -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" -c src/common/anode_plat.c -o build/common/anode_plat.o + +# --- Patched DWM --- +dwm: build/dwm/dwm + +build/dwm/drw.o: src/dwm/drw.c src/dwm/drw.h src/dwm/util.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 $$DWM_CFLAGS -c src/dwm/drw.c -o build/dwm/drw.o + +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/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 + . ./build/flags.sh && $(CC) -o build/dwm/dwm build/dwm/dwm.o build/dwm/drw.o build/dwm/util.o $(LDFLAGS) $$DWM_LIBS -lm + +# --- Patched dmenu --- +dmenu: build/dmenu/dmenu build/dmenu/stest + +build/dmenu/drw.o: src/dmenu/drw.c src/dmenu/drw.h src/dmenu/util.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L -DXINERAMA $$DMENU_CFLAGS -c src/dmenu/drw.c -o build/dmenu/drw.o + +build/dmenu/util.o: src/dmenu/util.c src/dmenu/util.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L -c src/dmenu/util.c -o build/dmenu/util.o + +build/dmenu/dmenu.o: src/dmenu/dmenu.c src/dmenu/arg.h src/dmenu/config.h src/dmenu/drw.h src/dmenu/util.h src/common/anode_scale.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -D_POSIX_C_SOURCE=200809L -DXINERAMA -DVERSION="\"$(DMENU_VERSION)\"" -Isrc/common $$DMENU_CFLAGS -c src/dmenu/dmenu.c -o build/dmenu/dmenu.o + +build/dmenu/stest.o: src/dmenu/stest.c src/dmenu/arg.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -D_POSIX_C_SOURCE=200809L -DVERSION="\"$(DMENU_VERSION)\"" -c src/dmenu/stest.c -o build/dmenu/stest.o + +build/dmenu/dmenu: build/dmenu/dmenu.o build/dmenu/drw.o build/dmenu/util.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/dmenu/dmenu build/dmenu/dmenu.o build/dmenu/drw.o build/dmenu/util.o $(LDFLAGS) $$DMENU_LIBS + +build/dmenu/stest: build/dmenu/stest.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/dmenu/stest build/dmenu/stest.o $(LDFLAGS) + +# --- Patched st --- +st: build/st/st + +build/st/st.o: src/st/st.c src/st/st.h src/st/win.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=600 -DVERSION="\"$(ST_VERSION)\"" $$ST_CFLAGS -c src/st/st.c -o build/st/st.o + +build/st/x.o: src/st/x.c src/st/st.h src/st/win.h src/st/hb.h src/st/arg.h src/st/config.h src/common/anode_scale.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=600 -DVERSION="\"$(ST_VERSION)\"" -Isrc/common $$ST_CFLAGS -c src/st/x.c -o build/st/x.o + +build/st/hb.o: src/st/hb.c src/st/st.h src/st/hb.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c99 -Wall -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=600 -DVERSION="\"$(ST_VERSION)\"" $$ST_CFLAGS -c src/st/hb.c -o build/st/hb.o + +build/st/st: build/st/st.o build/st/x.o build/st/hb.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/st/st build/st/st.o build/st/x.o build/st/hb.o $(LDFLAGS) $$ST_LIBS + +# --- GemUI SDK --- +libgemui: build/libgemui/libgemui.so build/libgemui/gemui.pc + +build/libgemui/gemui.o: src/libgemui/gemui.c src/libgemui/gemui.h src/common/anode_scale.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -fPIC -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$GEMUI_CFLAGS -c src/libgemui/gemui.c -o build/libgemui/gemui.o + +build/libgemui/libgemui.so: build/libgemui/gemui.o build/common/anode_plat.o build/flags.sh + . ./build/flags.sh && $(CC) -shared -Wl,-soname,libgemui.so -o build/libgemui/libgemui.so build/libgemui/gemui.o build/common/anode_plat.o $(LDFLAGS) $$GEMUI_LIBS + +build/libgemui/gemui.pc: src/libgemui/gemui.pc.in build/flags.sh + sed "s|@PREFIX@|$(PREFIX)|g; s|@VERSION@|$(VERSION)|g" src/libgemui/gemui.pc.in > build/libgemui/gemui.pc + +# --- Desktop Utilities & Virtual Keyboard --- +apps: build/apps/anode-net build/apps/anode-audio build/apps/anode-display build/apps/anode-datetime build/apps/anode-power build/apps/anode-themes build/apps/anode-lock build/apps/anode-media-key + +vkbd: build/apps/anode-vkbd + +build/apps/anode-net.o: src/apps/anode-net.c src/libgemui/gemui.h src/common/anode_plat.h src/common/anode_wifi_list.h src/common/anode_bt_list.h src/common/anode_dns_valid.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-net.c -o build/apps/anode-net.o + +build/apps/anode-net: build/apps/anode-net.o build/libgemui/libgemui.so build/common/anode_plat.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/apps/anode-net build/apps/anode-net.o build/common/anode_plat.o -Lbuild/libgemui -Wl,-rpath,$(PREFIX)/lib -lgemui $(LDFLAGS) $$APP_LIBS + +build/apps/anode-audio.o: src/apps/anode-audio.c src/libgemui/gemui.h src/common/anode_plat.h src/common/anode_audio_parse.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-audio.c -o build/apps/anode-audio.o + +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/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 + . ./build/flags.sh && $(CC) -o build/apps/anode-display build/apps/anode-display.o build/common/anode_plat.o -Lbuild/libgemui -Wl,-rpath,$(PREFIX)/lib -lgemui $(LDFLAGS) $$APP_LIBS + +build/apps/anode-datetime.o: src/apps/anode-datetime.c src/libgemui/gemui.h src/common/anode_plat.h src/common/anode_tz_valid.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-datetime.c -o build/apps/anode-datetime.o + +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/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/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 + . ./build/flags.sh && $(CC) -o build/apps/anode-themes build/apps/anode-themes.o build/common/anode_plat.o -Lbuild/libgemui -Wl,-rpath,$(PREFIX)/lib -lgemui $(LDFLAGS) $$APP_LIBS + +build/apps/anode-lock.o: src/apps/anode-lock.c src/libgemui/gemui.h src/common/anode_plat.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-lock.c -o build/apps/anode-lock.o + +build/apps/anode-lock: build/apps/anode-lock.o build/libgemui/libgemui.so build/common/anode_plat.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/apps/anode-lock build/apps/anode-lock.o build/common/anode_plat.o -Lbuild/libgemui -Wl,-rpath,$(PREFIX)/lib -lgemui $(LDFLAGS) $$APP_LIBS + +build/apps/anode-media-key.o: src/apps/anode-media-key.c src/common/anode_plat.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" -c src/apps/anode-media-key.c -o build/apps/anode-media-key.o + +build/apps/anode-media-key: build/apps/anode-media-key.o build/common/anode_plat.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/apps/anode-media-key build/apps/anode-media-key.o build/common/anode_plat.o $(LDFLAGS) + +build/apps/anode-vkbd.o: src/apps/anode-vkbd.c src/libgemui/gemui.h src/common/anode_plat.h src/common/anode_scale.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-vkbd.c -o build/apps/anode-vkbd.o + +build/apps/anode-vkbd: build/apps/anode-vkbd.o build/libgemui/libgemui.so build/common/anode_plat.o build/flags.sh + . ./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 + +build/daemons/anode-statusd.o: src/daemons/anode-statusd.c src/common/anode_plat.h src/common/anode_tz_valid.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" $$STATUSD_CFLAGS -c src/daemons/anode-statusd.c -o build/daemons/anode-statusd.o + +build/daemons/anode-statusd: build/daemons/anode-statusd.o build/common/anode_plat.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/daemons/anode-statusd build/daemons/anode-statusd.o build/common/anode_plat.o $(LDFLAGS) $$STATUSD_LIBS + +build/daemons/anode-touch-gesture.o: src/daemons/anode-touch-gesture.c src/daemons/anode-touch-gesture.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/daemons -c src/daemons/anode-touch-gesture.c -o build/daemons/anode-touch-gesture.o + +build/daemons/anode-touchd.o: src/daemons/anode-touchd.c src/daemons/anode-touch-gesture.h src/common/anode_scale.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/daemons -Isrc/common $$TOUCHD_CFLAGS -c src/daemons/anode-touchd.c -o build/daemons/anode-touchd.o + +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/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 + . ./build/flags.sh && $(CC) -o build/daemons/anode-powerd build/daemons/anode-powerd.o build/common/anode_plat.o $(LDFLAGS) $$POWERD_LIBS + +build/daemons/anode-power-ctl.o: src/daemons/anode-power-ctl.c src/common/anode_plat.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -DANODE_PREFIX="\"$(PREFIX)\"" -c src/daemons/anode-power-ctl.c -o build/daemons/anode-power-ctl.o + +build/daemons/anode-power-ctl: build/daemons/anode-power-ctl.o build/common/anode_plat.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/daemons/anode-power-ctl build/daemons/anode-power-ctl.o build/common/anode_plat.o $(LDFLAGS) + +build/daemons/anode-dnsctl.o: src/daemons/anode-dnsctl.c src/common/anode_dns_valid.h src/common/anode_plat.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -c src/daemons/anode-dnsctl.c -o build/daemons/anode-dnsctl.o + +build/daemons/anode-dnsctl: build/daemons/anode-dnsctl.o build/common/anode_plat.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/daemons/anode-dnsctl build/daemons/anode-dnsctl.o build/common/anode_plat.o $(LDFLAGS) + +build/daemons/anode-tzctl.o: src/daemons/anode-tzctl.c src/common/anode_tz_valid.h src/common/anode_plat.h build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -Isrc/common -c src/daemons/anode-tzctl.c -o build/daemons/anode-tzctl.o + +build/daemons/anode-tzctl: build/daemons/anode-tzctl.o build/common/anode_plat.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/daemons/anode-tzctl build/daemons/anode-tzctl.o build/common/anode_plat.o $(LDFLAGS) + +build/daemons/anode-checkpw.o: src/daemons/anode-checkpw.c build/flags.sh + . ./build/flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra $$CHECKPW_DEFS -c src/daemons/anode-checkpw.c -o build/daemons/anode-checkpw.o + +build/daemons/anode-checkpw: build/daemons/anode-checkpw.o build/flags.sh + . ./build/flags.sh && $(CC) -o build/daemons/anode-checkpw build/daemons/anode-checkpw.o $(LDFLAGS) $$CHECKPW_LIBS + +# --- gtkTtk 0.9 Port --- +gtkttk-auto: build/flags.sh + . ./build/flags.sh && if [ "$$GTKTTK_AVAILABLE" = "1" ]; then $(MAKE) gtkttk; else printf 'Note: skipping gtkTtk (%s)\n' "$$GTKTTK_REASON"; fi + +gtkttk: build/gtkTtk/libgtkTtk0.9.so + +build/gtkTtk/gtkTtk_Init.o: src/gtkTtk/generic/gtkTtk_Init.cpp build/flags.sh + . ./build/flags.sh && [ "$$GTKTTK_AVAILABLE" = "1" ] || { printf 'gtkTtk build error: %s\n' "$$GTKTTK_REASON" >&2; exit 1; } && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Init.cpp -o build/gtkTtk/gtkTtk_Init.o + +build/gtkTtk/gtkTtk_GtkApp.o: src/gtkTtk/generic/gtkTtk_GtkApp.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_GtkApp.cpp -o build/gtkTtk/gtkTtk_GtkApp.o + +build/gtkTtk/gtkTtk_Utilities.o: src/gtkTtk/generic/gtkTtk_Utilities.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Utilities.cpp -o build/gtkTtk/gtkTtk_Utilities.o + +build/gtkTtk/gtkTtk_Background.o: src/gtkTtk/generic/gtkTtk_Background.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Background.cpp -o build/gtkTtk/gtkTtk_Background.o + +build/gtkTtk/gtkTtk_Button.o: src/gtkTtk/generic/gtkTtk_Button.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Button.cpp -o build/gtkTtk/gtkTtk_Button.o + +build/gtkTtk/gtkTtk_CheckButton.o: src/gtkTtk/generic/gtkTtk_CheckButton.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_CheckButton.cpp -o build/gtkTtk/gtkTtk_CheckButton.o + +build/gtkTtk/gtkTtk_RadioButton.o: src/gtkTtk/generic/gtkTtk_RadioButton.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_RadioButton.cpp -o build/gtkTtk/gtkTtk_RadioButton.o + +build/gtkTtk/gtkTtk_ToolButton.o: src/gtkTtk/generic/gtkTtk_ToolButton.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_ToolButton.cpp -o build/gtkTtk/gtkTtk_ToolButton.o + +build/gtkTtk/gtkTtk_Labelframe.o: src/gtkTtk/generic/gtkTtk_Labelframe.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Labelframe.cpp -o build/gtkTtk/gtkTtk_Labelframe.o + +build/gtkTtk/gtkTtk_Entry.o: src/gtkTtk/generic/gtkTtk_Entry.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Entry.cpp -o build/gtkTtk/gtkTtk_Entry.o + +build/gtkTtk/gtkTtk_Menubutton.o: src/gtkTtk/generic/gtkTtk_Menubutton.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Menubutton.cpp -o build/gtkTtk/gtkTtk_Menubutton.o + +build/gtkTtk/gtkTtk_Scrollbar.o: src/gtkTtk/generic/gtkTtk_Scrollbar.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Scrollbar.cpp -o build/gtkTtk/gtkTtk_Scrollbar.o + +build/gtkTtk/gtkTtk_Scale.o: src/gtkTtk/generic/gtkTtk_Scale.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Scale.cpp -o build/gtkTtk/gtkTtk_Scale.o + +build/gtkTtk/gtkTtk_Progress.o: src/gtkTtk/generic/gtkTtk_Progress.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Progress.cpp -o build/gtkTtk/gtkTtk_Progress.o + +build/gtkTtk/gtkTtk_SizeGrip.o: src/gtkTtk/generic/gtkTtk_SizeGrip.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_SizeGrip.cpp -o build/gtkTtk/gtkTtk_SizeGrip.o + +build/gtkTtk/gtkTtk_Paned.o: src/gtkTtk/generic/gtkTtk_Paned.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Paned.cpp -o build/gtkTtk/gtkTtk_Paned.o + +build/gtkTtk/gtkTtk_Notebook.o: src/gtkTtk/generic/gtkTtk_Notebook.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Notebook.cpp -o build/gtkTtk/gtkTtk_Notebook.o + +build/gtkTtk/gtkTtk_Combobox.o: src/gtkTtk/generic/gtkTtk_Combobox.cpp build/flags.sh + . ./build/flags.sh && $(CXX) $(CXXFLAGS) -fPIC -Wno-deprecated-declarations -Wno-cpp -DGTKTTK_INSTALL_XERROR_HANDLER -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS -DPACKAGE_NAME="\"gtkTtk\"" -DPACKAGE_VERSION="\"0.9\"" -Isrc/gtkTtk/generic $$GTKTTK_CXXFLAGS -c src/gtkTtk/generic/gtkTtk_Combobox.cpp -o build/gtkTtk/gtkTtk_Combobox.o + +build/gtkTtk/libgtkTtk0.9.so: \ + build/gtkTtk/gtkTtk_Init.o \ + build/gtkTtk/gtkTtk_GtkApp.o \ + build/gtkTtk/gtkTtk_Utilities.o \ + build/gtkTtk/gtkTtk_Background.o \ + build/gtkTtk/gtkTtk_Button.o \ + build/gtkTtk/gtkTtk_CheckButton.o \ + build/gtkTtk/gtkTtk_RadioButton.o \ + build/gtkTtk/gtkTtk_ToolButton.o \ + build/gtkTtk/gtkTtk_Labelframe.o \ + build/gtkTtk/gtkTtk_Entry.o \ + build/gtkTtk/gtkTtk_Menubutton.o \ + build/gtkTtk/gtkTtk_Scrollbar.o \ + build/gtkTtk/gtkTtk_Scale.o \ + build/gtkTtk/gtkTtk_Progress.o \ + build/gtkTtk/gtkTtk_SizeGrip.o \ + build/gtkTtk/gtkTtk_Paned.o \ + build/gtkTtk/gtkTtk_Notebook.o \ + build/gtkTtk/gtkTtk_Combobox.o \ + build/flags.sh + . ./build/flags.sh && $(CXX) -shared -o build/gtkTtk/libgtkTtk0.9.so \ + build/gtkTtk/gtkTtk_Init.o build/gtkTtk/gtkTtk_GtkApp.o build/gtkTtk/gtkTtk_Utilities.o \ + build/gtkTtk/gtkTtk_Background.o build/gtkTtk/gtkTtk_Button.o build/gtkTtk/gtkTtk_CheckButton.o \ + build/gtkTtk/gtkTtk_RadioButton.o build/gtkTtk/gtkTtk_ToolButton.o build/gtkTtk/gtkTtk_Labelframe.o \ + build/gtkTtk/gtkTtk_Entry.o build/gtkTtk/gtkTtk_Menubutton.o build/gtkTtk/gtkTtk_Scrollbar.o \ + build/gtkTtk/gtkTtk_Scale.o build/gtkTtk/gtkTtk_Progress.o build/gtkTtk/gtkTtk_SizeGrip.o \ + build/gtkTtk/gtkTtk_Paned.o build/gtkTtk/gtkTtk_Notebook.o build/gtkTtk/gtkTtk_Combobox.o \ + $(LDFLAGS) $$GTKTTK_LDFLAGS + +# --- Install / Uninstall / Clean --- +install: all + mkdir -p \ + "$(DESTDIR)$(PREFIX)/bin" \ + "$(DESTDIR)$(PREFIX)/lib" \ + "$(DESTDIR)$(PREFIX)/lib/pkgconfig" \ + "$(DESTDIR)$(PREFIX)/include" \ + "$(DESTDIR)$(PREFIX)/share/anode/themes" \ + "$(DESTDIR)$(PREFIX)/share/xsessions" \ + "$(DESTDIR)$(MANPREFIX)/man1" + cp -f build/dwm/dwm "$(DESTDIR)$(PREFIX)/bin/dwm" + cp -f build/dmenu/dmenu build/dmenu/stest src/dmenu/dmenu_path src/dmenu/dmenu_run "$(DESTDIR)$(PREFIX)/bin/" + cp -f build/st/st "$(DESTDIR)$(PREFIX)/bin/st" + cp -f build/apps/anode-net build/apps/anode-audio build/apps/anode-display \ + 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 \ + build/daemons/anode-power-ctl build/daemons/anode-dnsctl build/daemons/anode-tzctl \ + build/daemons/anode-checkpw "$(DESTDIR)$(PREFIX)/bin/" + cp -f scripts/anode-session scripts/anode-launcher scripts/anode-apply-theme \ + scripts/anode-apply-scale scripts/anode-sync-gtk-theme scripts/anode-sync-dunst-theme \ + "$(DESTDIR)$(PREFIX)/bin/" + chmod 755 \ + "$(DESTDIR)$(PREFIX)/bin/dwm" "$(DESTDIR)$(PREFIX)/bin/dmenu" \ + "$(DESTDIR)$(PREFIX)/bin/stest" "$(DESTDIR)$(PREFIX)/bin/dmenu_path" \ + "$(DESTDIR)$(PREFIX)/bin/dmenu_run" "$(DESTDIR)$(PREFIX)/bin/st" \ + "$(DESTDIR)$(PREFIX)/bin/anode-net" "$(DESTDIR)$(PREFIX)/bin/anode-audio" \ + "$(DESTDIR)$(PREFIX)/bin/anode-display" "$(DESTDIR)$(PREFIX)/bin/anode-datetime" \ + "$(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-power-ctl" "$(DESTDIR)$(PREFIX)/bin/anode-dnsctl" \ + "$(DESTDIR)$(PREFIX)/bin/anode-tzctl" "$(DESTDIR)$(PREFIX)/bin/anode-checkpw" \ + "$(DESTDIR)$(PREFIX)/bin/anode-session" "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ + "$(DESTDIR)$(PREFIX)/bin/anode-apply-theme" "$(DESTDIR)$(PREFIX)/bin/anode-apply-scale" \ + "$(DESTDIR)$(PREFIX)/bin/anode-sync-gtk-theme" "$(DESTDIR)$(PREFIX)/bin/anode-sync-dunst-theme" + cp -f build/libgemui/libgemui.so "$(DESTDIR)$(PREFIX)/lib/libgemui.so" + chmod 755 "$(DESTDIR)$(PREFIX)/lib/libgemui.so" + cp -f src/libgemui/gemui.h "$(DESTDIR)$(PREFIX)/include/gemui.h" + 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" + 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" + chmod 644 "$(DESTDIR)$(PREFIX)/share/anode/env.sh" + cp -f src/st/st.info "$(DESTDIR)$(PREFIX)/share/anode/st.info" + chmod 644 "$(DESTDIR)$(PREFIX)/share/anode/st.info" + sed "s|@PREFIX@|$(PREFIX)|g" data/anode.desktop > "$(DESTDIR)$(PREFIX)/share/xsessions/anode.desktop" + chmod 644 "$(DESTDIR)$(PREFIX)/share/xsessions/anode.desktop" + sed "s/VERSION/$(DWM_VERSION)/g" src/dwm/dwm.1 > "$(DESTDIR)$(MANPREFIX)/man1/dwm.1" + sed "s/VERSION/$(DMENU_VERSION)/g" src/dmenu/dmenu.1 > "$(DESTDIR)$(MANPREFIX)/man1/dmenu.1" + sed "s/VERSION/$(DMENU_VERSION)/g" src/dmenu/stest.1 > "$(DESTDIR)$(MANPREFIX)/man1/stest.1" + sed "s/VERSION/$(ST_VERSION)/g" src/st/st.1 > "$(DESTDIR)$(MANPREFIX)/man1/st.1" + chmod 644 "$(DESTDIR)$(MANPREFIX)/man1/dwm.1" "$(DESTDIR)$(MANPREFIX)/man1/dmenu.1" \ + "$(DESTDIR)$(MANPREFIX)/man1/stest.1" "$(DESTDIR)$(MANPREFIX)/man1/st.1" + if [ -f build/gtkTtk/libgtkTtk0.9.so ]; then \ + mkdir -p "$(DESTDIR)$(PREFIX)/lib/gtkTtk0.9"; \ + cp -f build/gtkTtk/libgtkTtk0.9.so "$(DESTDIR)$(PREFIX)/lib/gtkTtk0.9/libgtkTtk0.9.so"; \ + cp -f src/gtkTtk/library/gtkTtk.tcl src/gtkTtk/library/pkgIndex.tcl "$(DESTDIR)$(PREFIX)/lib/gtkTtk0.9/"; \ + 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 + +uninstall: + rm -f \ + "$(DESTDIR)$(PREFIX)/bin/dwm" \ + "$(DESTDIR)$(PREFIX)/bin/dmenu" \ + "$(DESTDIR)$(PREFIX)/bin/stest" \ + "$(DESTDIR)$(PREFIX)/bin/dmenu_path" \ + "$(DESTDIR)$(PREFIX)/bin/dmenu_run" \ + "$(DESTDIR)$(PREFIX)/bin/st" \ + "$(DESTDIR)$(PREFIX)/bin/anode-net" \ + "$(DESTDIR)$(PREFIX)/bin/anode-audio" \ + "$(DESTDIR)$(PREFIX)/bin/anode-display" \ + "$(DESTDIR)$(PREFIX)/bin/anode-datetime" \ + "$(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-power-ctl" \ + "$(DESTDIR)$(PREFIX)/bin/anode-dnsctl" \ + "$(DESTDIR)$(PREFIX)/bin/anode-tzctl" \ + "$(DESTDIR)$(PREFIX)/bin/anode-checkpw" \ + "$(DESTDIR)$(PREFIX)/bin/anode-session" \ + "$(DESTDIR)$(PREFIX)/bin/anode-launcher" \ + "$(DESTDIR)$(PREFIX)/bin/anode-apply-theme" \ + "$(DESTDIR)$(PREFIX)/bin/anode-apply-scale" \ + "$(DESTDIR)$(PREFIX)/bin/anode-sync-gtk-theme" \ + "$(DESTDIR)$(PREFIX)/bin/anode-sync-dunst-theme" \ + "$(DESTDIR)$(PREFIX)/lib/libgemui.so" \ + "$(DESTDIR)$(PREFIX)/include/gemui.h" \ + "$(DESTDIR)$(PREFIX)/lib/pkgconfig/gemui.pc" \ + "$(DESTDIR)$(PREFIX)/share/xsessions/anode.desktop" \ + "$(DESTDIR)$(MANPREFIX)/man1/dwm.1" \ + "$(DESTDIR)$(MANPREFIX)/man1/dmenu.1" \ + "$(DESTDIR)$(MANPREFIX)/man1/stest.1" \ + "$(DESTDIR)$(MANPREFIX)/man1/st.1" + rm -rf "$(DESTDIR)$(PREFIX)/share/anode" "$(DESTDIR)$(PREFIX)/lib/gtkTtk0.9" + +clean: + rm -rf build + +# --- Tests --- +build/tests/test_units: tests/test_units.c src/daemons/anode-touch-gesture.c src/common/anode_plat.c build/flags.sh + . ./build/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 + python3 tests/test_posix_make.py + ./build/tests/test_units + python3 tests/test_theme_scale.py + python3 tests/test_x11_xvfb.py + +.PHONY: all dwm dmenu st libgemui apps vkbd daemons gtkttk gtkttk-auto install uninstall clean test diff --git a/README.md b/README.md new file mode 100644 index 0000000..304a6ce --- /dev/null +++ b/README.md @@ -0,0 +1,58 @@ +# ANODE — A Nicely Optimized Desktop Environment + +ANODE is a lightweight, keyboard-first, cross-Unix X11 desktop environment adapted from [Geminux](../geminux) for **Linux, FreeBSD, OpenBSD, and NetBSD**. It aims for low memory footprint, zero busy-polling daemons, unified `.xth` theming across every toolkit, first-class XEmbed/EWMH systray integration, fractional DPI scaling, and optional touch / virtual keyboard support. + +## Key Features + +- **Patched Window & Core X11 Stack**: + - **DWM (`6.5-anode`)**: Pango/HarfBuzz status & title bar (`Fira Code` + `DejaVuSansM Nerd Font`), first-class 32-bit ARGB XEmbed systray (`_NET_SYSTEM_TRAY_S`, `XEMBED_INFO` state, empty-tray unmap, `ReparentNotify` undocking, multi-monitor relocation), EWMH dock struts (`_NET_WM_WINDOW_TYPE_DOCK`, `_NET_WM_STRUT_PARTIAL`, `_NET_WORKAREA`), per-tag/grid layouts (`[]=`, `[M]`, `><>`, `###`), clickable bar regions, `Super_L` quick-tap support, `SIGHUP` live restart, and `SIGUSR1`/`XA_RESOURCE_MANAGER` live theme & DPI reload. + - **dmenu (`5.3-anode`)**: Pango/HarfBuzz rendering, fuzzy matching, touch/pointer navigation, XFixes/XI2 pointer auto-hiding, dynamic `.Xresources` & fractional scale sizing. + - **st (`0.9.2-anode`)**: HarfBuzz programming ligatures (`Fira Code`), dirty-cell rendering cache, focus-gated cursor blink, `.Xresources` + `SIGUSR1` live reload, portable Linux/BSD PTY handling. +- **Unified `.xth` Theme & Fractional DPI Scaling Engine**: + - 22 normalized 96-DPI `.xth` themes (`data/themes/*.xth`) centered on `Fira Code` with ligatures. + - `anode-apply-scale` & `anode-apply-theme` synchronize `.Xresources`, `xrdb`, `dwm`, `dmenu`, `st`, `libgemui`, `anode-vkbd`, `dunst`, GTK-2, GTK-3, GTK-4 / `libadwaita`, `xsettingsd`, Qt5 (`qt5ct`), Qt6 (`qt6ct`), Kvantum, and Tk (`gtkTtk`) without double-scaling. +- **GemUI Toolkit (`libgemui`) & Desktop Utilities**: + - `anode-net`: Wi-Fi (`nmcli` / `wpa_cli` / BSD `ifconfig`), POSIX `getifaddrs` interfaces, Bluetooth (`bluetoothctl`), and DNS presets/custom nameservers (`anode-dnsctl`). + - `anode-audio`: PipeWire (`wpctl`), PulseAudio (`pactl`), ALSA (`amixer`), OpenBSD `sndioctl`, and OSS audio mixer & profile/stream control. + - `anode-display`: Native `libXrandr` output/mode/rotation control, brightness slider, fractional scale selector (`0.50x–4.00x` + `Auto EDID`), and touch-mode toggle. + - `anode-datetime`: Live clock, NTP status (`chronyc`/`timedatectl`), IANA timezone search & setter (`anode-tzctl`). + - `anode-power`: Battery/AC telemetry (Linux sysfs, FreeBSD `sysctl`, OpenBSD `apm`), brightness & volume sliders, power profiles, utility launcher grid, and Lock / Suspend / Hibernate / Reboot / Power Off actions (`anode-power-ctl`). + - `anode-themes`: Interactive `.xth` theme switcher with live color swatches and `Fira Code` ligature preview. + - `anode-lock`: Fullscreen X11 screen locker with `anode-checkpw` (`shadow.h` / BSD `getpwnam`). + - `anode-media-key`: Multimedia key dispatcher for volume, mic mute, brightness, MPRIS/MPD/mpv media playback, screenshots, airplane toggle, suspend, and virtual keyboard toggling. + - `anode-vkbd`: Optional EWMH dock multi-layer touch virtual keyboard (`QWERTY`, `Shift`, `Sym`, `Nav`) injecting XTest keystrokes without stealing focus. +- **Zero-Poll Event Daemons**: + - `anode-statusd`: `poll()` + self-pipe + Linux `NETLINK_ROUTE` / BSD `PF_ROUTE` link watcher + minute-aligned timer. + - `anode-touchd`: XI2 multitouch edge-swipe gesture recognizer. + - `anode-powerd`: Idle dim / lock / suspend policy daemon (`XScreenSaverQueryInfo` when available). +- **gtkTtk 0.9 Port**: + - Native GTK2-backed Ttk/Tkinter widget theme with full `[0.5, 4.0]` fractional DPI scaling and BSD library paths. + +## Dependencies + +- **Build-time**: POSIX `make`, C11/C99 compiler (`cc`), `pkg-config`, X11 development headers (`x11`, `xext`, `xft`, `xinerama`, `xrandr`, `xfixes`, `xi`, `xtst`, optionally `xscrnsaver`), `fontconfig`, `freetype2`, `harfbuzz`, `cairo`, `pango`, `pangoxft`, `pangocairo`, and `libcrypt` (`-lcrypt` where separate). Optional for `gtkTtk`: C++ compiler, `gtk+-2.0`, `tcl`, `tk`, and Tk private `ttkTheme.h`. +- **Runtime (optional tools auto-detected)**: `xrdb`, `xrandr`, `xsettingsd`, `dunst`, `notify-send`, `scrot`/`import`/`maim`, `wpctl`/`pactl`/`amixer`/`sndioctl`, `nmcli`/`wpa_cli`, `bluetoothctl`, `playerctl`/`mpc`, `chronyc`, `doas`/`sudo`/`pkexec`, and **Fira Code** + **DejaVuSansM Nerd Font**. + +## Build & Install + +```sh +# Build all core targets (uses WITH_GTKTTK=auto by default) +make + +# Optional overrides: +make PREFIX=/opt/anode CC=clang WITH_GTKTTK=1 +make DESTDIR=/tmp/stage PREFIX=/usr/local install +``` + +Start ANODE from `.xinitrc` (`exec /usr/local/bin/anode-session`) or via a display manager selecting the installed `ANODE` XSession (`PREFIX/share/xsessions/anode.desktop`). + +## Documentation & Tests + +- [Architecture](docs/ARCHITECTURE.md) +- [Keybindings](docs/KEYBINDINGS.md) + +Run verification suite (requires Python 3 and `Xvfb` for X11 integration checks): + +```sh +make test +``` diff --git a/data/anode.desktop b/data/anode.desktop new file mode 100644 index 0000000..32c5788 --- /dev/null +++ b/data/anode.desktop @@ -0,0 +1,7 @@ +[Desktop Entry] +Name=ANODE +Comment=A Nicely Optimized Desktop Environment +Exec=@PREFIX@/bin/anode-session +TryExec=@PREFIX@/bin/anode-session +Type=Application +DesktopNames=ANODE diff --git a/data/env.sh b/data/env.sh new file mode 100755 index 0000000..166095c --- /dev/null +++ b/data/env.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# ANODE Desktop Environment session variables (POSIX sh compatible) + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +: "${XDG_DATA_HOME:=$HOME/.local/share}" +: "${XDG_CACHE_HOME:=$HOME/.cache}" +: "${XDG_STATE_HOME:=$HOME/.local/state}" +: "${ANODE_PREFIX:=/usr/local}" +export XDG_CONFIG_HOME XDG_DATA_HOME XDG_CACHE_HOME XDG_STATE_HOME ANODE_PREFIX + +# Load active scale settings generated by anode-apply-scale +if [ -f "$XDG_CONFIG_HOME/anode/scale.env" ]; then + . "$XDG_CONFIG_HOME/anode/scale.env" +fi + +# Non-double-scaling multi-toolkit defaults +: "${ANODE_SCALE:=1.00}" +: "${ANODE_TOUCH:=0}" +: "${GDK_SCALE:=1}" +: "${GDK_DPI_SCALE:=1.0}" +: "${ADW_DISABLE_PORTAL:=1}" +: "${QT_QPA_PLATFORMTHEME:=qt6ct:qt5ct:gtk3}" +: "${QT_AUTO_SCREEN_SCALE_FACTOR:=0}" +: "${QT_ENABLE_HIGHDPI_SCALING:=1}" +: "${QT_SCALE_FACTOR_ROUNDING_POLICY:=PassThrough}" +: "${QT_SCALE_FACTOR:=$ANODE_SCALE}" +: "${QT_FONT_DPI:=96}" +: "${GTK_USE_PORTAL:=0}" +export ANODE_SCALE ANODE_TOUCH GDK_SCALE GDK_DPI_SCALE ADW_DISABLE_PORTAL \ + QT_QPA_PLATFORMTHEME QT_AUTO_SCREEN_SCALE_FACTOR QT_ENABLE_HIGHDPI_SCALING \ + QT_SCALE_FACTOR_ROUNDING_POLICY QT_SCALE_FACTOR QT_FONT_DPI GTK_USE_PORTAL + +if [ -d "$XDG_CONFIG_HOME/anode/themes" ]; then + export GTK2_RC_FILES="${GTK2_RC_FILES:-$HOME/.gtkrc-2.0}" +fi + +# Expose gtkTtk 0.9 to Tcl/Tk and Python Tkinter applications +for _ttkdir in \ + "$ANODE_PREFIX/lib/gtkTtk0.9" \ + "/usr/local/lib/gtkTtk0.9" \ + "/usr/lib/gtkTtk0.9" \ + "/usr/lib64/gtkTtk0.9" \ + "/usr/pkg/lib/gtkTtk0.9" +do + if [ -d "$_ttkdir" ]; then + case " ${TCLLIBPATH:-} " in + *" $_ttkdir "*) ;; + *) TCLLIBPATH="$_ttkdir${TCLLIBPATH:+ $TCLLIBPATH}" ;; + esac + fi +done +export TCLLIBPATH +unset _ttkdir + +case ":$PATH:" in + *":$ANODE_PREFIX/bin:"*) ;; + *) PATH="$ANODE_PREFIX/bin:$PATH" ;; +esac +export PATH diff --git a/data/themes/AnodeDefault.xth b/data/themes/AnodeDefault.xth new file mode 100644 index 0000000..b3b88c4 --- /dev/null +++ b/data/themes/AnodeDefault.xth @@ -0,0 +1,86 @@ +! 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.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:pixelsize=15: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/CatppuccinLatte.xth b/data/themes/CatppuccinLatte.xth new file mode 100644 index 0000000..286ac23 --- /dev/null +++ b/data/themes/CatppuccinLatte.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: CatppuccinLatte + +theme.name: CatppuccinLatte +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #eff1f5 +theme.bgBar: #eff1f5 +theme.bgHeader: #e6e9ef +theme.bgFooter: #dce0e8 +theme.bgOverlay: #d5d9e2 +theme.bgAltEven: #e9ecf1 +theme.bgAltOdd: #e2e5ec +theme.bgInput: #ffffff +theme.bgInputFocus: #d2d9f7 +theme.bgButton: #e4e7ee +theme.bgSearch: #ccd0da +theme.bgBubbleIn: #dcebd8 +theme.bgBubbleOut: #d6dcf5 +theme.bgToast: #3b4880 + +theme.fgMain: #4c4f69 +theme.fgBright: #1e1e2e +theme.fgMuted: #7c7f93 + +theme.selBg: #7287fd +theme.selFg: #ffffff +theme.accent: #8839ef +theme.accentAlt: #1e66f5 +theme.highlight: #df8e1d +theme.border: #bcc0cc +theme.divider: #9ca0b0 + +theme.success: #40a02b +theme.info: #04a5e5 +theme.warning: #fe640b +theme.danger: #d20f39 +theme.dangerBg: #9e0b2b + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #e6e9ef +dmenu.foreground: #1e1e2e +dmenu.selbackground: #7287fd +dmenu.selforeground: #ffffff +dmenu.outbackground: #ccd0da +dmenu.outforeground: #1e1e2e +dmenu.highlight: #df8e1d + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #eff1f5 +dwm.foreground: #4c4f69 +dwm.border: #bcc0cc +dwm.selbackground: #7287fd +dwm.selforeground: #ffffff +dwm.selborder: #7287fd +dwm.normbgcolor: #eff1f5 +dwm.normbordercolor: #bcc0cc +dwm.normfgcolor: #4c4f69 +dwm.selbgcolor: #7287fd +dwm.selbordercolor: #7287fd +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #e6e9ef +st.foreground: #4c4f69 +st.cursorColor: #8839ef +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/CatppuccinMocha.xth b/data/themes/CatppuccinMocha.xth new file mode 100644 index 0000000..3961796 --- /dev/null +++ b/data/themes/CatppuccinMocha.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: CatppuccinMocha + +theme.name: CatppuccinMocha +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #1e1e2e +theme.bgBar: #1e1e2e +theme.bgHeader: #181825 +theme.bgFooter: #11111b +theme.bgOverlay: #11111b +theme.bgAltEven: #242538 +theme.bgAltOdd: #2a2b40 +theme.bgInput: #181825 +theme.bgInputFocus: #43335e +theme.bgButton: #292a3d +theme.bgSearch: #3b3c54 +theme.bgBubbleIn: #243330 +theme.bgBubbleOut: #332847 +theme.bgToast: #2b223d + +theme.fgMain: #cdd6f4 +theme.fgBright: #ffffff +theme.fgMuted: #7f849c + +theme.selBg: #724b9e +theme.selFg: #ffffff +theme.accent: #cba6f7 +theme.accentAlt: #89b4fa +theme.highlight: #f9e2af +theme.border: #45475a +theme.divider: #6c7086 + +theme.success: #a6e3a1 +theme.info: #89dceb +theme.warning: #fab387 +theme.danger: #f38ba8 +theme.dangerBg: #873951 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #181825 +dmenu.foreground: #ffffff +dmenu.selbackground: #724b9e +dmenu.selforeground: #ffffff +dmenu.outbackground: #3b3c54 +dmenu.outforeground: #ffffff +dmenu.highlight: #f9e2af + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #1e1e2e +dwm.foreground: #cdd6f4 +dwm.border: #45475a +dwm.selbackground: #724b9e +dwm.selforeground: #ffffff +dwm.selborder: #724b9e +dwm.normbgcolor: #1e1e2e +dwm.normbordercolor: #45475a +dwm.normfgcolor: #cdd6f4 +dwm.selbgcolor: #724b9e +dwm.selbordercolor: #724b9e +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #181825 +st.foreground: #cdd6f4 +st.cursorColor: #cba6f7 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/Cyberpunk.xth b/data/themes/Cyberpunk.xth new file mode 100644 index 0000000..7d7ef72 --- /dev/null +++ b/data/themes/Cyberpunk.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: Cyberpunk + +theme.name: Cyberpunk +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #000000 +theme.bgBar: #000000 +theme.bgHeader: #000000 +theme.bgFooter: #000000 +theme.bgOverlay: #000000 +theme.bgAltEven: #050a10 +theme.bgAltOdd: #09121c +theme.bgInput: #000000 +theme.bgInputFocus: #002b4d +theme.bgButton: #08121e +theme.bgSearch: #0d1f33 +theme.bgBubbleIn: #00241a +theme.bgBubbleOut: #002240 +theme.bgToast: #001d36 + +theme.fgMain: #e0f7ff +theme.fgBright: #ffffff +theme.fgMuted: #4d88a8 + +theme.selBg: #0066cc +theme.selFg: #ffffff +theme.accent: #00f0ff +theme.accentAlt: #0088ff +theme.highlight: #fcee0a +theme.border: #004477 +theme.divider: #006699 + +theme.success: #00ff9f +theme.info: #00f0ff +theme.warning: #fcee0a +theme.danger: #ff0055 +theme.dangerBg: #8a002e + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #000000 +dmenu.foreground: #ffffff +dmenu.selbackground: #0066cc +dmenu.selforeground: #ffffff +dmenu.outbackground: #0d1f33 +dmenu.outforeground: #ffffff +dmenu.highlight: #fcee0a + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #000000 +dwm.foreground: #e0f7ff +dwm.border: #004477 +dwm.selbackground: #0066cc +dwm.selforeground: #ffffff +dwm.selborder: #0066cc +dwm.normbgcolor: #000000 +dwm.normbordercolor: #004477 +dwm.normfgcolor: #e0f7ff +dwm.selbgcolor: #0066cc +dwm.selbordercolor: #0066cc +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #000000 +st.foreground: #e0f7ff +st.cursorColor: #00f0ff +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/Default.xth b/data/themes/Default.xth new file mode 100644 index 0000000..b43ed17 --- /dev/null +++ b/data/themes/Default.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: Default + +theme.name: Default +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #222222 +theme.bgBar: #222222 +theme.bgHeader: #1c1c1c +theme.bgFooter: #181818 +theme.bgOverlay: #161616 +theme.bgAltEven: #282828 +theme.bgAltOdd: #2e2e2e +theme.bgInput: #1a1a1a +theme.bgInputFocus: #1b3b4b +theme.bgButton: #2a2a2a +theme.bgSearch: #383838 +theme.bgBubbleIn: #262d32 +theme.bgBubbleOut: #1f2d38 +theme.bgToast: #102535 + +theme.fgMain: #dddddd +theme.fgBright: #ffffff +theme.fgMuted: #999999 + +theme.selBg: #005577 +theme.selFg: #ffffff +theme.accent: #f4d03f +theme.accentAlt: #0088bb +theme.highlight: #ffc978 +theme.border: #444444 +theme.divider: #666666 + +theme.success: #2ecc71 +theme.info: #5dade2 +theme.warning: #e67e22 +theme.danger: #e74c3c +theme.dangerBg: #922b21 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #1c1c1c +dmenu.foreground: #ffffff +dmenu.selbackground: #005577 +dmenu.selforeground: #ffffff +dmenu.outbackground: #383838 +dmenu.outforeground: #ffffff +dmenu.highlight: #ffc978 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #222222 +dwm.foreground: #dddddd +dwm.border: #444444 +dwm.selbackground: #005577 +dwm.selforeground: #ffffff +dwm.selborder: #005577 +dwm.normbgcolor: #222222 +dwm.normbordercolor: #444444 +dwm.normfgcolor: #dddddd +dwm.selbgcolor: #005577 +dwm.selbordercolor: #005577 +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #1c1c1c +st.foreground: #dddddd +st.cursorColor: #f4d03f +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/Dracula.xth b/data/themes/Dracula.xth new file mode 100644 index 0000000..96966c6 --- /dev/null +++ b/data/themes/Dracula.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: Dracula + +theme.name: Dracula +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #282a36 +theme.bgBar: #282a36 +theme.bgHeader: #21222c +theme.bgFooter: #1c1d26 +theme.bgOverlay: #191a21 +theme.bgAltEven: #2e303e +theme.bgAltOdd: #343746 +theme.bgInput: #21222c +theme.bgInputFocus: #3f476b +theme.bgButton: #313442 +theme.bgSearch: #44475a +theme.bgBubbleIn: #283b36 +theme.bgBubbleOut: #343952 +theme.bgToast: #2f354d + +theme.fgMain: #f8f8f2 +theme.fgBright: #ffffff +theme.fgMuted: #6272a4 + +theme.selBg: #6272a4 +theme.selFg: #f8f8f2 +theme.accent: #bd93f9 +theme.accentAlt: #ff79c6 +theme.highlight: #f1fa8c +theme.border: #44475a +theme.divider: #6272a4 + +theme.success: #50fa7b +theme.info: #8be9fd +theme.warning: #ffb86c +theme.danger: #ff5555 +theme.dangerBg: #8f2828 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #21222c +dmenu.foreground: #ffffff +dmenu.selbackground: #6272a4 +dmenu.selforeground: #f8f8f2 +dmenu.outbackground: #44475a +dmenu.outforeground: #ffffff +dmenu.highlight: #f1fa8c + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #282a36 +dwm.foreground: #f8f8f2 +dwm.border: #44475a +dwm.selbackground: #6272a4 +dwm.selforeground: #f8f8f2 +dwm.selborder: #6272a4 +dwm.normbgcolor: #282a36 +dwm.normbordercolor: #44475a +dwm.normfgcolor: #f8f8f2 +dwm.selbgcolor: #6272a4 +dwm.selbordercolor: #6272a4 +dwm.selfgcolor: #f8f8f2 +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #21222c +st.foreground: #f8f8f2 +st.cursorColor: #bd93f9 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/EverforestDark.xth b/data/themes/EverforestDark.xth new file mode 100644 index 0000000..0fa544e --- /dev/null +++ b/data/themes/EverforestDark.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: EverforestDark + +theme.name: EverforestDark +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #2d353b +theme.bgBar: #2d353b +theme.bgHeader: #232a2e +theme.bgFooter: #1e2428 +theme.bgOverlay: #1b2024 +theme.bgAltEven: #323b41 +theme.bgAltOdd: #374248 +theme.bgInput: #232a2e +theme.bgInputFocus: #384d3c +theme.bgButton: #343f44 +theme.bgSearch: #475258 +theme.bgBubbleIn: #324236 +theme.bgBubbleOut: #34453a +theme.bgToast: #2d4034 + +theme.fgMain: #d3c6aa +theme.fgBright: #fdf6e3 +theme.fgMuted: #859289 + +theme.selBg: #426348 +theme.selFg: #fdf6e3 +theme.accent: #a7c080 +theme.accentAlt: #7fbbb3 +theme.highlight: #dbbc7f +theme.border: #475258 +theme.divider: #56635f + +theme.success: #a7c080 +theme.info: #7fbbb3 +theme.warning: #e69875 +theme.danger: #e67e80 +theme.dangerBg: #82383a + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #232a2e +dmenu.foreground: #fdf6e3 +dmenu.selbackground: #426348 +dmenu.selforeground: #fdf6e3 +dmenu.outbackground: #475258 +dmenu.outforeground: #fdf6e3 +dmenu.highlight: #dbbc7f + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #2d353b +dwm.foreground: #d3c6aa +dwm.border: #475258 +dwm.selbackground: #426348 +dwm.selforeground: #fdf6e3 +dwm.selborder: #426348 +dwm.normbgcolor: #2d353b +dwm.normbordercolor: #475258 +dwm.normfgcolor: #d3c6aa +dwm.selbgcolor: #426348 +dwm.selbordercolor: #426348 +dwm.selfgcolor: #fdf6e3 +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #232a2e +st.foreground: #d3c6aa +st.cursorColor: #a7c080 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/GeminuxHelio.xth b/data/themes/GeminuxHelio.xth new file mode 100644 index 0000000..8d0b25f --- /dev/null +++ b/data/themes/GeminuxHelio.xth @@ -0,0 +1,73 @@ +! ANODE Unified Theme: ANODEHelio +theme.name: GeminuxHelio +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #0f1419 +theme.bgBar: #0b0e14 +theme.bgHeader: #131922 +theme.bgFooter: #0b0e14 +theme.bgOverlay: #161d26 +theme.bgAltEven: #121820 +theme.bgAltOdd: #18202a +theme.bgInput: #0b0e14 +theme.bgInputFocus: #1b2838 +theme.bgButton: #1d2633 +theme.bgSearch: #243040 +theme.bgBubbleIn: #1b2632 +theme.bgBubbleOut: #1c3244 +theme.bgToast: #132230 + +theme.fgMain: #e6e1cf +theme.fgBright: #ffffff +theme.fgMuted: #7b8898 + +theme.selBg: #2b5278 +theme.selFg: #ffffff +theme.accent: #59c2ff +theme.accentAlt: #ffb454 +theme.highlight: #ff8f40 +theme.border: #283444 +theme.divider: #364559 + +theme.success: #7fd962 +theme.info: #59c2ff +theme.warning: #ffb454 +theme.danger: #f07178 +theme.dangerBg: #4c1d24 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #0b0e14 +dmenu.foreground: #e6e1cf +dmenu.selbackground: #2b5278 +dmenu.selforeground: #ffffff +dmenu.outbackground: #243040 +dmenu.outforeground: #ffffff +dmenu.highlight: #ffb454 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #0b0e14 +dwm.foreground: #e6e1cf +dwm.border: #283444 +dwm.selbackground: #2b5278 +dwm.selforeground: #ffffff +dwm.selborder: #59c2ff +dwm.normbgcolor: #0b0e14 +dwm.normbordercolor: #283444 +dwm.normfgcolor: #e6e1cf +dwm.selbgcolor: #2b5278 +dwm.selbordercolor: #59c2ff +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #0f1419 +st.foreground: #e6e1cf +st.cursorColor: #59c2ff + +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/GitHubDark.xth b/data/themes/GitHubDark.xth new file mode 100644 index 0000000..825238c --- /dev/null +++ b/data/themes/GitHubDark.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: GitHubDark + +theme.name: GitHubDark +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #0d1117 +theme.bgBar: #0d1117 +theme.bgHeader: #090c10 +theme.bgFooter: #06090c +theme.bgOverlay: #05070a +theme.bgAltEven: #12171f +theme.bgAltOdd: #161b22 +theme.bgInput: #090d11 +theme.bgInputFocus: #122d52 +theme.bgButton: #161b22 +theme.bgSearch: #21262d +theme.bgBubbleIn: #11261e +theme.bgBubbleOut: #11243d +theme.bgToast: #0f233d + +theme.fgMain: #c9d1d9 +theme.fgBright: #f0f6fc +theme.fgMuted: #8b949e + +theme.selBg: #1f6feb +theme.selFg: #ffffff +theme.accent: #58a6ff +theme.accentAlt: #3fb950 +theme.highlight: #e3b341 +theme.border: #30363d +theme.divider: #484f58 + +theme.success: #3fb950 +theme.info: #58a6ff +theme.warning: #d29922 +theme.danger: #f85149 +theme.dangerBg: #8e2520 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #090c10 +dmenu.foreground: #f0f6fc +dmenu.selbackground: #1f6feb +dmenu.selforeground: #ffffff +dmenu.outbackground: #21262d +dmenu.outforeground: #f0f6fc +dmenu.highlight: #e3b341 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #0d1117 +dwm.foreground: #c9d1d9 +dwm.border: #30363d +dwm.selbackground: #1f6feb +dwm.selforeground: #ffffff +dwm.selborder: #1f6feb +dwm.normbgcolor: #0d1117 +dwm.normbordercolor: #30363d +dwm.normfgcolor: #c9d1d9 +dwm.selbgcolor: #1f6feb +dwm.selbordercolor: #1f6feb +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #090c10 +st.foreground: #c9d1d9 +st.cursorColor: #58a6ff +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/GruvboxDark.xth b/data/themes/GruvboxDark.xth new file mode 100644 index 0000000..c533fc3 --- /dev/null +++ b/data/themes/GruvboxDark.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: GruvboxDark + +theme.name: GruvboxDark +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #282828 +theme.bgBar: #282828 +theme.bgHeader: #1d2021 +theme.bgFooter: #181a1b +theme.bgOverlay: #141617 +theme.bgAltEven: #2e2c2b +theme.bgAltOdd: #353230 +theme.bgInput: #1d2021 +theme.bgInputFocus: #5c3f14 +theme.bgButton: #32302f +theme.bgSearch: #504945 +theme.bgBubbleIn: #333824 +theme.bgBubbleOut: #45341c +theme.bgToast: #3d2e18 + +theme.fgMain: #ebdbb2 +theme.fgBright: #fbf1c7 +theme.fgMuted: #928374 + +theme.selBg: #b57614 +theme.selFg: #fbf1c7 +theme.accent: #fabd2f +theme.accentAlt: #83a598 +theme.highlight: #fe8019 +theme.border: #504945 +theme.divider: #665c54 + +theme.success: #b8bb26 +theme.info: #83a598 +theme.warning: #fe8019 +theme.danger: #fb4934 +theme.dangerBg: #9d0006 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #1d2021 +dmenu.foreground: #fbf1c7 +dmenu.selbackground: #b57614 +dmenu.selforeground: #fbf1c7 +dmenu.outbackground: #504945 +dmenu.outforeground: #fbf1c7 +dmenu.highlight: #fe8019 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #282828 +dwm.foreground: #ebdbb2 +dwm.border: #504945 +dwm.selbackground: #b57614 +dwm.selforeground: #fbf1c7 +dwm.selborder: #b57614 +dwm.normbgcolor: #282828 +dwm.normbordercolor: #504945 +dwm.normfgcolor: #ebdbb2 +dwm.selbgcolor: #b57614 +dwm.selbordercolor: #b57614 +dwm.selfgcolor: #fbf1c7 +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #1d2021 +st.foreground: #ebdbb2 +st.cursorColor: #fabd2f +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/GruvboxLight.xth b/data/themes/GruvboxLight.xth new file mode 100644 index 0000000..34b49e2 --- /dev/null +++ b/data/themes/GruvboxLight.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: GruvboxLight + +theme.name: GruvboxLight +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #fbf1c7 +theme.bgBar: #fbf1c7 +theme.bgHeader: #f2e5bc +theme.bgFooter: #e8d8ab +theme.bgOverlay: #e2d1a2 +theme.bgAltEven: #f5e9be +theme.bgAltOdd: #ede0b5 +theme.bgInput: #fff9de +theme.bgInputFocus: #e6cba1 +theme.bgButton: #ede0b4 +theme.bgSearch: #d5c4a1 +theme.bgBubbleIn: #e2e6b8 +theme.bgBubbleOut: #ebd5b3 +theme.bgToast: #593b10 + +theme.fgMain: #3c3836 +theme.fgBright: #1d2021 +theme.fgMuted: #7c6f64 + +theme.selBg: #b57614 +theme.selFg: #fbf1c7 +theme.accent: #af3a03 +theme.accentAlt: #076678 +theme.highlight: #d65d0e +theme.border: #d5c4a1 +theme.divider: #bdae93 + +theme.success: #79740e +theme.info: #076678 +theme.warning: #b57614 +theme.danger: #9d0006 +theme.dangerBg: #790004 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #f2e5bc +dmenu.foreground: #1d2021 +dmenu.selbackground: #b57614 +dmenu.selforeground: #fbf1c7 +dmenu.outbackground: #d5c4a1 +dmenu.outforeground: #1d2021 +dmenu.highlight: #d65d0e + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #fbf1c7 +dwm.foreground: #3c3836 +dwm.border: #d5c4a1 +dwm.selbackground: #b57614 +dwm.selforeground: #fbf1c7 +dwm.selborder: #b57614 +dwm.normbgcolor: #fbf1c7 +dwm.normbordercolor: #d5c4a1 +dwm.normfgcolor: #3c3836 +dwm.selbgcolor: #b57614 +dwm.selbordercolor: #b57614 +dwm.selfgcolor: #fbf1c7 +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #f2e5bc +st.foreground: #3c3836 +st.cursorColor: #af3a03 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/Kanagawa.xth b/data/themes/Kanagawa.xth new file mode 100644 index 0000000..12bfcb7 --- /dev/null +++ b/data/themes/Kanagawa.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: Kanagawa + +theme.name: Kanagawa +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #1f1f28 +theme.bgBar: #1f1f28 +theme.bgHeader: #16161d +theme.bgFooter: #13131a +theme.bgOverlay: #111117 +theme.bgAltEven: #252530 +theme.bgAltOdd: #2a2a37 +theme.bgInput: #181820 +theme.bgInputFocus: #25394b +theme.bgButton: #272733 +theme.bgSearch: #363646 +theme.bgBubbleIn: #232e28 +theme.bgBubbleOut: #22303f +theme.bgToast: #1d2b3a + +theme.fgMain: #dcd7ba +theme.fgBright: #ffffff +theme.fgMuted: #727169 + +theme.selBg: #2d4f67 +theme.selFg: #dcd7ba +theme.accent: #e6c384 +theme.accentAlt: #7e9cd8 +theme.highlight: #ffa066 +theme.border: #363646 +theme.divider: #54546d + +theme.success: #98bb6c +theme.info: #7fb4ca +theme.warning: #ff9e3b +theme.danger: #e82424 +theme.dangerBg: #821414 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #16161d +dmenu.foreground: #ffffff +dmenu.selbackground: #2d4f67 +dmenu.selforeground: #dcd7ba +dmenu.outbackground: #363646 +dmenu.outforeground: #ffffff +dmenu.highlight: #ffa066 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #1f1f28 +dwm.foreground: #dcd7ba +dwm.border: #363646 +dwm.selbackground: #2d4f67 +dwm.selforeground: #dcd7ba +dwm.selborder: #2d4f67 +dwm.normbgcolor: #1f1f28 +dwm.normbordercolor: #363646 +dwm.normfgcolor: #dcd7ba +dwm.selbgcolor: #2d4f67 +dwm.selbordercolor: #2d4f67 +dwm.selfgcolor: #dcd7ba +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #16161d +st.foreground: #dcd7ba +st.cursorColor: #e6c384 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/LinuxConsole.xth b/data/themes/LinuxConsole.xth new file mode 100644 index 0000000..16dd0e0 --- /dev/null +++ b/data/themes/LinuxConsole.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: LinuxConsole + +theme.name: LinuxConsole +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #000000 +theme.bgBar: #000000 +theme.bgHeader: #000000 +theme.bgFooter: #080808 +theme.bgOverlay: #050505 +theme.bgAltEven: #0a0a0a +theme.bgAltOdd: #121212 +theme.bgInput: #050505 +theme.bgInputFocus: #002b55 +theme.bgButton: #141414 +theme.bgSearch: #1f1f1f +theme.bgBubbleIn: #0a240a +theme.bgBubbleOut: #001f3f +theme.bgToast: #001a33 + +theme.fgMain: #aaaaaa +theme.fgBright: #ffffff +theme.fgMuted: #686868 + +theme.selBg: #0055aa +theme.selFg: #ffffff +theme.accent: #55ff55 +theme.accentAlt: #55ffff +theme.highlight: #ffff55 +theme.border: #333333 +theme.divider: #555555 + +theme.success: #55ff55 +theme.info: #55ffff +theme.warning: #ffff55 +theme.danger: #ff5555 +theme.dangerBg: #880000 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #000000 +dmenu.foreground: #ffffff +dmenu.selbackground: #0055aa +dmenu.selforeground: #ffffff +dmenu.outbackground: #1f1f1f +dmenu.outforeground: #ffffff +dmenu.highlight: #ffff55 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #000000 +dwm.foreground: #aaaaaa +dwm.border: #333333 +dwm.selbackground: #0055aa +dwm.selforeground: #ffffff +dwm.selborder: #0055aa +dwm.normbgcolor: #000000 +dwm.normbordercolor: #333333 +dwm.normfgcolor: #aaaaaa +dwm.selbgcolor: #0055aa +dwm.selbordercolor: #0055aa +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #000000 +st.foreground: #aaaaaa +st.cursorColor: #55ff55 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/LynxLair.xth b/data/themes/LynxLair.xth new file mode 100644 index 0000000..b932906 --- /dev/null +++ b/data/themes/LynxLair.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: LynxLair + +theme.name: LynxLair +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #000000 +theme.bgBar: #000000 +theme.bgHeader: #000000 +theme.bgFooter: #000000 +theme.bgOverlay: #000000 +theme.bgAltEven: #080705 +theme.bgAltOdd: #121212 +theme.bgInput: #000000 +theme.bgInputFocus: #4d3008 +theme.bgButton: #121212 +theme.bgSearch: #2b1c07 +theme.bgBubbleIn: #0f211f +theme.bgBubbleOut: #382308 +theme.bgToast: #2e1d06 + +theme.fgMain: #efe5c0 +theme.fgBright: #fff8dc +theme.fgMuted: #a89984 + +theme.selBg: #9e6210 +theme.selFg: #fff8dc +theme.accent: #e0a044 +theme.accentAlt: #ffb84d +theme.highlight: #e3dc82 +theme.border: #5c3b0c +theme.divider: #9e6210 + +theme.success: #00d67d +theme.info: #588883 +theme.warning: #e0a044 +theme.danger: #d62828 +theme.dangerBg: #5f0f1e + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #000000 +dmenu.foreground: #efe5c0 +dmenu.selbackground: #9e6210 +dmenu.selforeground: #fff8dc +dmenu.outbackground: #4d3008 +dmenu.outforeground: #fff8dc +dmenu.highlight: #ffb84d + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #000000 +dwm.foreground: #efe5c0 +dwm.border: #5c3b0c +dwm.selbackground: #9e6210 +dwm.selforeground: #fff8dc +dwm.selborder: #e0a044 +dwm.normbgcolor: #000000 +dwm.normbordercolor: #5c3b0c +dwm.normfgcolor: #efe5c0 +dwm.selbgcolor: #9e6210 +dwm.selbordercolor: #e0a044 +dwm.selfgcolor: #fff8dc +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #000000 +st.foreground: #efe5c0 +st.cursorColor: #e0a044 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/MatrixGreen.xth b/data/themes/MatrixGreen.xth new file mode 100644 index 0000000..4d6d70f --- /dev/null +++ b/data/themes/MatrixGreen.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: MatrixGreen + +theme.name: MatrixGreen +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #0a140c +theme.bgBar: #0a140c +theme.bgHeader: #070e08 +theme.bgFooter: #050b06 +theme.bgOverlay: #040905 +theme.bgAltEven: #0e1c11 +theme.bgAltOdd: #132416 +theme.bgInput: #071009 +theme.bgInputFocus: #143d1f +theme.bgButton: #102013 +theme.bgSearch: #18301c +theme.bgBubbleIn: #112b16 +theme.bgBubbleOut: #16381d +theme.bgToast: #0f3018 + +theme.fgMain: #a8ffb2 +theme.fgBright: #e0ffe4 +theme.fgMuted: #52995b + +theme.selBg: #196627 +theme.selFg: #ffffff +theme.accent: #00ff41 +theme.accentAlt: #2ecc71 +theme.highlight: #80ff9d +theme.border: #1e4224 +theme.divider: #2d6336 + +theme.success: #00ff41 +theme.info: #5dade2 +theme.warning: #f1c40f +theme.danger: #e74c3c +theme.dangerBg: #922b21 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #070e08 +dmenu.foreground: #e0ffe4 +dmenu.selbackground: #196627 +dmenu.selforeground: #ffffff +dmenu.outbackground: #18301c +dmenu.outforeground: #e0ffe4 +dmenu.highlight: #80ff9d + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #0a140c +dwm.foreground: #a8ffb2 +dwm.border: #1e4224 +dwm.selbackground: #196627 +dwm.selforeground: #ffffff +dwm.selborder: #196627 +dwm.normbgcolor: #0a140c +dwm.normbordercolor: #1e4224 +dwm.normfgcolor: #a8ffb2 +dwm.selbgcolor: #196627 +dwm.selbordercolor: #196627 +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #070e08 +st.foreground: #a8ffb2 +st.cursorColor: #00ff41 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/MonokaiPro.xth b/data/themes/MonokaiPro.xth new file mode 100644 index 0000000..56c4c43 --- /dev/null +++ b/data/themes/MonokaiPro.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: MonokaiPro + +theme.name: MonokaiPro +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #272822 +theme.bgBar: #272822 +theme.bgHeader: #1e1f1c +theme.bgFooter: #191a17 +theme.bgOverlay: #161714 +theme.bgAltEven: #2d2e27 +theme.bgAltOdd: #33342c +theme.bgInput: #1f201c +theme.bgInputFocus: #52253b +theme.bgButton: #31322b +theme.bgSearch: #414339 +theme.bgBubbleIn: #2c3624 +theme.bgBubbleOut: #402432 +theme.bgToast: #3b1f2e + +theme.fgMain: #f8f8f2 +theme.fgBright: #ffffff +theme.fgMuted: #90908a + +theme.selBg: #a61c52 +theme.selFg: #ffffff +theme.accent: #a6e22e +theme.accentAlt: #66d9ef +theme.highlight: #e6db74 +theme.border: #49483e +theme.divider: #75715e + +theme.success: #a6e22e +theme.info: #66d9ef +theme.warning: #fd971f +theme.danger: #f92672 +theme.dangerBg: #8a1540 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #1e1f1c +dmenu.foreground: #ffffff +dmenu.selbackground: #a61c52 +dmenu.selforeground: #ffffff +dmenu.outbackground: #414339 +dmenu.outforeground: #ffffff +dmenu.highlight: #e6db74 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #272822 +dwm.foreground: #f8f8f2 +dwm.border: #49483e +dwm.selbackground: #a61c52 +dwm.selforeground: #ffffff +dwm.selborder: #a61c52 +dwm.normbgcolor: #272822 +dwm.normbordercolor: #49483e +dwm.normfgcolor: #f8f8f2 +dwm.selbgcolor: #a61c52 +dwm.selbordercolor: #a61c52 +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #1e1f1c +st.foreground: #f8f8f2 +st.cursorColor: #a6e22e +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/NordFrost.xth b/data/themes/NordFrost.xth new file mode 100644 index 0000000..b969924 --- /dev/null +++ b/data/themes/NordFrost.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: NordFrost + +theme.name: NordFrost +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #2e3440 +theme.bgBar: #2e3440 +theme.bgHeader: #242933 +theme.bgFooter: #1f242d +theme.bgOverlay: #1d212a +theme.bgAltEven: #333a47 +theme.bgAltOdd: #39404f +theme.bgInput: #262b36 +theme.bgInputFocus: #394b68 +theme.bgButton: #363d4c +theme.bgSearch: #434c5e +theme.bgBubbleIn: #354249 +theme.bgBubbleOut: #344459 +theme.bgToast: #2b3c54 + +theme.fgMain: #e5e9f0 +theme.fgBright: #eceff4 +theme.fgMuted: #9099ab + +theme.selBg: #5e81ac +theme.selFg: #eceff4 +theme.accent: #88c0d0 +theme.accentAlt: #81a1c1 +theme.highlight: #ebcb8b +theme.border: #4c566a +theme.divider: #616e88 + +theme.success: #a3be8c +theme.info: #88c0d0 +theme.warning: #d08770 +theme.danger: #bf616a +theme.dangerBg: #7a373e + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #242933 +dmenu.foreground: #eceff4 +dmenu.selbackground: #5e81ac +dmenu.selforeground: #eceff4 +dmenu.outbackground: #434c5e +dmenu.outforeground: #eceff4 +dmenu.highlight: #ebcb8b + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #2e3440 +dwm.foreground: #e5e9f0 +dwm.border: #4c566a +dwm.selbackground: #5e81ac +dwm.selforeground: #eceff4 +dwm.selborder: #5e81ac +dwm.normbgcolor: #2e3440 +dwm.normbordercolor: #4c566a +dwm.normfgcolor: #e5e9f0 +dwm.selbgcolor: #5e81ac +dwm.selbordercolor: #5e81ac +dwm.selfgcolor: #eceff4 +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #242933 +st.foreground: #e5e9f0 +st.cursorColor: #88c0d0 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/OneDark.xth b/data/themes/OneDark.xth new file mode 100644 index 0000000..d786d4a --- /dev/null +++ b/data/themes/OneDark.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: OneDark + +theme.name: OneDark +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #282c34 +theme.bgBar: #282c34 +theme.bgHeader: #21252b +theme.bgFooter: #1b1f24 +theme.bgOverlay: #181a1f +theme.bgAltEven: #2c313a +theme.bgAltOdd: #323842 +theme.bgInput: #21252b +theme.bgInputFocus: #293d59 +theme.bgButton: #2f343e +theme.bgSearch: #3e4451 +theme.bgBubbleIn: #28362e +theme.bgBubbleOut: #253447 +theme.bgToast: #202f42 + +theme.fgMain: #abb2bf +theme.fgBright: #ffffff +theme.fgMuted: #5c6370 + +theme.selBg: #2c5380 +theme.selFg: #ffffff +theme.accent: #61afef +theme.accentAlt: #c678dd +theme.highlight: #e5c07b +theme.border: #3e4451 +theme.divider: #5c6370 + +theme.success: #98c379 +theme.info: #56b6c2 +theme.warning: #d19a66 +theme.danger: #e06c75 +theme.dangerBg: #823037 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #21252b +dmenu.foreground: #ffffff +dmenu.selbackground: #2c5380 +dmenu.selforeground: #ffffff +dmenu.outbackground: #3e4451 +dmenu.outforeground: #ffffff +dmenu.highlight: #e5c07b + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #282c34 +dwm.foreground: #abb2bf +dwm.border: #3e4451 +dwm.selbackground: #2c5380 +dwm.selforeground: #ffffff +dwm.selborder: #2c5380 +dwm.normbgcolor: #282c34 +dwm.normbordercolor: #3e4451 +dwm.normfgcolor: #abb2bf +dwm.selbgcolor: #2c5380 +dwm.selbordercolor: #2c5380 +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #21252b +st.foreground: #abb2bf +st.cursorColor: #61afef +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/RosePine.xth b/data/themes/RosePine.xth new file mode 100644 index 0000000..c70f93d --- /dev/null +++ b/data/themes/RosePine.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: RosePine + +theme.name: RosePine +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #191724 +theme.bgBar: #191724 +theme.bgHeader: #1f1d2e +theme.bgFooter: #14121d +theme.bgOverlay: #12101a +theme.bgAltEven: #1f1d2e +theme.bgAltOdd: #26233a +theme.bgInput: #15131f +theme.bgInputFocus: #3b2e52 +theme.bgButton: #232036 +theme.bgSearch: #332f4c +theme.bgBubbleIn: #1d2c36 +theme.bgBubbleOut: #2c2440 +theme.bgToast: #28203b + +theme.fgMain: #e0def4 +theme.fgBright: #ffffff +theme.fgMuted: #6e6a86 + +theme.selBg: #6e5694 +theme.selFg: #ffffff +theme.accent: #ebbcba +theme.accentAlt: #c4a7e7 +theme.highlight: #f6c177 +theme.border: #403d52 +theme.divider: #524f67 + +theme.success: #9ccfd8 +theme.info: #31748f +theme.warning: #f6c177 +theme.danger: #eb6f92 +theme.dangerBg: #852d47 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #1f1d2e +dmenu.foreground: #ffffff +dmenu.selbackground: #6e5694 +dmenu.selforeground: #ffffff +dmenu.outbackground: #332f4c +dmenu.outforeground: #ffffff +dmenu.highlight: #f6c177 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #191724 +dwm.foreground: #e0def4 +dwm.border: #403d52 +dwm.selbackground: #6e5694 +dwm.selforeground: #ffffff +dwm.selborder: #6e5694 +dwm.normbgcolor: #191724 +dwm.normbordercolor: #403d52 +dwm.normfgcolor: #e0def4 +dwm.selbgcolor: #6e5694 +dwm.selbordercolor: #6e5694 +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #1f1d2e +st.foreground: #e0def4 +st.cursorColor: #ebbcba +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/SolarizedDark.xth b/data/themes/SolarizedDark.xth new file mode 100644 index 0000000..da2a47e --- /dev/null +++ b/data/themes/SolarizedDark.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: SolarizedDark + +theme.name: SolarizedDark +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #002b36 +theme.bgBar: #002b36 +theme.bgHeader: #00212b +theme.bgFooter: #001b24 +theme.bgOverlay: #00171f +theme.bgAltEven: #04313d +theme.bgAltOdd: #083845 +theme.bgInput: #00232c +theme.bgInputFocus: #0d4a66 +theme.bgButton: #063541 +theme.bgSearch: #0d4352 +theme.bgBubbleIn: #0c3b38 +theme.bgBubbleOut: #093e54 +theme.bgToast: #083a52 + +theme.fgMain: #93a1a1 +theme.fgBright: #fdf6e3 +theme.fgMuted: #657b83 + +theme.selBg: #268bd2 +theme.selFg: #fdf6e3 +theme.accent: #b58900 +theme.accentAlt: #2aa198 +theme.highlight: #cb4b16 +theme.border: #164c5a +theme.divider: #586e75 + +theme.success: #859900 +theme.info: #268bd2 +theme.warning: #cb4b16 +theme.danger: #dc322f +theme.dangerBg: #801d1b + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #00212b +dmenu.foreground: #fdf6e3 +dmenu.selbackground: #268bd2 +dmenu.selforeground: #fdf6e3 +dmenu.outbackground: #0d4352 +dmenu.outforeground: #fdf6e3 +dmenu.highlight: #cb4b16 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #002b36 +dwm.foreground: #93a1a1 +dwm.border: #164c5a +dwm.selbackground: #268bd2 +dwm.selforeground: #fdf6e3 +dwm.selborder: #268bd2 +dwm.normbgcolor: #002b36 +dwm.normbordercolor: #164c5a +dwm.normfgcolor: #93a1a1 +dwm.selbgcolor: #268bd2 +dwm.selbordercolor: #268bd2 +dwm.selfgcolor: #fdf6e3 +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #00212b +st.foreground: #93a1a1 +st.cursorColor: #b58900 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/SolarizedLight.xth b/data/themes/SolarizedLight.xth new file mode 100644 index 0000000..2fafb5a --- /dev/null +++ b/data/themes/SolarizedLight.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: SolarizedLight + +theme.name: SolarizedLight +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #fdf6e3 +theme.bgBar: #fdf6e3 +theme.bgHeader: #e6dfca +theme.bgFooter: #e0d9c3 +theme.bgOverlay: #ddd6c1 +theme.bgAltEven: #f7f0dd +theme.bgAltOdd: #efe8d5 +theme.bgInput: #ffffff +theme.bgInputFocus: #d5e5f2 +theme.bgButton: #e8e1cc +theme.bgSearch: #d9d2bd +theme.bgBubbleIn: #e3f0d8 +theme.bgBubbleOut: #d5e6f5 +theme.bgToast: #1b4f72 + +theme.fgMain: #283739 +theme.fgBright: #073642 +theme.fgMuted: #657b83 + +theme.selBg: #268bd2 +theme.selFg: #ffffff +theme.accent: #b58900 +theme.accentAlt: #2aa198 +theme.highlight: #cb4b16 +theme.border: #93a1a1 +theme.divider: #839496 + +theme.success: #2aa198 +theme.info: #268bd2 +theme.warning: #cb4b16 +theme.danger: #dc322f +theme.dangerBg: #a93226 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #e6dfca +dmenu.foreground: #073642 +dmenu.selbackground: #268bd2 +dmenu.selforeground: #ffffff +dmenu.outbackground: #d9d2bd +dmenu.outforeground: #073642 +dmenu.highlight: #cb4b16 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #fdf6e3 +dwm.foreground: #283739 +dwm.border: #93a1a1 +dwm.selbackground: #268bd2 +dwm.selforeground: #ffffff +dwm.selborder: #268bd2 +dwm.normbgcolor: #fdf6e3 +dwm.normbordercolor: #93a1a1 +dwm.normfgcolor: #283739 +dwm.selbgcolor: #268bd2 +dwm.selbordercolor: #268bd2 +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #fdf6e3 +st.foreground: #283739 +st.cursorColor: #b58900 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/data/themes/TokyoNight.xth b/data/themes/TokyoNight.xth new file mode 100644 index 0000000..3866e91 --- /dev/null +++ b/data/themes/TokyoNight.xth @@ -0,0 +1,75 @@ +! Space to setup configversion +! configversion: 7bff124b2de16292fe6e7a7e5d3322ae +! ANODE Unified Theme: TokyoNight + +theme.name: TokyoNight +theme.fontFace: Fira Code +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 15 + +theme.bgMain: #1a1b26 +theme.bgBar: #1a1b26 +theme.bgHeader: #16161e +theme.bgFooter: #13141c +theme.bgOverlay: #111219 +theme.bgAltEven: #1f2335 +theme.bgAltOdd: #24283b +theme.bgInput: #14151e +theme.bgInputFocus: #283457 +theme.bgButton: #222638 +theme.bgSearch: #2f3549 +theme.bgBubbleIn: #1f2d30 +theme.bgBubbleOut: #222c4a +theme.bgToast: #1d2945 + +theme.fgMain: #c0caf5 +theme.fgBright: #ffffff +theme.fgMuted: #565f89 + +theme.selBg: #3d59a1 +theme.selFg: #ffffff +theme.accent: #7aa2f7 +theme.accentAlt: #bb9af7 +theme.highlight: #e0af68 +theme.border: #3b4261 +theme.divider: #545c7e + +theme.success: #9ece6a +theme.info: #7dcfff +theme.warning: #e0af68 +theme.danger: #f7768e +theme.dangerBg: #8c2d42 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 15px +dmenu.background: #16161e +dmenu.foreground: #ffffff +dmenu.selbackground: #3d59a1 +dmenu.selforeground: #ffffff +dmenu.outbackground: #2f3549 +dmenu.outforeground: #ffffff +dmenu.highlight: #e0af68 + +dwm.font: Fira Code, DejaVuSansM Nerd Font 15px +dwm.background: #1a1b26 +dwm.foreground: #c0caf5 +dwm.border: #3b4261 +dwm.selbackground: #3d59a1 +dwm.selforeground: #ffffff +dwm.selborder: #3d59a1 +dwm.normbgcolor: #1a1b26 +dwm.normbordercolor: #3b4261 +dwm.normfgcolor: #c0caf5 +dwm.selbgcolor: #3d59a1 +dwm.selbordercolor: #3d59a1 +dwm.selfgcolor: #ffffff +dwm.borderpx: 2 + +st.font: Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #16161e +st.foreground: #c0caf5 +st.cursorColor: #7aa2f7 +Xft.dpi: 96 +Xcursor.theme: default +Xcursor.size: 24 +*TkTheme: gtkTtk diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..1d95b50 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,29 @@ +# ANODE Architecture + +## Component Map + +- `Makefile` & `scripts/detect-env.sh`: Strict `.POSIX:` single build orchestration probing OS headers, `-lcrypt` vs ``, `-lrt`, `-lutil`, `XScrnSaver`, and optional `gtk+-2.0`/`tcl`/`tk` headers cleanly into `build/flags.sh`. +- `src/common/`: Cross-Unix platform layer (`anode_plat.c`, `anode_plat.h`), `.Xresources` / EDID fractional scale helpers (`anode_scale.h`), input validators (`anode_dns_valid.h`, `anode_tz_valid.h`), CLI output parsers (`anode_audio_parse.h`, `anode_wifi_list.h`, `anode_bt_list.h`), and power policy (`anode_power_policy.h`). +- `src/dwm/`, `src/dmenu/`, `src/st/`: Patched suckless X11 core using Pango/HarfBuzz (`Fira Code` ligatures), `.Xresources` + `SIGUSR1` live reload, and `anode_scale.h`. +- `src/libgemui/`: Shared library `libgemui.so` + `gemui.pc` providing double-buffered Cairo + Pango rendering, workarea-clamped responsive window sizing, hit tracking, touch-mode sizing (`gemui_touch_row_px`), self-pipe `SIGUSR1` + root `XA_RESOURCE_MANAGER` live reload, and non-blocking `poll()` loops. +- `src/apps/`: Desktop control panels and optional dock virtual keyboard (`anode-vkbd`) + multimedia dispatcher (`anode-media-key`). +- `src/daemons/`: Zero-poll `poll()` + signal self-pipe daemons (`anode-statusd`, `anode-touchd`, `anode-powerd`) and narrowly-scoped privilege helpers (`anode-power-ctl`, `anode-dnsctl`, `anode-tzctl`, `anode-checkpw`). +- `src/gtkTtk/`: Tk/Ttk native GTK-2 bridge (`libgtkTtk0.9.so` + `gtkTtk.tcl`) supporting full `[0.5, 4.0]` fractional scaling. +- `data/` & `scripts/`: 22 96-DPI `.xth` themes and strict POSIX `/bin/sh` synchronization scripts. + +## Fractional DPI Multi-Toolkit Contract + +For a user or EDID-detected scale `S` clamped to `[0.50, 4.00]`: + +- `Xft.dpi = round(96 * S)` +- `ANODE_SCALE = S`, `theme.baseFontSize = round(15 * S)` +- **GTK-3 / GTK-4 / xsettingsd**: `GDK_SCALE = (S < 1.75) ? 1 : round(S)`, `GDK_DPI_SCALE=1.0`, `ADW_DISABLE_PORTAL=1`, and `Gdk/WindowScalingFactor = GDK_SCALE` in `xsettingsd.conf` (**`Xft/DPI` is intentionally omitted** so GTK3 never double-scales). +- **Qt5 / Qt6**: `QT_AUTO_SCREEN_SCALE_FACTOR=0`, `QT_ENABLE_HIGHDPI_SCALING=1`, `QT_SCALE_FACTOR_ROUNDING_POLICY=PassThrough`, `QT_SCALE_FACTOR=S`, `QT_FONT_DPI=96`, with synced palettes in both `~/.config/qt5ct/` and `~/.config/qt6ct/`. +- **Tk / Tkinter (`gtkTtk`)**: `*TkTheme: gtkTtk`, Tk scaling normalized against `ANODE_SCALE` / `Xft.dpi`, using `Fira Code`. + +## First-Class Systray & EWMH Workarea Struts + +In `src/dwm/dwm.c`: +1. Acquires screen-specific `_NET_SYSTEM_TRAY_S` using a 32-bit ARGB `TrueColor` visual (when available, falling back cleanly to screen default visual) and publishes `_NET_SYSTEM_TRAY_VISUAL` and `_NET_SYSTEM_TRAY_ORIENTATION = 0`. +2. Tracks XEmbed `_XEMBED_INFO` flags bit `data[1]` (`XEMBED_MAPPED`), preserves `SubstructureNotifyMask`, emits `XEMBED_WINDOW_ACTIVATE` / `XEMBED_WINDOW_DEACTIVATE (2)`, unmaps the tray window when empty (`0` mapped icons), undocks cleanly on `ReparentNotify`/`UnmapNotify`/`DestroyNotify`, centers & re-scales icons on `SIGUSR1` / `XA_RESOURCE_MANAGER`, and relocates cleanly across monitors. +3. Monitors `_NET_WM_WINDOW_TYPE_DOCK` windows (`_NET_WM_STRUT_PARTIAL` / `_NET_WM_STRUT`), including `override_redirect` docks such as `anode-vkbd`, adjusting monitor workarea bounds (`wx, wy, ww, wh`) and publishing root `_NET_WORKAREA`. diff --git a/docs/KEYBINDINGS.md b/docs/KEYBINDINGS.md new file mode 100644 index 0000000..75768f2 --- /dev/null +++ b/docs/KEYBINDINGS.md @@ -0,0 +1,57 @@ +# ANODE Keybindings & Touch Gestures + +Default `MODKEY` is `Mod4` (`Super` / `Win`). + +## Window Management (`dwm`) + +| Binding | Action | +|---|---| +| `Mod4 + Return` | Launch `st` terminal (with `Fira Code` HarfBuzz ligatures) | +| `Mod4 + p` / `Mod4 + Space` / `Menu` | Open `anode-launcher` (desktop + app menu) | +| `Mod4 + Shift + p` | Open `dmenu_run` | +| `Mod4 + j` / `Mod4 + Down` | Focus next window | +| `Mod4 + k` / `Mod4 + Up` | Focus previous window | +| `Mod4 + Shift + Return` | Promote focused window to master (`zoom`) | +| `Mod4 + h` / `Mod4 + l` | Shrink / grow master area (`mfact`) | +| `Mod4 + i` / `Mod4 + o` | Increase / decrease master window count | +| `Mod4 + Shift + c` / `Mod4 + Shift + q` | Close focused window | +| `Mod4 + Shift + Space` | Toggle floating mode for focused window | +| `Mod4 + b` | Toggle DWM status & systray bar | +| `Mod4 + F1` / `F2` / `F3` / `F4` | Select layout: Tile (`[]=`), Monocle (`[M]`), Float (`><>`), Grid (`###`) | +| `Mod4 + m` / `f` / `g` | Monocle / Floating / Grid layout | +| `Mod4 + 1..5` | Switch to tag `1..5` | +| `Mod4 + Shift + 1..5` | Move focused window to tag `1..5` | +| `Mod4 + Tab` | Toggle previous tag | +| `Mod4 + ,` / `.` | Focus previous / next monitor | +| `Mod4 + Shift + ,` / `.` | Send window to previous / next monitor | +| `Mod4 + Shift + r` | Reload `.Xresources` / theme / DPI scale | +| `Mod4 + Ctrl + Shift + q` | Quit DWM | + +## Utilities & Multimedia Keys + +| Binding / Key | Action | +|---|---| +| `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 + w` | Date & Timezone (`anode-datetime`) | +| `Mod4 + t` | Themes & Typography (`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`) | +| `XF86AudioRaiseVolume` / `LowerVolume` / `Mute` | Output volume ±5% / mute + OSD | +| `XF86AudioMicMute` / `AudioRecord` | Toggle microphone mute + OSD | +| `XF86AudioPlay` / `Pause` / `Prev` / `Next` / `Stop` | Media playback control (`playerctl`/`mpc`/`mpv`) | +| `XF86MonBrightnessUp` / `Down` | Display backlight ±10% + OSD | +| `XF86UWB` / `XF86RFKill` | Toggle Airplane Mode | +| `XF86Sleep` | Suspend system (`anode-power-ctl suspend`) | + +## Edge Touch Gestures (`anode-touchd`) + +| Swipe Gesture | Action | +|---|---| +| Top edge swipe down | Launch `anode-launcher` | +| Bottom edge swipe up | Toggle virtual keyboard (`anode-vkbd`) | +| Right edge swipe left | Open Control Center (`anode-power`) | +| Left edge swipe right | Cycle focused window | diff --git a/scripts/anode-apply-scale b/scripts/anode-apply-scale new file mode 100755 index 0000000..128d1e9 --- /dev/null +++ b/scripts/anode-apply-scale @@ -0,0 +1,169 @@ +#!/bin/sh +# ANODE fractional DPI scale & touch-mode manager (strict POSIX sh) +set -eu + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +CONF_DIR="$XDG_CONFIG_HOME/anode" +CONF_FILE="$CONF_DIR/scale.conf" +ENV_FILE="$CONF_DIR/scale.env" + +SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" + +usage() { + cat <<'EOF' +Usage: anode-apply-scale [SCALE|auto] [--touch=0|1] [--no-apply] + +Options: + SCALE Fractional UI scale factor between 0.50 and 4.00 (e.g. 0.75, 1.00, 1.25, 1.50, 2.00) + auto Detect scale automatically from primary X11 output EDID dimensions (fallback 1.00) + --touch=0|1 Enable (1) or disable (0) touch-mode sizing & virtual keyboard defaults + --no-apply Only write scale.conf/scale.env without re-applying the active theme +EOF +} + +SCALE="" +TOUCH="" +DO_APPLY=1 + +if [ -f "$CONF_FILE" ]; then + . "$CONF_FILE" +fi +: "${SCALE:=1.00}" +: "${TOUCH:=0}" + +for arg in "$@"; do + case "$arg" in + -h|--help) + usage + exit 0 + ;; + --touch=0|--touch=false|--touch=off) + TOUCH=0 + ;; + --touch=1|--touch=true|--touch=on) + TOUCH=1 + ;; + --no-apply) + DO_APPLY=0 + ;; + auto) + SCALE="auto" + ;; + *) + SCALE="$arg" + ;; + esac +done + +detect_edid_scale() { + _dpi="96" + if [ -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) + } + px = 0; wmm = 0 + for (i = 1; i <= NF; i++) { + if ($i ~ /^[0-9]+x[0-9]+(\+[0-9]+\+[0-9]+)?$/ && px == 0) { + split($i, a, "x"); px = a[1] + 0 + } + if ($i ~ /^[0-9]+mm$/ && $(i+1) == "x" && $(i+2) ~ /^[0-9]+mm$/) { + wmm = $i; gsub(/mm/, "", wmm); wmm += 0 + } + } + if (px > 0 && wmm > 0) { + printf "%.2f\n", (px * 25.4) / wmm + exit + } + } + ' || true)" + if [ -n "${_xrandr_dpi:-}" ]; then + _dpi="$_xrandr_dpi" + fi + fi + if [ "$_dpi" = "96" ] && [ -n "${DISPLAY:-}" ] && command -v xdpyinfo >/dev/null 2>&1; then + _xdpy_dpi="$(xdpyinfo 2>/dev/null | awk '/resolution:/ { split($2, a, "x"); if (a[1] > 0) { print a[1]; exit } }' || true)" + if [ -n "${_xdpy_dpi:-}" ]; then + _dpi="$_xdpy_dpi" + fi + fi + awk -v d="$_dpi" 'BEGIN { + s = (d + 0) / 96.0 + s = int(s * 20.0 + 0.5) / 20.0 + if (s < 0.50) s = 0.50 + if (s > 4.00) s = 4.00 + printf "%.2f\n", s + }' +} + +if [ "$SCALE" = "auto" ]; then + SCALE="$(detect_edid_scale)" +fi + +if ! printf '%s\n' "$SCALE" | awk '/^[0-9]+(\.[0-9]+)?$/ { exit 0 } { exit 1 }'; then + printf 'anode-apply-scale: invalid scale value: %s\n' "$SCALE" >&2 + exit 1 +fi + +CALC="$(awk -v raw="$SCALE" -v touch="$TOUCH" 'BEGIN { + s = raw + 0.0 + if (s < 0.50) s = 0.50 + if (s > 4.00) s = 4.00 + s = int(s * 100.0 + 0.5) / 100.0 + xft_dpi = int(96.0 * s + 0.5) + gdk_scale = (s < 1.75) ? 1 : int(s + 0.5) + cur_sz = int(24.0 * s + 0.5) + if (cur_sz < 16) cur_sz = 16 + if (cur_sz > 96) cur_sz = 96 + t = (touch == "1" || touch == 1) ? 1 : 0 + printf "%.2f %d %d %d %d\n", s, xft_dpi, gdk_scale, cur_sz, t +}')" + +set -- $CALC +SCALE="$1" +XFT_DPI="$2" +GDK_SCALE="$3" +XCURSOR_SIZE="$4" +TOUCH="$5" + +mkdir -p "$CONF_DIR" + +TMP_CONF="$CONF_FILE.tmp.$$" +cat > "$TMP_CONF" < "$TMP_ENV" </dev/null 2>&1; then + anode-apply-theme + fi +fi + +printf 'ANODE scale: %s (Xft.dpi=%s, GDK_SCALE=%s, QT_SCALE_FACTOR=%s, Xcursor=%s, touch=%s)\n' \ + "$SCALE" "$XFT_DPI" "$GDK_SCALE" "$SCALE" "$XCURSOR_SIZE" "$TOUCH" diff --git a/scripts/anode-apply-theme b/scripts/anode-apply-theme new file mode 100755 index 0000000..f4a5d62 --- /dev/null +++ b/scripts/anode-apply-theme @@ -0,0 +1,231 @@ +#!/bin/sh +# ANODE unified .xth theme applier (strict POSIX sh, fractional DPI aware) +set -eu + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +: "${ANODE_PREFIX:=/usr/local}" +CONF_DIR="$XDG_CONFIG_HOME/anode" +THEME_CONF="$CONF_DIR/theme.conf" +SCALE_CONF="$CONF_DIR/scale.conf" +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] +EOF + exit 0 +fi + +REQ_THEME="${1:-}" +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}" + +find_xth() { + _q="$1" + if [ -f "$_q" ]; then + printf '%s\n' "$_q" + return 0 + fi + if [ -f "$_q.xth" ]; then + printf '%s\n' "$_q.xth" + return 0 + fi + _base="$(basename "$_q" .xth)" + for _dir in \ + "$CONF_DIR/themes" \ + "$HOME/.xthemes" \ + "$ANODE_PREFIX/share/anode/themes" \ + "$SCRIPT_DIR/../share/anode/themes" \ + "$SCRIPT_DIR/../data/themes" + do + if [ -f "$_dir/$_base.xth" ]; then + printf '%s\n' "$_dir/$_base.xth" + return 0 + fi + done + return 1 +} + +XTH_FILE="$(find_xth "$REQ_THEME" || true)" +if [ -z "$XTH_FILE" ] || [ ! -r "$XTH_FILE" ]; then + printf 'anode-apply-theme: theme not found: %s\n' "$REQ_THEME" >&2 + exit 1 +fi + +SCALE="1.00" +TOUCH="0" +if [ -f "$SCALE_CONF" ]; then + . "$SCALE_CONF" +fi +if [ -n "${ANODE_SCALE:-}" ]; then SCALE="$ANODE_SCALE"; fi +if [ -n "${ANODE_TOUCH:-}" ]; then TOUCH="$ANODE_TOUCH"; fi + +THEME_NAME="$(awk -F: '/^theme\.name[[:space:]]*:/ { sub(/^[[:space:]]+/, "", $2); print $2; exit }' "$XTH_FILE" || true)" +if [ -z "$THEME_NAME" ]; then + THEME_NAME="$(basename "$XTH_FILE" .xth)" +fi + +mkdir -p "$CONF_DIR" +TMP_XRES="$HOME/.Xresources.tmp.$$" + +awk -v scale_str="$SCALE" -v touch_str="$TOUCH" -v tname="$THEME_NAME" ' +function trim(s) { + gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s) + return s +} +function rint(x) { + return int(x + 0.5) +} +{ + raw[NR] = $0 + s = trim($0) + if (s == "" || substr(s, 1, 1) == "!" || substr(s, 1, 1) == "#") next + pos = index(s, ":") + if (pos > 0) { + k = trim(substr(s, 1, pos - 1)) + v = trim(substr(s, pos + 1)) + vals[k] = v + } +} +END { + s = scale_str + 0.0 + if (s < 0.50) s = 0.50 + if (s > 4.00) s = 4.00 + t = (touch_str == "1" || touch_str == 1) ? 1 : 0 + + orig_dpi = ("Xft.dpi" in vals) ? (vals["Xft.dpi"] + 0.0) : 96.0 + base_sz = ("theme.baseFontSize" in vals) ? (vals["theme.baseFontSize"] + 0.0) : 15.0 + cur_sz = ("Xcursor.size" in vals) ? (vals["Xcursor.size"] + 0.0) : 24.0 + bw = ("dwm.borderpx" in vals) ? (vals["dwm.borderpx"] + 0.0) : 2.0 + + # Normalize imported 192-DPI themes down to 96-DPI logical bases before scaling + if (orig_dpi >= 160.0 && base_sz >= 24.0) { + base_sz = base_sz / 2.0 + if (cur_sz >= 40.0) cur_sz = cur_sz / 2.0 + if (bw >= 4.0) bw = bw / 2.0 + } + if (base_sz < 8.0 || base_sz > 28.0) base_sz = 15.0 + if (cur_sz < 12.0 || cur_sz > 48.0) cur_sz = 24.0 + if (bw < 1.0 || bw > 6.0) bw = 2.0 + + xft_dpi = rint(96.0 * s) + if (xft_dpi < 48) xft_dpi = 48 + if (xft_dpi > 384) xft_dpi = 384 + + scaled_font_px = rint(base_sz * s) + if (scaled_font_px < 8) scaled_font_px = 8 + if (scaled_font_px > 96) scaled_font_px = 96 + + scaled_cur = rint(cur_sz * s) + if (scaled_cur < 16) scaled_cur = 16 + if (scaled_cur > 96) scaled_cur = 96 + + scaled_bw = rint(bw * s) + if (scaled_bw < 1) scaled_bw = 1 + if (scaled_bw > 10) scaled_bw = 10 + + scaled_dm_lh = rint(36.0 * s) + if (scaled_dm_lh < 22) scaled_dm_lh = 22 + if (t == 1 && scaled_dm_lh < rint(44.0 * s)) scaled_dm_lh = rint(44.0 * s) + + font_face = ("theme.fontFace" in vals && vals["theme.fontFace"] != "") ? vals["theme.fontFace"] : "Fira Code" + icon_face = ("theme.iconFontFace" in vals && vals["theme.iconFontFace"] != "") ? vals["theme.iconFontFace"] : "DejaVuSansM Nerd Font" + + over["theme.name"] = tname + over["theme.fontFace"] = font_face + over["theme.iconFontFace"] = icon_face + over["theme.baseFontSize"] = sprintf("%d", scaled_font_px) + over["theme.scale"] = sprintf("%.2f", s) + over["theme.touchMode"] = sprintf("%d", t) + over["theme.gtkTheme"] = "ANODE-" tname + over["*TkTheme"] = "gtkTtk" + over["Xft.dpi"] = sprintf("%d", xft_dpi) + over["Xcursor.size"] = sprintf("%d", scaled_cur) + over["dwm.borderpx"] = sprintf("%d", scaled_bw) + over["dwm.font"] = sprintf("%s, %s %dpx", font_face, icon_face, scaled_font_px) + over["dmenu.font"] = sprintf("%s, %s %dpx", font_face, icon_face, scaled_font_px) + over["dmenu.lineheight"] = sprintf("%d", scaled_dm_lh) + over["st.font"] = sprintf("%s:pixelsize=%d:style=Regular:antialias=true:autohint=true", font_face, scaled_font_px) + + for (i = 1; i <= NR; i++) { + sline = trim(raw[i]) + if (sline == "" || substr(sline, 1, 1) == "!" || substr(sline, 1, 1) == "#") { + print raw[i] + continue + } + p = index(sline, ":") + if (p > 0) { + key = trim(substr(sline, 1, p - 1)) + if (key in over) { + if (!(key in emitted)) { + printf "%s: %s\n", key, over[key] + emitted[key] = 1 + } + } else { + print raw[i] + } + } else { + print raw[i] + } + } + order[1] = "theme.scale"; order[2] = "theme.touchMode"; order[3] = "theme.gtkTheme" + order[4] = "*TkTheme"; order[5] = "Xft.dpi"; order[6] = "Xcursor.size" + order[7] = "theme.fontFace"; order[8] = "theme.iconFontFace"; order[9] = "theme.baseFontSize" + order[10] = "dwm.borderpx"; order[11] = "dwm.font"; order[12] = "dmenu.font" + order[13] = "dmenu.lineheight"; order[14] = "st.font" + for (j = 1; j <= 14; j++) { + ok = order[j] + if (!(ok in emitted)) { + printf "%s: %s\n", ok, over[ok] + emitted[ok] = 1 + } + } +} +' "$XTH_FILE" > "$TMP_XRES" + +mv -f "$TMP_XRES" "$HOME/.Xresources" + +TMP_TC="$THEME_CONF.tmp.$$" +printf 'THEME=%s\nXTH_FILE=%s\n' "$THEME_NAME" "$XTH_FILE" > "$TMP_TC" +mv -f "$TMP_TC" "$THEME_CONF" + +if [ -n "${DISPLAY:-}" ] && command -v xrdb >/dev/null 2>&1; then + xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true +fi + +if [ -x "$SCRIPT_DIR/anode-sync-gtk-theme" ]; then + "$SCRIPT_DIR/anode-sync-gtk-theme" +elif command -v anode-sync-gtk-theme >/dev/null 2>&1; then + anode-sync-gtk-theme +fi + +if [ -x "$SCRIPT_DIR/anode-sync-dunst-theme" ]; then + "$SCRIPT_DIR/anode-sync-dunst-theme" +elif command -v anode-sync-dunst-theme >/dev/null 2>&1; then + anode-sync-dunst-theme +fi + +if [ -n "${DISPLAY:-}" ] && [ "${ANODE_NO_SIGNAL:-0}" != "1" ]; then + _pids="$( (ps -eo pid=,comm= 2>/dev/null || ps -ax -o pid=,comm= 2>/dev/null || true) | awk ' + { + pid = $1; cmd = $2 + sub(/^.*\//, "", cmd) + if (cmd == "dwm" || cmd == "st" || cmd == "anode-statusd" || + cmd == "anode-net" || cmd == "anode-audio" || cmd == "anode-display" || + cmd == "anode-datetime" || cmd == "anode-power" || cmd == "anode-themes") { + print "USR1 " pid + } else if (cmd == "anode-vkbd") { + print "HUP " pid + } + } + ' )" + if [ -n "${_pids:-}" ]; then + printf '%s\n' "$_pids" | while read -r _sig _p; do + [ -n "${_p:-}" ] && kill -"$_sig" "$_p" 2>/dev/null || true + done + fi +fi + +printf 'ANODE applied theme: %s (scale=%s)\n' "$THEME_NAME" "$SCALE" diff --git a/scripts/anode-launcher b/scripts/anode-launcher new file mode 100755 index 0000000..7b5ff37 --- /dev/null +++ b/scripts/anode-launcher @@ -0,0 +1,64 @@ +#!/bin/sh +# ANODE dynamic launcher using patched dmenu (strict POSIX sh) +set -u + +: "${XDG_DATA_HOME:=$HOME/.local/share}" +: "${ANODE_PREFIX:=/usr/local}" +CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/anode" +mkdir -p "$CACHE_DIR" + +APPS_TMP="$CACHE_DIR/launcher-apps.$$" +cleanup() { rm -f "$APPS_TMP"; } +trap cleanup EXIT INT TERM + +{ + printf 'Terminal\tst\n' + printf 'Control Center & Power\tanode-power\n' + printf 'Network & Wi-Fi\tanode-net\n' + printf 'Audio & Volume\tanode-audio\n' + printf 'Display & Scaling\tanode-display\n' + printf 'Date & Timezone\tanode-datetime\n' + printf 'Themes & Fonts\tanode-themes\n' + printf 'Virtual Keyboard Toggle\tanode-media-key vkbd-toggle\n' + printf 'Lock Screen\tanode-lock\n' + + IFS=: + for _base in "$XDG_DATA_HOME" "${XDG_DATA_DIRS:-$ANODE_PREFIX/share:/usr/local/share:/usr/share}"; do + _dir="$_base/applications" + [ -d "$_dir" ] || continue + for _f in "$_dir"/*.desktop; do + [ -f "$_f" ] || continue + awk ' + /^\[Desktop Entry\]/ { in_entry=1; next } + /^\[/ { in_entry=0 } + in_entry && /^Name=/ && !name { sub(/^Name=/, ""); name=$0 } + in_entry && /^Exec=/ && !exec_cmd { sub(/^Exec=/, ""); exec_cmd=$0 } + in_entry && /^NoDisplay=true/ { hidden=1 } + in_entry && /^Terminal=true/ { isterm=1 } + END { + if (!hidden && name != "" && exec_cmd != "") { + gsub(/%[fFuUdDnNickvm]/, "", exec_cmd) + gsub(/^[ \t]+|[ \t]+$/, "", exec_cmd) + if (isterm) printf "%s (term)\tst -e %s\n", name, exec_cmd + else printf "%s\t%s\n", name, exec_cmd + } + } + ' "$_f" + done + done + unset IFS + + if command -v dmenu_path >/dev/null 2>&1; then + dmenu_path | while IFS= read -r _bin; do + [ -n "$_bin" ] && printf '%s\t%s\n' "$_bin" "$_bin" + done + fi +} | awk -F'\t' '!seen[$1]++ { print $0 }' > "$APPS_TMP" + +CHOICE="$(cut -f1 "$APPS_TMP" | dmenu -i -l 12 -p "Run:")" || exit 0 +[ -n "$CHOICE" ] || exit 0 + +CMD="$(awk -F'\t' -v ch="$CHOICE" '$1 == ch { print $2; exit }' "$APPS_TMP")" +[ -n "$CMD" ] || CMD="$CHOICE" + +exec /bin/sh -c "exec $CMD" >/dev/null 2>&1 & diff --git a/scripts/anode-session b/scripts/anode-session new file mode 100755 index 0000000..f06393d --- /dev/null +++ b/scripts/anode-session @@ -0,0 +1,75 @@ +#!/bin/sh +# ANODE X11 desktop session entrypoint (strict POSIX sh) +set -u + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +: "${ANODE_PREFIX:=/usr/local}" +SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" + +# Ensure ANODE prefix binaries are on PATH +case ":$PATH:" in + *":$SCRIPT_DIR:"*) ;; + *) PATH="$SCRIPT_DIR:$PATH" ;; +esac +case ":$PATH:" in + *":$ANODE_PREFIX/bin:"*) ;; + *) PATH="$ANODE_PREFIX/bin:$PATH" ;; +esac +export PATH + +for _envfile in "$ANODE_PREFIX/share/anode/env.sh" "$SCRIPT_DIR/../data/env.sh"; do + if [ -r "$_envfile" ]; then + . "$_envfile" + break + fi +done +unset _envfile + +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 +if [ -f "$XDG_CONFIG_HOME/anode/scale.env" ]; then + . "$XDG_CONFIG_HOME/anode/scale.env" +fi + +if [ ! -f "$HOME/.Xresources" ] && command -v anode-apply-theme >/dev/null 2>&1; then + anode-apply-theme AnodeDefault >/dev/null 2>&1 || true +elif [ -f "$HOME/.Xresources" ] && command -v xrdb >/dev/null 2>&1; then + xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true +fi + +if command -v xsetroot >/dev/null 2>&1; then + xsetroot -cursor_name left_ptr >/dev/null 2>&1 || true +fi + +BG_PIDS="" +spawn_bg() { + if command -v "$1" >/dev/null 2>&1; then + "$@" >/dev/null 2>&1 & + BG_PIDS="$BG_PIDS $!" + fi +} + +cleanup_bg() { + for _pid in $BG_PIDS; do + kill "$_pid" 2>/dev/null || true + done +} +trap cleanup_bg EXIT INT TERM + +spawn_bg xsettingsd +spawn_bg dunst +spawn_bg anode-statusd +spawn_bg anode-powerd +spawn_bg anode-touchd + +if [ "${ANODE_TOUCH:-0}" = "1" ]; then + spawn_bg anode-vkbd +fi + +if command -v dwm >/dev/null 2>&1; then + dwm +else + printf 'anode-session: dwm executable not found\n' >&2 + exit 1 +fi diff --git a/scripts/anode-sync-dunst-theme b/scripts/anode-sync-dunst-theme new file mode 100755 index 0000000..1aa546e --- /dev/null +++ b/scripts/anode-sync-dunst-theme @@ -0,0 +1,156 @@ +#!/bin/sh +# ANODE Dunst notification theme & DPI scaler (strict POSIX sh) +set -eu + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +XRES="${1:-$HOME/.Xresources}" +DUNST_DIR="$XDG_CONFIG_HOME/dunst" +DUNST_RC="$DUNST_DIR/dunstrc" + +xres_get() { + _k="$1" + _def="$2" + _val="$(awk -v key="$_k" ' + { + s = $0 + gsub(/^[ \t\r]+|[ \t\r]+$/, "", s) + if (s == "" || substr(s, 1, 1) == "!" || substr(s, 1, 1) == "#") next + p = index(s, ":") + if (p > 0) { + k = substr(s, 1, p - 1) + gsub(/^[ \t]+|[ \t]+$/, "", k) + if (k == key) { + v = substr(s, p + 1) + gsub(/^[ \t]+|[ \t]+$/, "", v) + print v + exit + } + } + } + ' "$XRES" 2>/dev/null || true)" + if [ -n "$_val" ]; then + printf '%s\n' "$_val" + else + printf '%s\n' "$_def" + fi +} + +if [ ! -r "$XRES" ]; then + exit 0 +fi + +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")" + +GEOM="$(awk -v s="$SCALE" -v bsz="$BASE_SZ" 'BEGIN { + sc = s + 0.0 + if (sc < 0.50) sc = 0.50 + if (sc > 4.00) sc = 4.00 + w = int(340.0 * sc + 0.5); if (w < 220) w = 220 + hmax = int(180.0 * sc + 0.5); if (hmax < 80) hmax = 80 + ox = int(16.0 * sc + 0.5); if (ox < 8) ox = 8 + oy = int(42.0 * sc + 0.5); if (oy < 20) oy = 20 + pad = int(12.0 * sc + 0.5); if (pad < 6) pad = 6 + hpad = int(14.0 * sc + 0.5); if (hpad < 8) hpad = 8 + tpad = int(8.0 * sc + 0.5); if (tpad < 4) tpad = 4 + fw = int(2.0 * sc + 0.5); if (fw < 1) fw = 1 + rad = int(8.0 * sc + 0.5); if (rad < 4) rad = 4 + pbar_h = int(8.0 * sc + 0.5); if (pbar_h < 4) pbar_h = 4 + fpt = int(((bsz + 0.0) * 0.72) + 0.5); if (fpt < 8) fpt = 8 + printf "%d %d %d %d %d %d %d %d %d %d %d\n", w, hmax, ox, oy, pad, hpad, tpad, fw, rad, pbar_h, fpt +}')" + +set -- $GEOM +D_W="$1" D_H="$2" D_OX="$3" D_OY="$4" D_PAD="$5" D_HPAD="$6" D_TPAD="$7" D_FW="$8" D_RAD="$9" +shift 9 +D_PBAR="$1" D_FPT="$2" + +mkdir -p "$DUNST_DIR" +TMP_RC="$DUNST_RC.tmp.$$" + +cat > "$TMP_RC" </dev/null 2>&1; then + dunstctl reload >/dev/null 2>&1 || true + fi + _dpids="$( (ps -eo pid=,comm= 2>/dev/null || ps -ax -o pid=,comm= 2>/dev/null || true) | awk ' + { cmd=$2; sub(/^.*\//, "", cmd); if (cmd == "dunst") print $1 } + ' )" + if [ -n "${_dpids:-}" ]; then + for _p in $_dpids; do + kill -HUP "$_p" 2>/dev/null || true + done + fi +fi diff --git a/scripts/anode-sync-gtk-theme b/scripts/anode-sync-gtk-theme new file mode 100755 index 0000000..0c90964 --- /dev/null +++ b/scripts/anode-sync-gtk-theme @@ -0,0 +1,399 @@ +#!/bin/sh +# ANODE multi-toolkit theme & fractional-DPI synchronizer (strict POSIX sh) +# Syncs GTK2, GTK3, GTK4/libadwaita, xsettingsd, Qt5 (qt5ct), Qt6 (qt6ct), and Kvantum. +set -eu + +: "${XDG_CONFIG_HOME:=$HOME/.config}" +XRES="${1:-$HOME/.Xresources}" + +if [ ! -r "$XRES" ]; then + exit 0 +fi + +xres_get() { + _k="$1" + _def="$2" + _val="$(awk -v key="$_k" ' + { + s = $0 + gsub(/^[ \t\r]+|[ \t\r]+$/, "", s) + if (s == "" || substr(s, 1, 1) == "!" || substr(s, 1, 1) == "#") next + p = index(s, ":") + if (p > 0) { + k = substr(s, 1, p - 1) + gsub(/^[ \t]+|[ \t]+$/, "", k) + if (k == key) { + v = substr(s, p + 1) + gsub(/^[ \t]+|[ \t]+$/, "", v) + print v + exit + } + } + } + ' "$XRES" 2>/dev/null || true)" + if [ -n "$_val" ]; then + printf '%s\n' "$_val" + else + printf '%s\n' "$_def" + fi +} + +TNAME="$(xres_get theme.name "AnodeDefault")" +DARK="$(xres_get theme.isDark "1")" +FONT_FACE="$(xres_get theme.fontFace "Fira Code")" +BASE_SZ="$(xres_get theme.baseFontSize "15")" +SCALE="$(xres_get theme.scale "1.00")" +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")" + +THEME_ID="ANODE-$TNAME" + +CALC="$(awk -v s="$SCALE" -v bsz="$BASE_SZ" -v dark="$DARK" 'BEGIN { + sc = s + 0.0 + if (sc < 0.50) sc = 0.50 + if (sc > 4.00) sc = 4.00 + gdk_sc = (sc < 1.75) ? 1 : int(sc + 0.5) + # Effective GTK logical scale multiplier when GDK_SCALE=1 vs 2 + eff = sc / gdk_sc + if (eff < 0.5) eff = 0.5 + pt = int(((bsz + 0.0) * 0.72 / gdk_sc) + 0.5) + if (pt < 7) pt = 7 + if (pt > 24) pt = 24 + btn_pv = int(6.0 * eff + 0.5); if (btn_pv < 3) btn_pv = 3 + btn_ph = int(12.0 * eff + 0.5); if (btn_ph < 6) btn_ph = 6 + rad = int(6.0 * eff + 0.5); if (rad < 3) rad = 3 + row_h = int(28.0 * eff + 0.5); if (row_h < 20) row_h = 20 + sb_w = int(12.0 * eff + 0.5); if (sb_w < 8) sb_w = 8 + is_d = (dark == "1" || dark == "true") ? 1 : 0 + printf "%d %d %d %d %d %d %d %d\n", gdk_sc, pt, btn_pv, btn_ph, rad, row_h, sb_w, is_d +}')" +set -- $CALC +GDK_SCALE_VAL="$1" +GTK_PT="$2" +PAD_V="$3" +PAD_H="$4" +RAD_PX="$5" +ROW_H="$6" +SB_W="$7" +IS_DARK="$8" + +GTK_FONT="$FONT_FACE $GTK_PT" + +# 1. GTK-2 theme & ~/.gtkrc-2.0 +GTK2_DIR="$HOME/.themes/$THEME_ID/gtk-2.0" +mkdir -p "$GTK2_DIR" +cat > "$GTK2_DIR/gtkrc.tmp.$$" < "$HOME/.gtkrc-2.0.tmp.$$" < "$_tmp" <> "$_tmp" < "$GTK3_CONF_DIR/settings.ini.tmp.$$" < "$GTK4_CONF_DIR/settings.ini.tmp.$$" < "$XSET_DIR/xsettingsd.conf.tmp.$$" < "${_pal}.tmp.$$" < "${_qconf}.tmp.$$" < "$KV_DIR/kvantum.kvconfig.tmp.$$" < "$KV_TDIR/$THEME_ID.kvconfig.tmp.$$" </dev/null || true + done + fi +fi diff --git a/scripts/detect-env.sh b/scripts/detect-env.sh new file mode 100755 index 0000000..7f890ec --- /dev/null +++ b/scripts/detect-env.sh @@ -0,0 +1,307 @@ +#!/bin/sh +# Detect OS, compiler capabilities, and X11/toolkit flags for ANODE. +# Strictly POSIX sh; writes an atomic shell-sourceable build configuration. +set -eu + +OUT_FILE="${1:-build/flags.sh}" +CC_BIN="${CC:-cc}" +CXX_BIN="${CXX:-c++}" +PKG_CFG="${PKG_CONFIG:-pkg-config}" +WITH_GTKTTK="${WITH_GTKTTK:-auto}" + +OS_NAME="$(uname -s 2>/dev/null || printf 'Unknown')" + +# Ensure common BSD/Linux/pkgsrc pkg-config directories are searched. +for pcdir in \ + /usr/local/lib/pkgconfig \ + /usr/local/libdata/pkgconfig \ + /usr/X11R6/lib/pkgconfig \ + /usr/X11R7/lib/pkgconfig \ + /usr/pkg/lib/pkgconfig \ + /usr/lib/pkgconfig \ + /usr/share/pkgconfig +do + if [ -d "$pcdir" ]; then + case ":${PKG_CONFIG_PATH:-}:" in + *":$pcdir:"*) ;; + *) PKG_CONFIG_PATH="${PKG_CONFIG_PATH:+$PKG_CONFIG_PATH:}$pcdir" ;; + esac + fi +done +export PKG_CONFIG_PATH + +if ! command -v "$PKG_CFG" >/dev/null 2>&1; then + printf 'detect-env.sh: error: %s not found\n' "$PKG_CFG" >&2 + exit 1 +fi + +mkdir -p \ + build \ + build/common \ + build/dwm \ + build/dmenu \ + build/st \ + build/libgemui \ + build/apps \ + build/daemons \ + build/gtkTtk \ + build/tests + +TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/anode-probe.XXXXXX")" +cleanup() { + rm -rf "$TMP_DIR" +} +trap cleanup EXIT INT TERM + +require_pkgs() { + for pkg in "$@"; do + if ! "$PKG_CFG" --exists "$pkg" 2>/dev/null; then + printf 'detect-env.sh: error: required pkg-config module "%s" not found\n' "$pkg" >&2 + exit 1 + fi + done +} + +require_pkgs \ + x11 xext xft xinerama xrender xrandr xfixes xi xtst \ + fontconfig freetype2 pango pangoxft pangocairo cairo harfbuzz + +# Probe openpty (libc vs -lutil) +cat > "$TMP_DIR/pty.c" <<'EOF' +#if defined(__linux__) || defined(__linux) +#include +#elif defined(__FreeBSD__) || defined(__DragonFly__) +#include +#include +#else +#include +#include +#include +#endif +int main(void) { + int m = 0, s = 0; + return openpty(&m, &s, 0, 0, 0); +} +EOF +PTY_LIBS="" +if "$CC_BIN" "$TMP_DIR/pty.c" -o "$TMP_DIR/pty.out" >/dev/null 2>&1; then + PTY_LIBS="" +elif "$CC_BIN" "$TMP_DIR/pty.c" -lutil -o "$TMP_DIR/pty.out" >/dev/null 2>&1; then + PTY_LIBS="-lutil" +fi + +# Probe clock_gettime (libc vs -lrt) +cat > "$TMP_DIR/rt.c" <<'EOF' +#include +int main(void) { + struct timespec ts; + return clock_gettime(CLOCK_MONOTONIC, &ts); +} +EOF +RT_LIBS="" +if "$CC_BIN" "$TMP_DIR/rt.c" -o "$TMP_DIR/rt.out" >/dev/null 2>&1; then + RT_LIBS="" +elif "$CC_BIN" "$TMP_DIR/rt.c" -lrt -o "$TMP_DIR/rt.out" >/dev/null 2>&1; then + RT_LIBS="-lrt" +fi + +# Probe crypt() and shadow.h vs BSD getpwnam(), with or without +HAVE_CRYPT_H=0 +cat > "$TMP_DIR/crypt_h.c" <<'EOF' +#include +int main(void) { return 0; } +EOF +if "$CC_BIN" "$TMP_DIR/crypt_h.c" -o "$TMP_DIR/chk.out" >/dev/null 2>&1; then + HAVE_CRYPT_H=1 +fi + +cat > "$TMP_DIR/shadow.c" < +#include +$( [ "$HAVE_CRYPT_H" = "1" ] && printf '#include \n' ) +int main(void) { + struct spwd *sp = getspnam("root"); + (void)sp; + return crypt("a", "aa") ? 0 : 1; +} +EOF +cat > "$TMP_DIR/bsd_pw.c" < +#include +$( [ "$HAVE_CRYPT_H" = "1" ] && printf '#include \n' ) +int main(void) { + struct passwd *pw = getpwnam("root"); + (void)pw; + return crypt("a", "aa") ? 0 : 1; +} +EOF + +CHECKPW_DEFS="-DHAVE_BSD_PASSWD=1" +[ "$HAVE_CRYPT_H" = "1" ] && CHECKPW_DEFS="$CHECKPW_DEFS -DHAVE_CRYPT_H=1" +CHECKPW_LIBS="" +if "$CC_BIN" "$TMP_DIR/shadow.c" -o "$TMP_DIR/chk.out" >/dev/null 2>&1; then + CHECKPW_DEFS="-DHAVE_SHADOW_H=1" + [ "$HAVE_CRYPT_H" = "1" ] && CHECKPW_DEFS="$CHECKPW_DEFS -DHAVE_CRYPT_H=1" + CHECKPW_LIBS="" +elif "$CC_BIN" "$TMP_DIR/shadow.c" -lcrypt -o "$TMP_DIR/chk.out" >/dev/null 2>&1; then + CHECKPW_DEFS="-DHAVE_SHADOW_H=1" + [ "$HAVE_CRYPT_H" = "1" ] && CHECKPW_DEFS="$CHECKPW_DEFS -DHAVE_CRYPT_H=1" + CHECKPW_LIBS="-lcrypt" +elif "$CC_BIN" "$TMP_DIR/bsd_pw.c" -o "$TMP_DIR/chk.out" >/dev/null 2>&1; then + CHECKPW_DEFS="-DHAVE_BSD_PASSWD=1" + [ "$HAVE_CRYPT_H" = "1" ] && CHECKPW_DEFS="$CHECKPW_DEFS -DHAVE_CRYPT_H=1" + CHECKPW_LIBS="" +elif "$CC_BIN" "$TMP_DIR/bsd_pw.c" -lcrypt -o "$TMP_DIR/chk.out" >/dev/null 2>&1; then + CHECKPW_DEFS="-DHAVE_BSD_PASSWD=1" + [ "$HAVE_CRYPT_H" = "1" ] && CHECKPW_DEFS="$CHECKPW_DEFS -DHAVE_CRYPT_H=1" + CHECKPW_LIBS="-lcrypt" +fi + +# Probe XScrnSaver for idle time tracking in anode-powerd +POWERD_PKGS="x11 xext" +POWERD_DEFS="" +if "$PKG_CFG" --exists xscrnsaver 2>/dev/null; then + POWERD_PKGS="x11 xext xscrnsaver" + 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)" + +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" + +ST_CFLAGS="$("$PKG_CFG" --cflags fontconfig freetype2 harfbuzz xft x11 xfixes xi)" +ST_LIBS="$("$PKG_CFG" --libs fontconfig freetype2 harfbuzz xft x11 xfixes xi) -lm $RT_LIBS $PTY_LIBS" + +GEMUI_CFLAGS="$("$PKG_CFG" --cflags x11 xext xft xinerama xrandr cairo pangocairo pango harfbuzz fontconfig freetype2)" +GEMUI_LIBS="$("$PKG_CFG" --libs x11 xext xft xinerama xrandr cairo pangocairo pango harfbuzz fontconfig freetype2) -lm" + +APP_CFLAGS="$("$PKG_CFG" --cflags x11 xext xft xinerama xrandr xtst cairo pangocairo pango harfbuzz fontconfig freetype2)" +APP_LIBS="$("$PKG_CFG" --libs x11 xext xft xinerama xrandr xtst cairo pangocairo pango harfbuzz fontconfig freetype2) -lm" + +TOUCHD_CFLAGS="$("$PKG_CFG" --cflags x11 xi xtst)" +TOUCHD_LIBS="$("$PKG_CFG" --libs x11 xi xtst) -lm" + +STATUSD_CFLAGS="$("$PKG_CFG" --cflags x11)" +STATUSD_LIBS="$("$PKG_CFG" --libs x11)" + +POWERD_CFLAGS="$POWERD_DEFS $("$PKG_CFG" --cflags $POWERD_PKGS)" +POWERD_LIBS="$("$PKG_CFG" --libs $POWERD_PKGS)" + +# Probe gtkTtk dependencies (gtk+-2.0, x11, tcl, tk, ttkTheme.h) +GTKTTK_AVAILABLE="0" +GTKTTK_REASON="disabled via WITH_GTKTTK=0" +GTKTTK_CXXFLAGS="" +GTKTTK_LDFLAGS="" + +if [ "$WITH_GTKTTK" != "0" ]; then + GTKTTK_REASON="" + if ! "$PKG_CFG" --exists gtk+-2.0 x11 2>/dev/null; then + GTKTTK_REASON="gtk+-2.0 development headers not found" + else + GTK2_C="$("$PKG_CFG" --cflags gtk+-2.0 x11)" + GTK2_L="$("$PKG_CFG" --libs gtk+-2.0 x11)" + TCL_C="" + TCL_L="" + + for tclmod in tcl tcl8.6 tcl86; do + if "$PKG_CFG" --exists "$tclmod" 2>/dev/null; then + TCL_C="$("$PKG_CFG" --cflags "$tclmod")" + break + fi + done + for tkmod in tk tk8.6 tk86; do + if "$PKG_CFG" --exists "$tkmod" 2>/dev/null; then + TCL_C="$TCL_C $("$PKG_CFG" --cflags "$tkmod")" + break + fi + done + + for incdir in \ + /usr/include \ + /usr/include/tcl8.6 \ + /usr/include/tk8.6 \ + /usr/include/tk8.6/tk-private/generic/ttk \ + /usr/include/tk/tk-private/generic/ttk \ + /usr/local/include \ + /usr/local/include/tcl8.6 \ + /usr/local/include/tk8.6 \ + /usr/local/include/tk8.6/generic/ttk \ + /usr/pkg/include \ + /usr/pkg/include/tcl \ + /usr/pkg/include/tk + do + if [ -d "$incdir" ]; then + if [ -f "$incdir/tcl.h" ] || [ -f "$incdir/tk.h" ] || [ -f "$incdir/ttkTheme.h" ]; then + TCL_C="$TCL_C -I$incdir" + fi + fi + done + + for stubver in 8.6 86 8.7 ""; do + for libdir in /usr/lib /usr/lib64 /usr/local/lib /usr/pkg/lib; do + if [ -d "$libdir" ]; then + : + fi + done + if [ -n "$stubver" ]; then + CAND_L="-ltclstub${stubver} -ltkstub${stubver}" + else + CAND_L="-ltclstub -ltkstub" + fi + cat > "$TMP_DIR/gtkttk_probe.cpp" <<'EOF' +#include +#include "ttkTheme.h" +#include +int probe_fn(void) { return 0; } +EOF + if "$CXX_BIN" -shared -fPIC -DUSE_TCL_STUBS -DUSE_TK_STUBS -DUSE_TTK_STUBS \ + $GTK2_C $TCL_C "$TMP_DIR/gtkttk_probe.cpp" \ + $CAND_L $GTK2_L -o "$TMP_DIR/gtkttk_probe.so" >/dev/null 2>&1; then + GTKTTK_AVAILABLE="1" + GTKTTK_CXXFLAGS="$GTK2_C $TCL_C" + GTKTTK_LDFLAGS="$CAND_L $GTK2_L" + break + fi + done + + if [ "$GTKTTK_AVAILABLE" != "1" ]; then + GTKTTK_REASON="Tcl/Tk stub libraries or ttkTheme.h not found" + fi + fi +fi + +escape_sh() { + printf '%s' "$1" | sed "s/'/'\\\\''/g" +} + +TMP_OUT="${OUT_FILE}.tmp.$$" +{ + printf '# Auto-generated by scripts/detect-env.sh (%s)\n' "$OS_NAME" + printf "OS_NAME='%s'\n" "$(escape_sh "$OS_NAME")" + printf "DWM_CFLAGS='%s'\n" "$(escape_sh "$DWM_CFLAGS")" + printf "DWM_LIBS='%s'\n" "$(escape_sh "$DWM_LIBS")" + printf "DMENU_CFLAGS='%s'\n" "$(escape_sh "$DMENU_CFLAGS")" + printf "DMENU_LIBS='%s'\n" "$(escape_sh "$DMENU_LIBS")" + printf "ST_CFLAGS='%s'\n" "$(escape_sh "$ST_CFLAGS")" + printf "ST_LIBS='%s'\n" "$(escape_sh "$ST_LIBS")" + printf "GEMUI_CFLAGS='%s'\n" "$(escape_sh "$GEMUI_CFLAGS")" + printf "GEMUI_LIBS='%s'\n" "$(escape_sh "$GEMUI_LIBS")" + printf "APP_CFLAGS='%s'\n" "$(escape_sh "$APP_CFLAGS")" + printf "APP_LIBS='%s'\n" "$(escape_sh "$APP_LIBS")" + printf "TOUCHD_CFLAGS='%s'\n" "$(escape_sh "$TOUCHD_CFLAGS")" + printf "TOUCHD_LIBS='%s'\n" "$(escape_sh "$TOUCHD_LIBS")" + printf "STATUSD_CFLAGS='%s'\n" "$(escape_sh "$STATUSD_CFLAGS")" + printf "STATUSD_LIBS='%s'\n" "$(escape_sh "$STATUSD_LIBS")" + printf "POWERD_CFLAGS='%s'\n" "$(escape_sh "$POWERD_CFLAGS")" + printf "POWERD_LIBS='%s'\n" "$(escape_sh "$POWERD_LIBS")" + printf "CHECKPW_DEFS='%s'\n" "$(escape_sh "$CHECKPW_DEFS")" + printf "CHECKPW_LIBS='%s'\n" "$(escape_sh "$CHECKPW_LIBS")" + printf "GTKTTK_AVAILABLE='%s'\n" "$(escape_sh "$GTKTTK_AVAILABLE")" + printf "GTKTTK_REASON='%s'\n" "$(escape_sh "$GTKTTK_REASON")" + printf "GTKTTK_CXXFLAGS='%s'\n" "$(escape_sh "$GTKTTK_CXXFLAGS")" + printf "GTKTTK_LDFLAGS='%s'\n" "$(escape_sh "$GTKTTK_LDFLAGS")" +} > "$TMP_OUT" +mv -f "$TMP_OUT" "$OUT_FILE" diff --git a/src/apps/anode-audio.c b/src/apps/anode-audio.c new file mode 100644 index 0000000..3418f8b --- /dev/null +++ b/src/apps/anode-audio.c @@ -0,0 +1,275 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" +#include "anode_audio_parse.h" + +#include +#include +#include +#include + +typedef struct { + gemui_app_t *app; + anode_audio_backend_t backend; + int tab; /* 0=Outputs, 1=Inputs, 2=Profiles, 3=Streams */ + anode_audio_node_t sinks[ANODE_MAX_AUDIO_NODES]; + int n_sinks; + anode_audio_node_t srcs[ANODE_MAX_AUDIO_NODES]; + int n_srcs; + anode_audio_node_t streams[ANODE_MAX_AUDIO_NODES]; + int n_streams; + anode_audio_profile_t profs[ANODE_MAX_AUDIO_PROFILES]; + int n_profs; + int master_vol; + bool master_muted; + int sel_idx; +} audio_state_t; + +enum { + HIT_TAB = 1, + HIT_SLIDER, + HIT_MUTE, + HIT_ROW, + HIT_TEST, + HIT_REFRESH, + HIT_QUIT +}; + +static void reload_audio(audio_state_t *st) { + st->backend = anode_detect_audio_backend(); + if (!anode_audio_get_default(st->tab == 1, &st->master_vol, &st->master_muted)) { + st->master_vol = 50; + st->master_muted = false; + } + + st->n_sinks = st->n_srcs = st->n_streams = st->n_profs = 0; + + if (anode_have_cmd("pactl")) { + char info[1024] = {0}, out[16384] = {0}; + char def_sink[128] = {0}, def_src[128] = {0}; + const char *c_info[] = {"pactl", "info", NULL}; + if (anode_run_cmd_timeout(c_info, info, sizeof(info), 1500) == 0) { + anode_parse_pactl_defaults(info, def_sink, sizeof(def_sink), def_src, sizeof(def_src)); + } + const char *c_sinks[] = {"pactl", "list", "sinks", NULL}; + if (anode_run_cmd_timeout(c_sinks, out, sizeof(out), 2000) == 0) { + st->n_sinks = anode_parse_pactl_nodes(out, "Sink #", def_sink, false, st->sinks, ANODE_MAX_AUDIO_NODES); + } + const char *c_srcs[] = {"pactl", "list", "sources", NULL}; + if (anode_run_cmd_timeout(c_srcs, out, sizeof(out), 2000) == 0) { + st->n_srcs = anode_parse_pactl_nodes(out, "Source #", def_src, false, st->srcs, ANODE_MAX_AUDIO_NODES); + } + const char *c_str[] = {"pactl", "list", "sink-inputs", NULL}; + if (anode_run_cmd_timeout(c_str, out, sizeof(out), 2000) == 0) { + st->n_streams = anode_parse_pactl_nodes(out, "Sink Input #", NULL, true, st->streams, ANODE_MAX_AUDIO_NODES); + } + const char *c_cards[] = {"pactl", "list", "cards", NULL}; + if (anode_run_cmd_timeout(c_cards, out, sizeof(out), 2000) == 0) { + st->n_profs = anode_parse_pactl_cards(out, st->profs, ANODE_MAX_AUDIO_PROFILES); + } + } else if (st->backend == ANODE_AUDIO_ALSA && anode_have_cmd("amixer")) { + char out[4096] = {0}; + const char *c_am[] = {"amixer", "scontrols", NULL}; + if (anode_run_cmd_timeout(c_am, out, sizeof(out), 1500) == 0) { + st->n_sinks = anode_parse_amixer_scontrols(out, st->sinks, ANODE_MAX_AUDIO_NODES); + } + } else if (st->backend == ANODE_AUDIO_SNDIO && anode_have_cmd("sndioctl")) { + char out[4096] = {0}; + const char *c_sn[] = {"sndioctl", NULL}; + if (anode_run_cmd_timeout(c_sn, out, sizeof(out), 1500) == 0) { + st->n_sinks = anode_parse_sndioctl(out, false, st->sinks, ANODE_MAX_AUDIO_NODES); + st->n_srcs = anode_parse_sndioctl(out, true, st->srcs, ANODE_MAX_AUDIO_NODES); + } + } +} + +static void notify_statusd(void) { + const char *names[] = {"anode-statusd"}; + anode_signal_procs(names, 1, SIGUSR1); +} + +static int tab_count(const audio_state_t *st) { + if (st->tab == 0) return st->n_sinks; + if (st->tab == 1) return st->n_srcs; + if (st->tab == 2) return st->n_profs; + return st->n_streams; +} + +static void activate_row(audio_state_t *st, int idx) { + if (st->tab == 0 && idx < st->n_sinks) { + if (anode_have_cmd("pactl")) { + const char *av[] = {"pactl", "set-default-sink", st->sinks[idx].name, NULL}; + anode_run_cmd_timeout(av, NULL, 0, 1500); + } + gemui_show_toast(st->app, "Default output updated", 1500); + } else if (st->tab == 1 && idx < st->n_srcs) { + if (anode_have_cmd("pactl")) { + const char *av[] = {"pactl", "set-default-source", st->srcs[idx].name, NULL}; + anode_run_cmd_timeout(av, NULL, 0, 1500); + } + gemui_show_toast(st->app, "Default input updated", 1500); + } else if (st->tab == 2 && idx < st->n_profs && anode_have_cmd("pactl")) { + const char *av[] = {"pactl", "set-card-profile", st->profs[idx].card_name, st->profs[idx].profile_name, NULL}; + anode_run_cmd_timeout(av, NULL, 0, 2000); + gemui_show_toast(st->app, "Card profile updated", 1500); + } + reload_audio(st); + notify_statusd(); + gemui_request_redraw(st->app); +} + +static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { + audio_state_t *st = (audio_state_t *)ud; + const gemui_theme_t *t = gemui_theme(app); + char badge[64]; + snprintf(badge, sizeof(badge), "Backend: %s", anode_audio_backend_name(st->backend)); + gemui_draw_header(app, cr, NULL, "ANODE Audio & Mixer", badge); + + int pad = gemui_scale_px(app, 12); + int y = gemui_scale_px(app, 42) + pad; + int cw = w - pad * 2; + int tab_h = gemui_touch_row_px(app, 32); + + static const char *TABS[4] = {"Outputs", "Inputs", "Profiles", "Streams"}; + int tw = (cw - pad * 3) / 4; + for (int i = 0; i < 4; i++) { + gemui_draw_button(app, cr, (gemui_rect_t){pad + i * (tw + pad), y, tw, tab_h}, + TABS[i], HIT_TAB, i, false, i == st->tab, false); + } + y += tab_h + pad; + + int sli_h = gemui_touch_row_px(app, 50); + int mute_w = gemui_scale_px(app, 96); + char vtxt[32]; + snprintf(vtxt, sizeof(vtxt), "%d%%%s", st->master_vol, st->master_muted ? " (Muted)" : ""); + gemui_draw_slider(app, cr, (gemui_rect_t){pad, y, cw - mute_w - pad / 2, sli_h}, + st->tab == 1 ? "Input Gain" : "Master Volume", + (double)st->master_vol / 100.0, vtxt, HIT_SLIDER, 0, false); + gemui_draw_button(app, cr, (gemui_rect_t){pad + cw - mute_w, y, mute_w, sli_h}, + st->master_muted ? "Unmute" : "Mute", HIT_MUTE, 0, false, st->master_muted, false); + y += sli_h + pad; + + int ftr_h = tab_h + pad; + int list_h = h - y - ftr_h - pad; + gemui_rect_t lr = {pad, y, cw, list_h}; + gemui_fill_round(cr, lr, (double)gemui_scale_px(app, 6), t->bg_alt_even); + gemui_stroke_round(cr, lr, (double)gemui_scale_px(app, 6), 1.0, t->border); + + int cnt = tab_count(st); + int row_h = gemui_touch_row_px(app, 34); + if (cnt == 0) { + gemui_draw_text(cr, t, lr, "No entries reported by current audio backend", + 0, false, GEMUI_ALIGN_CENTER, t->fg_muted); + } else { + int max_r = (list_h - pad) / row_h; + for (int i = 0; i < cnt && i < max_r; i++) { + gemui_rect_t rr = {lr.x + pad / 2, lr.y + pad / 2 + i * row_h, lr.w - pad, row_h - 4}; + bool sel = (i == st->sel_idx); + bool act = false; + char line[256] = {0}; + if (st->tab == 0) { + act = st->sinks[i].is_default; + snprintf(line, sizeof(line), "%s%s (%d%%%s)", + act ? "* " : " ", st->sinks[i].label[0] ? st->sinks[i].label : st->sinks[i].name, + st->sinks[i].vol_pct, st->sinks[i].muted ? " Muted" : ""); + } else if (st->tab == 1) { + act = st->srcs[i].is_default; + snprintf(line, sizeof(line), "%s%s (%d%%%s)", + act ? "* " : " ", st->srcs[i].label[0] ? st->srcs[i].label : st->srcs[i].name, + st->srcs[i].vol_pct, st->srcs[i].muted ? " Muted" : ""); + } else if (st->tab == 2) { + act = st->profs[i].active; + snprintf(line, sizeof(line), "%s%s: %s", + act ? "* " : " ", st->profs[i].card_label, st->profs[i].profile_desc); + } else { + snprintf(line, sizeof(line), " #%d %s (%d%%)", + st->streams[i].index, st->streams[i].label, st->streams[i].vol_pct); + } + if (sel) gemui_fill_round(cr, rr, (double)gemui_scale_px(app, 5), t->sel_bg); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 8, rr.y, rr.w - 16, rr.h}, + line, 0, sel || act, GEMUI_ALIGN_LEFT, sel ? t->sel_fg : t->fg_main); + gemui_hit_add(app, rr, HIT_ROW, i); + } + } + + int fy = h - tab_h - pad; + int bw = gemui_scale_px(app, 110); + gemui_draw_button(app, cr, (gemui_rect_t){pad, fy, bw, tab_h}, "Test", HIT_TEST, 0, false, false, false); + gemui_draw_button(app, cr, (gemui_rect_t){w - pad * 2 - bw * 2, fy, bw, tab_h}, "Refresh", HIT_REFRESH, 0, false, false, false); + gemui_draw_button(app, cr, (gemui_rect_t){w - pad - bw, fy, bw, tab_h}, "Close", HIT_QUIT, 0, false, false, false); +} + +static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) { + (void)state; + (void)utf8; + audio_state_t *st = (audio_state_t *)ud; + int cnt = tab_count(st); + if (ks == XK_Escape || ks == XK_q) gemui_quit(app, 0); + else if (ks == XK_Tab) { st->tab = (st->tab + 1) % 4; st->sel_idx = 0; reload_audio(st); gemui_request_redraw(app); } + else if (ks == XK_Down || ks == XK_j) { if (st->sel_idx + 1 < cnt) st->sel_idx++; gemui_request_redraw(app); } + else if (ks == XK_Up || ks == XK_k) { if (st->sel_idx > 0) st->sel_idx--; gemui_request_redraw(app); } + else if (ks == XK_Left || ks == XK_h) { + int nv = st->master_vol - 5; if (nv < 0) nv = 0; + anode_audio_set_vol(st->tab == 1, nv); + reload_audio(st); notify_statusd(); gemui_request_redraw(app); + } else if (ks == XK_Right || ks == XK_l) { + int nv = st->master_vol + 5; if (nv > 100) nv = 100; + anode_audio_set_vol(st->tab == 1, nv); + reload_audio(st); notify_statusd(); gemui_request_redraw(app); + } else if (ks == XK_m) { + anode_audio_toggle_mute(st->tab == 1); + reload_audio(st); notify_statusd(); gemui_request_redraw(app); + } else if (ks == XK_Return || ks == XK_space) { + activate_row(st, st->sel_idx); + } else if (ks == XK_r) { + reload_audio(st); gemui_request_redraw(app); + } +} + +static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { + audio_state_t *st = (audio_state_t *)ud; + 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_TAB) { + st->tab = hit->val; st->sel_idx = 0; reload_audio(st); + } else if (hit->id == HIT_SLIDER) { + int pct = ((x - hit->r.x) * 100) / (hit->r.w > 0 ? hit->r.w : 1); + if (pct < 0) pct = 0; + if (pct > 100) pct = 100; + anode_audio_set_vol(st->tab == 1, pct); + reload_audio(st); notify_statusd(); + } else if (hit->id == HIT_MUTE) { + anode_audio_toggle_mute(st->tab == 1); + reload_audio(st); notify_statusd(); + } else if (hit->id == HIT_ROW) { + if (st->sel_idx == hit->val) activate_row(st, hit->val); + else st->sel_idx = hit->val; + } else if (hit->id == HIT_TEST) { + if (anode_have_cmd("speaker-test")) { + const char *av[] = {"speaker-test", "-c", "2", "-t", "sine", "-l", "1", NULL}; + anode_spawn_detached(av); + gemui_show_toast(app, "Playing test tone...", 1500); + } else { + gemui_show_toast(app, "speaker-test not installed", 1500); + } + } else if (hit->id == HIT_REFRESH) { + reload_audio(st); + } else if (hit->id == HIT_QUIT) { + gemui_quit(app, 0); + } + gemui_request_redraw(app); +} + +int main(void) { + audio_state_t st; + memset(&st, 0, sizeof(st)); + st.app = gemui_create("anode-audio", "ANODE Audio", 800, 520, false); + if (!st.app) return 1; + reload_audio(&st); + 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); + gemui_destroy(st.app); + return rc; +} diff --git a/src/apps/anode-datetime.c b/src/apps/anode-datetime.c new file mode 100644 index 0000000..fe191a3 --- /dev/null +++ b/src/apps/anode-datetime.c @@ -0,0 +1,259 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" +#include "anode_tz_valid.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_ZONES 600 + +typedef struct { + gemui_app_t *app; + char zones[MAX_ZONES][96]; + int total_zones; + int filtered[MAX_ZONES]; + int n_filt; + int sel; + int scroll; + char filter[64]; + char cur_tz[96]; + char ntp_status[128]; +} dt_state_t; + +enum { HIT_INPUT = 1, HIT_ROW, HIT_APPLY, HIT_NTP, HIT_QUIT }; + +static const char *zoneinfo_root(void) { + if (access("/usr/share/zoneinfo", R_OK | X_OK) == 0) return "/usr/share/zoneinfo"; + if (access("/usr/lib/zoneinfo", R_OK | X_OK) == 0) return "/usr/lib/zoneinfo"; + return "/usr/share/zoneinfo"; +} + +static void walk_zones(dt_state_t *st, const char *root, const char *sub) { + if (st->total_zones >= MAX_ZONES) return; + char dirpath[512]; + if (sub && sub[0]) snprintf(dirpath, sizeof(dirpath), "%s/%s", root, sub); + else snprintf(dirpath, sizeof(dirpath), "%s", root); + DIR *d = opendir(dirpath); + if (!d) return; + struct dirent *de; + while ((de = readdir(d)) != NULL && st->total_zones < MAX_ZONES) { + if (de->d_name[0] == '.') continue; + if (strcmp(de->d_name, "posix") == 0 || strcmp(de->d_name, "right") == 0 || + strcmp(de->d_name, "Etc") == 0) continue; + char rel[384]; + if (sub && sub[0]) snprintf(rel, sizeof(rel), "%.120s/%.250s", sub, de->d_name); + else snprintf(rel, sizeof(rel), "%.255s", de->d_name); + char full[1024]; + snprintf(full, sizeof(full), "%.511s/%.383s", root, rel); + struct stat sb; + if (lstat(full, &sb) != 0) continue; + if (S_ISDIR(sb.st_mode)) { + walk_zones(st, root, rel); + } else if (S_ISREG(sb.st_mode) && anode_tz_file_valid(root, rel)) { + snprintf(st->zones[st->total_zones++], 96, "%.95s", rel); + } + } + closedir(d); +} + +static int cmp_str(const void *a, const void *b) { + return strcmp((const char *)a, (const char *)b); +} + +static bool ci_contains(const char *hay, const char *needle) { + if (!needle || !needle[0]) return true; + size_t nlen = strlen(needle); + for (size_t i = 0; hay[i]; i++) { + size_t j = 0; + while (j < nlen && hay[i + j] && + tolower((unsigned char)hay[i + j]) == tolower((unsigned char)needle[j])) { + j++; + } + if (j == nlen) return true; + } + return false; +} + +static void apply_filter(dt_state_t *st) { + st->n_filt = 0; + for (int i = 0; i < st->total_zones; i++) { + if (ci_contains(st->zones[i], st->filter)) { + st->filtered[st->n_filt++] = i; + } + } + st->sel = 0; + st->scroll = 0; +} + +static void refresh_dt(dt_state_t *st) { + char out[256] = {0}; + const char *c_get[] = {"anode-tzctl", "get", NULL}; + if (anode_run_cmd_timeout(c_get, out, sizeof(out), 1000) == 0 && out[0]) { + size_t l = strlen(out); + while (l > 0 && (out[l - 1] == '\n' || out[l - 1] == '\r')) out[--l] = '\0'; + snprintf(st->cur_tz, sizeof(st->cur_tz), "%s", out); + } else { + const char *tz = getenv("TZ"); + snprintf(st->cur_tz, sizeof(st->cur_tz), "%s", (tz && tz[0]) ? tz : "UTC"); + } + + if (anode_have_cmd("chronyc")) { + const char *c_ch[] = {"chronyc", "tracking", NULL}; + if (anode_run_cmd_timeout(c_ch, out, sizeof(out), 1500) == 0) { + snprintf(st->ntp_status, sizeof(st->ntp_status), "NTP synced (chrony)"); + return; + } + } + if (anode_have_cmd("timedatectl")) { + const char *c_td[] = {"timedatectl", "show", "-p", "NTPSynchronized", "--value", NULL}; + if (anode_run_cmd_timeout(c_td, out, sizeof(out), 1500) == 0 && strstr(out, "yes")) { + snprintf(st->ntp_status, sizeof(st->ntp_status), "NTP synced (systemd-timesyncd)"); + return; + } + } + snprintf(st->ntp_status, sizeof(st->ntp_status), "Local clock (%s)", st->cur_tz); +} + +static void apply_tz(dt_state_t *st) { + if (st->sel < 0 || st->sel >= st->n_filt) return; + const char *tz = st->zones[st->filtered[st->sel]]; + const char *av[] = {"anode-tzctl", "set", tz, NULL}; + if (anode_run_priv_timeout(av, NULL, 0, 3000) == 0) { + setenv("TZ", tz, 1); + tzset(); + refresh_dt(st); + gemui_show_toast(st->app, tz, 1800); + } else { + gemui_show_toast(st->app, "Privilege escalation required for timezone", 2200); + } + gemui_request_redraw(st->app); +} + +static void on_timer(gemui_app_t *app, void *ud) { + (void)ud; + gemui_request_redraw(app); +} + +static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { + dt_state_t *st = (dt_state_t *)ud; + const gemui_theme_t *t = gemui_theme(app); + + time_t now = time(NULL); + struct tm tmb; + localtime_r(&now, &tmb); + char clk[64]; + strftime(clk, sizeof(clk), "%Y-%m-%d %H:%M:%S", &tmb); + gemui_draw_header(app, cr, NULL, "ANODE Date & Timezone", clk); + + int pad = gemui_scale_px(app, 12); + int y = gemui_scale_px(app, 42) + pad; + int cw = w - pad * 2; + int row_h = gemui_touch_row_px(app, 34); + + gemui_draw_text(cr, t, (gemui_rect_t){pad, y, cw, gemui_scale_px(app, 24)}, + st->ntp_status, -1, false, GEMUI_ALIGN_LEFT, t->accent); + y += gemui_scale_px(app, 28); + + gemui_draw_input(app, cr, (gemui_rect_t){pad, y, cw, row_h}, + "Filter timezone (e.g. Europe, America, Tokyo)...", st->filter, false, true, HIT_INPUT, 0); + y += row_h + pad; + + int list_h = h - y - row_h - pad * 2; + gemui_rect_t lr = {pad, y, cw, list_h}; + gemui_fill_round(cr, lr, (double)gemui_scale_px(app, 6), t->bg_alt_even); + gemui_stroke_round(cr, lr, (double)gemui_scale_px(app, 6), 1.0, t->border); + + int vis = (list_h - pad) / row_h; + if (vis < 1) vis = 1; + if (st->sel < st->scroll) st->scroll = st->sel; + if (st->sel >= st->scroll + vis) st->scroll = st->sel - vis + 1; + + for (int i = 0; i < vis && (st->scroll + i) < st->n_filt; i++) { + int idx = st->scroll + i; + const char *z = st->zones[st->filtered[idx]]; + bool is_sel = (idx == st->sel); + bool is_cur = (strcmp(z, st->cur_tz) == 0); + gemui_rect_t rr = {lr.x + pad / 2, lr.y + pad / 2 + i * row_h, lr.w - pad, row_h - 4}; + if (is_sel) gemui_fill_round(cr, rr, (double)gemui_scale_px(app, 5), t->sel_bg); + char lbl[128]; + snprintf(lbl, sizeof(lbl), "%s%s", is_cur ? "* " : " ", z); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 8, rr.y, rr.w - 16, rr.h}, + lbl, 0, is_sel || is_cur, GEMUI_ALIGN_LEFT, is_sel ? t->sel_fg : t->fg_main); + gemui_hit_add(app, rr, HIT_ROW, idx); + } + + int fy = h - row_h - pad; + int bw = gemui_scale_px(app, 120); + gemui_draw_button(app, cr, (gemui_rect_t){pad, fy, bw, row_h}, "Sync NTP", HIT_NTP, 0, false, false, false); + gemui_draw_button(app, cr, (gemui_rect_t){w - pad * 2 - bw * 2, fy, bw, row_h}, "Set Zone", HIT_APPLY, 0, true, false, false); + gemui_draw_button(app, cr, (gemui_rect_t){w - pad - bw, fy, bw, row_h}, "Close", HIT_QUIT, 0, false, false, false); +} + +static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) { + (void)state; + dt_state_t *st = (dt_state_t *)ud; + if (ks == XK_Escape) { gemui_quit(app, 0); return; } + if (ks == XK_Down) { if (st->sel + 1 < st->n_filt) st->sel++; gemui_request_redraw(app); } + else if (ks == XK_Up) { if (st->sel > 0) st->sel--; gemui_request_redraw(app); } + else if (ks == XK_Return) { apply_tz(st); } + else if (ks == XK_BackSpace) { gemui_utf8_pop_char(st->filter); apply_filter(st); gemui_request_redraw(app); } + else if (utf8 && utf8[0]) { + size_t cl = strlen(st->filter), al = strlen(utf8); + if (cl + al + 1 < sizeof(st->filter)) { + memcpy(st->filter + cl, utf8, al); + st->filter[cl + al] = '\0'; + apply_filter(st); + gemui_request_redraw(app); + } + } +} + +static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { + dt_state_t *st = (dt_state_t *)ud; + if (type == GEMUI_PTR_SCROLL_UP) { if (st->sel > 0) st->sel--; gemui_request_redraw(app); return; } + if (type == GEMUI_PTR_SCROLL_DOWN) { if (st->sel + 1 < st->n_filt) st->sel++; 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_ROW) { + if (st->sel == hit->val) apply_tz(st); + else { st->sel = hit->val; gemui_request_redraw(app); } + } else if (hit->id == HIT_APPLY) { + apply_tz(st); + } else if (hit->id == HIT_NTP) { + if (anode_have_cmd("chronyc")) { + const char *av[] = {"chronyc", "makestep", NULL}; + anode_run_priv_timeout(av, NULL, 0, 3000); + gemui_show_toast(app, "NTP step requested", 1600); + } + refresh_dt(st); + gemui_request_redraw(app); + } else if (hit->id == HIT_QUIT) { + gemui_quit(app, 0); + } +} + +int main(void) { + dt_state_t *st = calloc(1, sizeof(*st)); + if (!st) return 1; + st->app = gemui_create("anode-datetime", "ANODE Date & Time", 760, 520, false); + if (!st->app) { free(st); return 1; } + walk_zones(st, zoneinfo_root(), ""); + if (st->total_zones > 1) qsort(st->zones, (size_t)st->total_zones, 96, cmp_str); + apply_filter(st); + refresh_dt(st); + gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr }; + gemui_set_handlers(st->app, &h, st); + gemui_set_timer_ms(st->app, 1000, on_timer, st); + int rc = gemui_run(st->app); + gemui_destroy(st->app); + free(st); + return rc; +} diff --git a/src/apps/anode-display.c b/src/apps/anode-display.c new file mode 100644 index 0000000..8fee7e9 --- /dev/null +++ b/src/apps/anode-display.c @@ -0,0 +1,319 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" +#include "anode_scale.h" + +#include +#include +#include +#include + +#define MAX_OUTPUTS 8 +#define MAX_MODES 24 + +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; + +typedef struct { + gemui_app_t *app; + out_info_t outs[MAX_OUTPUTS]; + int n_outs; + int sel_out; + int sel_mode; + double scale; + bool touch_mode; + int bri_pct; +} disp_state_t; + +enum { + HIT_OUT = 1, + HIT_MODE, + HIT_ROT, + HIT_SCALE_PRESET, + HIT_SCALE_STEP, + HIT_TOUCH, + HIT_BRI, + HIT_APPLY_MODE, + 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 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; + + 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); + } + } + + 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; + } + } + 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; + } + } + } + XRRFreeOutputInfo(oi); + } + XRRFreeScreenResources(res); + + double dpi = 96.0, sc = 1.0; + int tm = 0; + anode_read_xres_scale(dpy, &dpi, &sc, &tm); + st->scale = sc; + st->touch_mode = (tm != 0); + + int bcur = 50, bmax = 100; + if (anode_backlight_get(&bcur, &bmax, NULL, 0) && bmax > 0) { + st->bri_pct = (bcur * 100 + bmax / 2) / bmax; + } else { + st->bri_pct = 100; + } +} + +static void apply_scale_now(disp_state_t *st, const char *scale_arg, int touch_override) { + char sbuf[16], tbuf[16]; + snprintf(sbuf, sizeof(sbuf), "%s", scale_arg); + int t = (touch_override >= 0) ? touch_override : (st->touch_mode ? 1 : 0); + snprintf(tbuf, sizeof(tbuf), "--touch=%d", t); + const char *av[] = {"anode-apply-scale", sbuf, tbuf, NULL}; + if (anode_run_cmd_timeout(av, NULL, 0, 5000) == 0) { + gemui_theme_reload(st->app); + const gemui_theme_t *th = gemui_theme(st->app); + st->scale = th ? th->scale : st->scale; + st->touch_mode = th ? th->touch_mode : (t != 0); + gemui_show_toast(st->app, "Display scale updated", 1800); + } else { + gemui_show_toast(st->app, "Scale update failed", 2000); + } + 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); + } + gemui_request_redraw(st->app); +} + +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 & Fractional Scaling", badge); + + 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); + + /* 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); + } + y += btn_h + pad; + } + + /* Scale presets grid (2 rows of 4 + Auto & -/+ steps) */ + int pw = (cw - pad * 3) / 4; + for (int i = 0; i < 8; i++) { + int r = i / 4, c = i % 4; + 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}, + 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); + y += btn_h + pad; + + /* Touch & Virtual Keyboard toggle */ + gemui_draw_toggle(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); + char btxt[24]; + snprintf(btxt, sizeof(btxt), "%d%%", st->bri_pct); + gemui_draw_slider(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; + + 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); + } + } + + /* Footer */ + int bw = gemui_scale_px(app, 140); + 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}, + "Close", HIT_QUIT, 0, false, false, false); +} + +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) { + 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) { + char b[16]; snprintf(b, sizeof(b), "%.2f", anode_clamp_scale(st->scale - 0.05)); + apply_scale_now(st, b, -1); + } +} + +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_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; + gemui_request_redraw(app); + } else if (hit->id == HIT_SCALE_PRESET) { + char b[16]; snprintf(b, sizeof(b), "%.2f", PRESETS[hit->val]); + apply_scale_now(st, b, -1); + } else if (hit->id == HIT_SCALE_STEP) { + if (hit->val == 0) apply_scale_now(st, "auto", -1); + else { + char b[16]; snprintf(b, sizeof(b), "%.2f", anode_clamp_scale(st->scale + (hit->val > 0 ? 0.05 : -0.05))); + apply_scale_now(st, b, -1); + } + } else if (hit->id == HIT_TOUCH) { + 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) { + 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 (hit->id == HIT_QUIT) { + gemui_quit(app, 0); + } +} + +int main(void) { + disp_state_t st; + memset(&st, 0, sizeof(st)); + st.app = gemui_create("anode-display", "ANODE Display & Scaling", 840, 560, false); + if (!st.app) return 1; + scan_outputs(&st); + 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); + gemui_destroy(st.app); + return rc; +} diff --git a/src/apps/anode-lock.c b/src/apps/anode-lock.c new file mode 100644 index 0000000..89f362c --- /dev/null +++ b/src/apps/anode-lock.c @@ -0,0 +1,205 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +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 }; + +static void wipe_str(char *s, size_t n) { + volatile char *p = (volatile char *)s; + while (n--) *p++ = '\0'; +} + +static bool verify_password(const char *user, const char *pw) { + if (!pw || !pw[0]) return false; + int pfd[2]; + if (pipe(pfd) != 0) return false; + + pid_t pid = fork(); + if (pid < 0) { + close(pfd[0]); + close(pfd[1]); + return false; + } + if (pid == 0) { + close(pfd[1]); + dup2(pfd[0], STDIN_FILENO); + if (pfd[0] > 2) close(pfd[0]); + const char *av[] = {"anode-checkpw", user, NULL}; + execvp(av[0], (char *const *)av); + _exit(127); + } + close(pfd[0]); + size_t plen = strlen(pw); + ssize_t u1 = write(pfd[1], pw, plen); + ssize_t u2 = write(pfd[1], "\n", 1); + (void)u1; + (void)u2; + close(pfd[1]); + + int status = 0; + while (waitpid(pid, &status, 0) < 0) { + if (errno != EINTR) return false; + } + return WIFEXITED(status) && WEXITSTATUS(status) == 0; +} + +static void try_unlock(lock_state_t *st) { + if (!st->pw[0]) { + snprintf(st->msg, sizeof(st->msg), "Enter password"); + gemui_request_redraw(st->app); + return; + } + if (verify_password(st->user, st->pw)) { + wipe_str(st->pw, sizeof(st->pw)); + gemui_ungrab_input(st->app); + gemui_quit(st->app, 0); + } else { + wipe_str(st->pw, sizeof(st->pw)); + snprintf(st->msg, sizeof(st->msg), "Authentication failed"); + gemui_request_redraw(st->app); + } +} + +static void on_timer(gemui_app_t *app, void *ud) { + lock_state_t *st = (lock_state_t *)ud; + anode_read_battery(&st->bat); + 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); + + 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_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); + + time_t now = time(NULL); + struct tm tmb; + 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); + + 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)}, + cstr, 10, true, GEMUI_ALIGN_CENTER, t->fg_bright); + y += gemui_scale_px(app, 40); + + 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); + + 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); + + 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)}, + st->msg, -1, false, GEMUI_ALIGN_CENTER, t->danger); + } + y += gemui_scale_px(app, 28); + + 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); + gemui_draw_button(app, cr, (gemui_rect_t){card.x + pad * 2 + half, y, half, btn_h}, + "Unlock", HIT_UNLOCK, 0, true, false, true); +} + +static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) { + (void)app; + (void)state; + lock_state_t *st = (lock_state_t *)ud; + if (ks == XK_Return || ks == XK_KP_Enter) { + try_unlock(st); + } else if (ks == XK_BackSpace) { + gemui_utf8_pop_char(st->pw); + gemui_request_redraw(st->app); + } else if (ks == XK_Escape) { + wipe_str(st->pw, sizeof(st->pw)); + st->msg[0] = '\0'; + gemui_request_redraw(st->app); + } else if (utf8 && utf8[0]) { + size_t cur = strlen(st->pw); + size_t add = strlen(utf8); + if (cur + add + 1 < sizeof(st->pw)) { + memcpy(st->pw + cur, utf8, add); + st->pw[cur + add] = '\0'; + st->msg[0] = '\0'; + gemui_request_redraw(st->app); + } + } +} + +static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { + (void)app; + lock_state_t *st = (lock_state_t *)ud; + if (type != GEMUI_PTR_DOWN || btn != Button1) return; + const gemui_hit_t *hit = gemui_hit_test(st->app, x, y); + if (!hit) return; + if (hit->id == HIT_UNLOCK) try_unlock(st); + else if (hit->id == HIT_VKBD) { + const char *av[] = {"anode-media-key", "vkbd-toggle", NULL}; + anode_spawn_detached(av); + } +} + +int main(void) { + lock_state_t st; + 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; + + gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr }; + gemui_set_handlers(st.app, &h, &st); + gemui_set_timer_ms(st.app, 1000, on_timer, &st); + gemui_flush_draw(st.app); + + for (int i = 0; i < 10; i++) { + if (gemui_grab_input(st.app)) break; + struct timespec ts = { .tv_sec = 0, .tv_nsec = 50000000L }; + nanosleep(&ts, NULL); + } + + int rc = gemui_run(st.app); + wipe_str(st.pw, sizeof(st.pw)); + gemui_destroy(st.app); + return rc; +} diff --git a/src/apps/anode-media-key.c b/src/apps/anode-media-key.c new file mode 100644 index 0000000..a7a59d7 --- /dev/null +++ b/src/apps/anode-media-key.c @@ -0,0 +1,277 @@ +#define _POSIX_C_SOURCE 200809L +#include "anode_plat.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void notify_osd(const char *title, const char *body, int progress) { + if (!anode_have_cmd("notify-send")) return; + char val_buf[32]; + if (progress >= 0) { + if (progress > 100) progress = 100; + snprintf(val_buf, sizeof(val_buf), "int:value:%d", progress); + const char *av[] = { + "notify-send", "-t", "1400", + "-h", "string:x-dunst-stack-tag:anode-osd", + "-h", val_buf, + title, body ? body : "", NULL + }; + anode_spawn_detached(av); + } else { + const char *av[] = { + "notify-send", "-t", "1800", + "-h", "string:x-dunst-stack-tag:anode-osd", + title, body ? body : "", NULL + }; + anode_spawn_detached(av); + } +} + +static void signal_statusd(void) { + const char *names[] = {"anode-statusd"}; + anode_signal_procs(names, 1, SIGUSR1); +} + +static int acquire_media_lock(const char *tag) { + char rdir[256], lpath[320]; + anode_runtime_dir(rdir, sizeof(rdir)); + snprintf(lpath, sizeof(lpath), "%s/anode-media-%s.lock", rdir, tag); + int fd = open(lpath, O_RDWR | O_CREAT, 0600); + if (fd < 0) return -1; + struct flock fl = { .l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = 0 }; + if (fcntl(fd, F_SETLKW, &fl) != 0) { + close(fd); + return -1; + } + return fd; +} + +static void toggle_vkbd(void) { + const char *ps_cmd[] = { + "sh", "-c", + "(ps -eo pid=,comm= 2>/dev/null || ps -ax -o pid=,comm= 2>/dev/null) | " + "awk '{ c=$2; sub(/^.*\\//, \"\", c); if (c == \"anode-vkbd\") print $1 }'", + NULL + }; + char out[128] = {0}; + if (anode_run_cmd_timeout(ps_cmd, out, sizeof(out), 1000) == 0 && out[0]) { + const char *p = out; + bool sent = false; + while (*p) { + long pid = strtol(p, (char **)&p, 10); + if (pid > 1) { + if (kill((pid_t)pid, SIGUSR1) == 0) sent = true; + } + while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; + } + if (sent) return; + } + const char *vk[] = {"anode-vkbd", NULL}; + anode_spawn_detached(vk); +} + +static int handle_volume(const char *action) { + int lfd = acquire_media_lock("audio"); + bool is_mic = (strcmp(action, "mic-mute") == 0); + int vol = 50; + bool muted = false; + anode_audio_get_default(is_mic, &vol, &muted); + + if (strcmp(action, "vol-up") == 0) { + int nv = vol + 5; + if (nv > 100) nv = 100; + anode_audio_set_vol(false, nv); + if (muted) anode_audio_toggle_mute(false); + anode_audio_get_default(false, &vol, &muted); + char msg[64]; + snprintf(msg, sizeof(msg), "Volume: %d%%%s", vol, muted ? " (Muted)" : ""); + notify_osd("Audio", msg, muted ? 0 : vol); + } else if (strcmp(action, "vol-down") == 0) { + int nv = vol - 5; + if (nv < 0) nv = 0; + anode_audio_set_vol(false, nv); + anode_audio_get_default(false, &vol, &muted); + char msg[64]; + snprintf(msg, sizeof(msg), "Volume: %d%%%s", vol, muted ? " (Muted)" : ""); + notify_osd("Audio", msg, muted ? 0 : vol); + } else if (strcmp(action, "vol-mute") == 0) { + anode_audio_toggle_mute(false); + anode_audio_get_default(false, &vol, &muted); + char msg[64]; + snprintf(msg, sizeof(msg), muted ? "Muted (%d%%)" : "Unmuted (%d%%)", vol); + notify_osd("Audio", msg, muted ? 0 : vol); + } else if (is_mic) { + anode_audio_toggle_mute(true); + anode_audio_get_default(true, &vol, &muted); + notify_osd("Microphone", muted ? "Microphone Muted" : "Microphone Live", -1); + } + + signal_statusd(); + if (lfd >= 0) close(lfd); + return 0; +} + +static int handle_brightness(bool up) { + int lfd = acquire_media_lock("bright"); + int cur = 50, maxv = 100; + double norm = 0.5; + if (anode_backlight_get(&cur, &maxv, NULL, 0) && maxv > 0) { + norm = (double)cur / (double)maxv; + } + norm += up ? 0.10 : -0.10; + if (norm < 0.05) norm = 0.05; + if (norm > 1.00) norm = 1.00; + if (!anode_backlight_set(norm) && anode_have_cmd("anode-power-ctl")) { + char pbuf[16]; + snprintf(pbuf, sizeof(pbuf), "%d", (int)(norm * 100.0 + 0.5)); + const char *av[] = {"anode-power-ctl", "backlight", pbuf, NULL}; + anode_run_priv_timeout(av, NULL, 0, 2000); + } + int pct = (int)(norm * 100.0 + 0.5); + char msg[64]; + snprintf(msg, sizeof(msg), "Brightness: %d%%", pct); + notify_osd("Display", msg, pct); + if (lfd >= 0) close(lfd); + return 0; +} + +static int handle_media_playback(const char *action) { + const char *pctl_cmd = strcmp(action, "play-pause") == 0 ? "play-pause" + : strcmp(action, "prev") == 0 ? "previous" + : strcmp(action, "next") == 0 ? "next" + : "stop"; + if (anode_have_cmd("playerctl")) { + const char *av[] = {"playerctl", pctl_cmd, NULL}; + if (anode_run_cmd_timeout(av, NULL, 0, 1500) == 0) { + notify_osd("Media", action, -1); + return 0; + } + } + if (anode_have_cmd("mpc")) { + const char *m_cmd = strcmp(action, "play-pause") == 0 ? "toggle" : action; + const char *av[] = {"mpc", m_cmd, NULL}; + if (anode_run_cmd_timeout(av, NULL, 0, 1500) == 0) { + notify_osd("Media", action, -1); + return 0; + } + } + char rdir[256], mpv_sock[320]; + anode_runtime_dir(rdir, sizeof(rdir)); + snprintf(mpv_sock, sizeof(mpv_sock), "%s/mpv.sock", rdir); + if (access(mpv_sock, F_OK) == 0 && anode_have_cmd("socat")) { + const char *json = strcmp(action, "play-pause") == 0 ? "{\"command\":[\"cycle\",\"pause\"]}\n" + : strcmp(action, "next") == 0 ? "{\"command\":[\"playlist-next\"]}\n" + : strcmp(action, "prev") == 0 ? "{\"command\":[\"playlist-prev\"]}\n" + : "{\"command\":[\"stop\"]}\n"; + char scmd[512]; + snprintf(scmd, sizeof(scmd), "printf '%%s' '%s' | socat - '%s'", json, mpv_sock); + const char *av[] = {"sh", "-c", scmd, NULL}; + anode_run_cmd_timeout(av, NULL, 0, 1000); + } + notify_osd("Media", action, -1); + return 0; +} + +static int handle_screenshot(bool focused_win) { + const char *home = getenv("HOME"); + const char *pic = getenv("XDG_PICTURES_DIR"); + char dir[320], outpath[420]; + if (pic && pic[0]) snprintf(dir, sizeof(dir), "%s", pic); + else if (home && home[0]) snprintf(dir, sizeof(dir), "%s/Pictures", home); + else snprintf(dir, sizeof(dir), "/tmp"); + mkdir(dir, 0755); + + time_t now = time(NULL); + struct tm tmb; + localtime_r(&now, &tmb); + char ts[32]; + strftime(ts, sizeof(ts), "%Y%m%d-%H%M%S", &tmb); + snprintf(outpath, sizeof(outpath), "%s/screenshot-%s.png", dir, ts); + + int rc = 1; + if (anode_have_cmd("scrot")) { + if (focused_win) { + const char *av[] = {"scrot", "-u", "-b", outpath, NULL}; + rc = anode_run_cmd_timeout(av, NULL, 0, 4000); + } else { + const char *av[] = {"scrot", outpath, NULL}; + rc = anode_run_cmd_timeout(av, NULL, 0, 4000); + } + } else if (anode_have_cmd("import")) { + const char *av[] = {"import", "-window", "root", outpath, NULL}; + rc = anode_run_cmd_timeout(av, NULL, 0, 4000); + } else if (anode_have_cmd("maim")) { + const char *av[] = {"maim", outpath, NULL}; + rc = anode_run_cmd_timeout(av, NULL, 0, 4000); + } + + if (rc == 0) { + notify_osd("Screenshot Saved", outpath, -1); + } else { + notify_osd("Screenshot", "No screenshot tool available (scrot/import/maim)", -1); + } + return rc == 0 ? 0 : 1; +} + +static int handle_airplane(void) { + if (anode_have_cmd("nmcli")) { + char out[64] = {0}; + const char *q[] = {"nmcli", "radio", "wifi", NULL}; + anode_run_cmd_timeout(q, out, sizeof(out), 1500); + bool currently_on = (strstr(out, "enabled") != NULL); + const char *t[] = {"nmcli", "radio", "all", currently_on ? "off" : "on", NULL}; + anode_run_cmd_timeout(t, NULL, 0, 2000); + notify_osd("Airplane Mode", currently_on ? "Radios disabled" : "Radios enabled", -1); + signal_statusd(); + return 0; + } + if (anode_have_cmd("rfkill")) { + char out[256] = {0}; + const char *q[] = {"rfkill", "list", NULL}; + anode_run_cmd_timeout(q, out, sizeof(out), 1500); + bool soft_blocked = (strstr(out, "Soft blocked: yes") != NULL); + const char *t[] = {"rfkill", soft_blocked ? "unblock" : "block", "all", NULL}; + anode_run_priv_timeout(t, NULL, 0, 2000); + notify_osd("Airplane Mode", soft_blocked ? "Radios enabled" : "Radios blocked", -1); + signal_statusd(); + return 0; + } + notify_osd("Airplane Mode", "Radio control tool unavailable", -1); + return 1; +} + +int main(int argc, char *argv[]) { + if (argc < 2) { + fprintf(stderr, "Usage: anode-media-key \n"); + return 2; + } + const char *act = argv[1]; + if (strcmp(act, "vol-up") == 0 || strcmp(act, "vol-down") == 0 || + strcmp(act, "vol-mute") == 0 || strcmp(act, "mic-mute") == 0) { + return handle_volume(act); + } + if (strcmp(act, "bri-up") == 0) return handle_brightness(true); + if (strcmp(act, "bri-down") == 0) return handle_brightness(false); + if (strcmp(act, "play-pause") == 0 || strcmp(act, "prev") == 0 || + strcmp(act, "next") == 0 || strcmp(act, "stop") == 0) { + return handle_media_playback(act); + } + if (strcmp(act, "screenshot") == 0) return handle_screenshot(false); + if (strcmp(act, "screenshot-window") == 0) return handle_screenshot(true); + if (strcmp(act, "airplane") == 0) return handle_airplane(); + if (strcmp(act, "vkbd-toggle") == 0) { toggle_vkbd(); return 0; } + if (strcmp(act, "suspend") == 0) { + const char *sp[] = {"anode-power-ctl", "suspend", NULL}; + return (anode_run_priv_timeout(sp, NULL, 0, 5000) == 0 || anode_power_action("suspend") == 0) ? 0 : 1; + } + fprintf(stderr, "anode-media-key: unknown action '%s'\n", act); + return 2; +} diff --git a/src/apps/anode-net.c b/src/apps/anode-net.c new file mode 100644 index 0000000..fc7d84b --- /dev/null +++ b/src/apps/anode-net.c @@ -0,0 +1,366 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" +#include "anode_wifi_list.h" +#include "anode_bt_list.h" +#include "anode_dns_valid.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct { + gemui_app_t *app; + int tab; /* 0=Wi-Fi, 1=Interfaces, 2=Bluetooth, 3=DNS */ + anode_wifi_group_t wifi[ANODE_MAX_WIFI_GROUPS]; + int n_wifi; + anode_net_iface_t ifaces[ANODE_MAX_IFACES]; + int n_ifaces; + anode_bt_dev_t bt[ANODE_MAX_BT_DEVS]; + int n_bt; + char dns_summary[256]; + char dns_input[128]; + char wifi_pass[128]; + bool pass_prompt; + bool scanning; + int worker_fd; + pid_t worker_pid; + char worker_buf[16384]; + size_t worker_len; + int sel; +} net_state_t; + +enum { + HIT_TAB = 1, + HIT_ROW, + HIT_INPUT, + HIT_ACTION1, + HIT_ACTION2, + HIT_QUIT +}; + +static void on_worker_fd(gemui_app_t *app, int fd, void *ud); + +static void refresh_sync(net_state_t *st) { + st->n_ifaces = anode_list_net_ifaces(st->ifaces, ANODE_MAX_IFACES); + FILE *rf = fopen("/etc/resolv.conf", "r"); + if (rf) { + char buf[2048] = {0}; + size_t r = fread(buf, 1, sizeof(buf) - 1, rf); + buf[r] = '\0'; + fclose(rf); + anode_parse_resolv_conf(buf, st->dns_summary, sizeof(st->dns_summary)); + } + if (!st->dns_summary[0]) snprintf(st->dns_summary, sizeof(st->dns_summary), "DHCP / Router Default"); + + if (st->tab == 2 && anode_have_cmd("bluetoothctl")) { + char a[4096] = {0}, p[2048] = {0}, c[2048] = {0}; + const char *c1[] = {"bluetoothctl", "devices", NULL}; + const char *c2[] = {"bluetoothctl", "devices", "Paired", NULL}; + const char *c3[] = {"bluetoothctl", "devices", "Connected", NULL}; + anode_run_cmd_timeout(c1, a, sizeof(a), 1500); + anode_run_cmd_timeout(c2, p, sizeof(p), 1500); + anode_run_cmd_timeout(c3, c, sizeof(c), 1500); + st->n_bt = anode_parse_bt_devices(a, p, c, st->bt, ANODE_MAX_BT_DEVS); + } +} + +static void start_wifi_scan(net_state_t *st) { + if (st->scanning) return; + int pfd[2]; + if (pipe(pfd) != 0) return; + + pid_t pid = fork(); + if (pid < 0) { + close(pfd[0]); + close(pfd[1]); + return; + } + if (pid == 0) { + close(pfd[0]); + dup2(pfd[1], STDOUT_FILENO); + if (pfd[1] > 2) close(pfd[1]); + if (anode_have_cmd("nmcli")) { + const char *av[] = {"nmcli", "-t", "-f", "IN-USE,BSSID,SSID,CHAN,SIGNAL,SECURITY", "dev", "wifi", "list", "--rescan", "yes", NULL}; + execvp(av[0], (char *const *)av); + } else if (anode_have_cmd("wpa_cli")) { + const char *av[] = {"sh", "-c", "wpa_cli scan >/dev/null 2>&1; sleep 1; wpa_cli scan_results", NULL}; + execvp(av[0], (char *const *)av); + } else { + char wiface[32] = {0}; + if (anode_find_wifi_iface(wiface, sizeof(wiface))) { + char cmd[128]; + snprintf(cmd, sizeof(cmd), "ifconfig %s list scan 2>/dev/null || true", wiface); + const char *av[] = {"sh", "-c", cmd, NULL}; + execvp(av[0], (char *const *)av); + } + } + _exit(0); + } + + close(pfd[1]); + fcntl(pfd[0], F_SETFL, fcntl(pfd[0], F_GETFL, 0) | O_NONBLOCK); + st->worker_fd = pfd[0]; + st->worker_pid = pid; + st->worker_len = 0; + st->worker_buf[0] = '\0'; + st->scanning = true; + gemui_add_fd(st->app, st->worker_fd, on_worker_fd, st); + gemui_request_redraw(st->app); +} + +static void on_worker_fd(gemui_app_t *app, int fd, void *ud) { + net_state_t *st = (net_state_t *)ud; + char tmp[1024]; + bool done = false; + while (1) { + ssize_t n = read(fd, tmp, sizeof(tmp)); + if (n > 0) { + size_t space = sizeof(st->worker_buf) - 1 - st->worker_len; + size_t cp = ((size_t)n < space) ? (size_t)n : space; + memcpy(st->worker_buf + st->worker_len, tmp, cp); + st->worker_len += cp; + st->worker_buf[st->worker_len] = '\0'; + } else if (n == 0) { + done = true; + break; + } else { + if (errno == EAGAIN || errno == EWOULDBLOCK) break; + done = true; + break; + } + } + if (done) { + gemui_del_fd(app, fd); + close(fd); + st->worker_fd = -1; + if (st->worker_pid > 0) { + waitpid(st->worker_pid, NULL, 0); + st->worker_pid = -1; + } + st->scanning = false; + if (anode_have_cmd("nmcli")) { + st->n_wifi = anode_parse_wifi_scan(st->worker_buf, st->wifi, ANODE_MAX_WIFI_GROUPS); + } else if (anode_have_cmd("wpa_cli")) { + st->n_wifi = anode_parse_wpa_scan(st->worker_buf, NULL, st->wifi, ANODE_MAX_WIFI_GROUPS); + } + gemui_request_redraw(app); + } +} + +static void trigger_connect(net_state_t *st) { + if (st->tab == 0 && st->sel < st->n_wifi) { + const anode_wifi_group_t *g = &st->wifi[st->sel]; + bool needs_pw = (strcmp(g->security, "Open") != 0 && !g->in_use); + if (needs_pw && !st->pass_prompt) { + st->pass_prompt = true; + st->wifi_pass[0] = '\0'; + gemui_request_redraw(st->app); + return; + } + if (anode_have_cmd("nmcli")) { + int rc = 1; + if (needs_pw && st->wifi_pass[0]) { + const char *av[] = {"nmcli", "dev", "wifi", "connect", g->ssid, "password", st->wifi_pass, NULL}; + rc = anode_run_cmd_timeout(av, NULL, 0, 8000); + } else { + const char *av[] = {"nmcli", "dev", "wifi", "connect", g->ssid, NULL}; + rc = anode_run_cmd_timeout(av, NULL, 0, 8000); + } + st->pass_prompt = false; + st->wifi_pass[0] = '\0'; + gemui_show_toast(st->app, rc == 0 ? "Wi-Fi Connected" : "Wi-Fi Connect Failed", 2000); + } else { + gemui_show_toast(st->app, "nmcli not available; configure wpa_supplicant", 2200); + } + start_wifi_scan(st); + const char *ns[] = {"anode-statusd"}; + anode_signal_procs(ns, 1, SIGUSR1); + } else if (st->tab == 2 && st->sel < st->n_bt && anode_have_cmd("bluetoothctl")) { + const anode_bt_dev_t *d = &st->bt[st->sel]; + const char *op = d->connected ? "disconnect" : "connect"; + const char *av[] = {"bluetoothctl", op, d->mac, NULL}; + anode_run_cmd_timeout(av, NULL, 0, 6000); + refresh_sync(st); + } else if (st->tab == 3 && st->sel < ANODE_DNS_COUNT) { + int rc = 1; + if (st->sel == ANODE_DNS_CUSTOM) { + const char *av[] = {"anode-dnsctl", "custom", st->dns_input, NULL}; + rc = anode_run_priv_timeout(av, NULL, 0, 3000); + } else { + const char *av[] = {"anode-dnsctl", "preset", ANODE_DNS_PRESETS[st->sel].mode, NULL}; + rc = anode_run_priv_timeout(av, NULL, 0, 3000); + } + refresh_sync(st); + gemui_show_toast(st->app, rc == 0 ? "DNS updated" : "DNS update failed (privilege needed)", 2000); + } + gemui_request_redraw(st->app); +} + +static int tab_items(const net_state_t *st) { + if (st->tab == 0) return st->n_wifi; + if (st->tab == 1) return st->n_ifaces; + if (st->tab == 2) return st->n_bt; + return ANODE_DNS_COUNT; +} + +static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { + net_state_t *st = (net_state_t *)ud; + const gemui_theme_t *t = gemui_theme(app); + gemui_draw_header(app, cr, NULL, "ANODE Network & Connectivity", + st->scanning ? "Scanning..." : st->dns_summary); + + 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); + + static const char *TABS[4] = {"Wi-Fi", "Interfaces", "Bluetooth", "DNS"}; + int tw = (cw - pad * 3) / 4; + for (int i = 0; i < 4; i++) { + gemui_draw_button(app, cr, (gemui_rect_t){pad + i * (tw + pad), y, tw, btn_h}, + TABS[i], HIT_TAB, i, false, i == st->tab, false); + } + y += btn_h + pad; + + if ((st->tab == 0 && st->pass_prompt) || (st->tab == 3 && st->sel == ANODE_DNS_CUSTOM)) { + const char *ph = (st->tab == 0) ? "Enter Wi-Fi Passphrase (Enter to connect)..." : "Custom DNS CSV (e.g. 1.1.1.1,9.9.9.9)"; + const char *tx = (st->tab == 0) ? st->wifi_pass : st->dns_input; + gemui_draw_input(app, cr, (gemui_rect_t){pad, y, cw, btn_h + 4}, + ph, tx, st->tab == 0, true, HIT_INPUT, 0); + y += btn_h + 4 + pad; + } + + int list_h = h - y - btn_h - pad * 2; + gemui_rect_t lr = {pad, y, cw, list_h}; + gemui_fill_round(cr, lr, (double)gemui_scale_px(app, 6), t->bg_alt_even); + gemui_stroke_round(cr, lr, (double)gemui_scale_px(app, 6), 1.0, t->border); + + int cnt = tab_items(st); + int row_h = gemui_touch_row_px(app, 34); + if (cnt == 0) { + gemui_draw_text(cr, t, lr, st->tab == 0 ? (st->scanning ? "Scanning wireless networks..." : "No Wi-Fi networks found (press r to scan)") : "No entries", + 0, false, GEMUI_ALIGN_CENTER, t->fg_muted); + } else { + int max_r = (list_h - pad) / row_h; + for (int i = 0; i < cnt && i < max_r; i++) { + gemui_rect_t rr = {lr.x + pad / 2, lr.y + pad / 2 + i * row_h, lr.w - pad, row_h - 4}; + bool sel = (i == st->sel); + if (sel) gemui_fill_round(cr, rr, (double)gemui_scale_px(app, 5), t->sel_bg); + char line[256] = {0}; + bool bold = sel; + if (st->tab == 0) { + bold = bold || st->wifi[i].in_use; + snprintf(line, sizeof(line), "%s%-26s %3d%% ch %d [%s]", + st->wifi[i].in_use ? "* " : " ", st->wifi[i].ssid, + st->wifi[i].best_signal, st->wifi[i].best_chan, st->wifi[i].security); + } else if (st->tab == 1) { + snprintf(line, sizeof(line), " %-10s %s%s %s %s", + st->ifaces[i].name, + st->ifaces[i].is_up ? "UP" : "DOWN", + st->ifaces[i].is_wireless ? "/WiFi" : "", + st->ifaces[i].ipv4[0] ? st->ifaces[i].ipv4 : "-", + st->ifaces[i].ipv6[0] ? st->ifaces[i].ipv6 : ""); + } else if (st->tab == 2) { + bold = bold || st->bt[i].connected; + snprintf(line, sizeof(line), "%s%-26s %s %s", + st->bt[i].connected ? "* " : " ", st->bt[i].name, st->bt[i].mac, + st->bt[i].paired ? "Paired" : "Discovered"); + } else { + snprintf(line, sizeof(line), " %-24s %s", + ANODE_DNS_PRESETS[i].label, ANODE_DNS_PRESETS[i].v4_csv); + } + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 8, rr.y, rr.w - 16, rr.h}, + line, 0, bold, GEMUI_ALIGN_LEFT, sel ? t->sel_fg : t->fg_main); + gemui_hit_add(app, rr, HIT_ROW, i); + } + } + + int fy = h - btn_h - pad; + int bw = gemui_scale_px(app, 120); + gemui_draw_button(app, cr, (gemui_rect_t){pad, fy, bw, btn_h}, + st->tab == 0 ? "Scan" : "Refresh", HIT_ACTION1, 0, false, false, false); + gemui_draw_button(app, cr, (gemui_rect_t){w - pad * 2 - bw * 2, fy, bw, btn_h}, + "Connect / Set", HIT_ACTION2, 0, true, false, false); + gemui_draw_button(app, cr, (gemui_rect_t){w - pad - bw, fy, bw, btn_h}, + "Close", HIT_QUIT, 0, false, false, false); +} + +static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) { + (void)state; + net_state_t *st = (net_state_t *)ud; + if (st->pass_prompt || (st->tab == 3 && st->sel == ANODE_DNS_CUSTOM)) { + char *buf = (st->tab == 0) ? st->wifi_pass : st->dns_input; + size_t bsz = sizeof(st->wifi_pass); + if (ks == XK_Escape) { st->pass_prompt = false; gemui_request_redraw(app); return; } + if (ks == XK_Return) { trigger_connect(st); return; } + if (ks == XK_BackSpace) { gemui_utf8_pop_char(buf); gemui_request_redraw(app); return; } + if (utf8 && utf8[0]) { + size_t cl = strlen(buf), al = strlen(utf8); + if (cl + al + 1 < bsz) { memcpy(buf + cl, utf8, al); buf[cl + al] = '\0'; } + gemui_request_redraw(app); + return; + } + } + + int cnt = tab_items(st); + if (ks == XK_Escape || ks == XK_q) gemui_quit(app, 0); + else if (ks == XK_Tab) { st->tab = (st->tab + 1) % 4; st->sel = 0; refresh_sync(st); gemui_request_redraw(app); } + else if (ks == XK_Down || ks == XK_j) { if (st->sel + 1 < cnt) 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) trigger_connect(st); + else if (ks == XK_r) { + refresh_sync(st); + if (st->tab == 0) start_wifi_scan(st); + gemui_request_redraw(app); + } +} + +static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { + net_state_t *st = (net_state_t *)ud; + 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_TAB) { + st->tab = hit->val; st->sel = 0; st->pass_prompt = false; + refresh_sync(st); + if (st->tab == 0 && st->n_wifi == 0) start_wifi_scan(st); + } else if (hit->id == HIT_ROW) { + if (st->sel == hit->val) trigger_connect(st); + else st->sel = hit->val; + } else if (hit->id == HIT_ACTION1) { + refresh_sync(st); + if (st->tab == 0) start_wifi_scan(st); + } else if (hit->id == HIT_ACTION2) { + trigger_connect(st); + } else if (hit->id == HIT_QUIT) { + gemui_quit(app, 0); + } + gemui_request_redraw(app); +} + +int main(void) { + net_state_t *st = calloc(1, sizeof(*st)); + if (!st) return 1; + st->worker_fd = -1; + st->worker_pid = -1; + st->app = gemui_create("anode-net", "ANODE Network", 820, 540, false); + if (!st->app) { free(st); return 1; } + refresh_sync(st); + 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); + if (st->worker_fd >= 0) close(st->worker_fd); + if (st->worker_pid > 0) { + kill(st->worker_pid, SIGTERM); + waitpid(st->worker_pid, NULL, 0); + } + gemui_destroy(st->app); + free(st); + return rc; +} diff --git a/src/apps/anode-power.c b/src/apps/anode-power.c new file mode 100644 index 0000000..8769faf --- /dev/null +++ b/src/apps/anode-power.c @@ -0,0 +1,263 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" + +#include +#include +#include +#include + +typedef struct { + gemui_app_t *app; + anode_battery_info_t bat; + int bri_pct; + int vol_pct; + bool muted; + char prof[32]; + int focus_idx; +} pwr_state_t; + +enum { + HIT_VOL_SLIDER = 1, + HIT_VOL_MUTE, + HIT_BRI_SLIDER, + HIT_PROF, + HIT_TOOL, + HIT_ACT +}; + +static const char *PROFILES[] = {"power-saver", "balanced", "performance"}; +static const char *TOOLS[][2] = { + {"Network", "anode-net"}, + {"Audio", "anode-audio"}, + {"Display", "anode-display"}, + {"Date/TZ", "anode-datetime"}, + {"Themes", "anode-themes"}, + {"Keyboard", "vkbd-toggle"} +}; +static const char *ACTIONS[][2] = { + {"Lock", "lock"}, + {"Suspend", "suspend"}, + {"Hibernate", "hibernate"}, + {"Reboot", "reboot"}, + {"Power Off", "poweroff"} +}; + +static void refresh_state(pwr_state_t *st) { + anode_read_battery(&st->bat); + int cur = 50, maxv = 100; + if (anode_backlight_get(&cur, &maxv, NULL, 0) && maxv > 0) { + st->bri_pct = (cur * 100 + maxv / 2) / maxv; + } else { + st->bri_pct = 75; + } + if (!anode_audio_get_default(false, &st->vol_pct, &st->muted)) { + st->vol_pct = 50; + st->muted = false; + } + if (!anode_power_profile_get(st->prof, sizeof(st->prof))) { + snprintf(st->prof, sizeof(st->prof), "balanced"); + } +} + +static void on_timer(gemui_app_t *app, void *ud) { + pwr_state_t *st = (pwr_state_t *)ud; + refresh_state(st); + gemui_request_redraw(app); +} + +static void do_action(pwr_state_t *st, int idx) { + if (idx < 0 || idx >= 5) return; + const char *act = ACTIONS[idx][1]; + if (strcmp(act, "lock") == 0) { + const char *av[] = {"anode-lock", NULL}; + anode_spawn_detached(av); + gemui_quit(st->app, 0); + } else { + const char *av[] = {"anode-power-ctl", act, NULL}; + if (anode_run_priv_timeout(av, NULL, 0, 4000) == 0 || anode_power_action(act) == 0) { + gemui_show_toast(st->app, ACTIONS[idx][0], 1500); + } else { + gemui_show_toast(st->app, "Privilege escalation required (doas/sudo/pkexec)", 2200); + } + } +} + +static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { + pwr_state_t *st = (pwr_state_t *)ud; + + char badge[96]; + if (st->bat.present && st->bat.capacity >= 0) { + snprintf(badge, sizeof(badge), "BAT %d%% (%s)", st->bat.capacity, st->bat.status); + } else { + snprintf(badge, sizeof(badge), "%s", st->bat.on_ac ? "AC Power" : "Power & Control"); + } + gemui_draw_header(app, cr, NULL, "ANODE Control Center & Power", badge); + + int pad = gemui_scale_px(app, 12); + int y = gemui_scale_px(app, 42) + pad; + int cw = w - pad * 2; + int slider_h = gemui_touch_row_px(app, 52); + + char vtxt[32]; + snprintf(vtxt, sizeof(vtxt), "%d%%%s", st->vol_pct, st->muted ? " (Muted)" : ""); + int mute_w = gemui_scale_px(app, 96); + gemui_draw_slider(app, cr, (gemui_rect_t){pad, y, cw - mute_w - pad / 2, slider_h}, + "Audio Volume", (double)st->vol_pct / 100.0, vtxt, + HIT_VOL_SLIDER, 0, st->focus_idx == 0); + gemui_draw_button(app, cr, (gemui_rect_t){pad + cw - mute_w, y, mute_w, slider_h}, + st->muted ? "Unmute" : "Mute", HIT_VOL_MUTE, 0, + false, st->muted, st->focus_idx == 1); + y += slider_h + pad; + + char btxt[32]; + snprintf(btxt, sizeof(btxt), "%d%%", st->bri_pct); + gemui_draw_slider(app, cr, (gemui_rect_t){pad, y, cw, slider_h}, + "Display Brightness", (double)st->bri_pct / 100.0, btxt, + HIT_BRI_SLIDER, 0, st->focus_idx == 2); + y += slider_h + pad; + + /* Power profile row */ + int row_h = gemui_touch_row_px(app, 36); + int pw = (cw - pad * 2) / 3; + for (int i = 0; i < 3; i++) { + bool act = (strcmp(st->prof, PROFILES[i]) == 0); + gemui_draw_button(app, cr, (gemui_rect_t){pad + i * (pw + pad), y, pw, row_h}, + PROFILES[i], HIT_PROF, i, false, act, st->focus_idx == 3 + i); + } + 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); + } + + /* Bottom power actions bar */ + int aw = (cw - pad * 4) / 5; + 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); + } +} + +static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) { + (void)utf8; + 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; + gemui_request_redraw(app); + } else if (ks == XK_Up || ks == XK_k) { + st->focus_idx = (st->focus_idx + 16) % 17; + 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; + if (st->focus_idx == 0) { + int nv = st->vol_pct + d; + if (nv < 0) nv = 0; + if (nv > 100) nv = 100; + anode_audio_set_vol(false, nv); + refresh_state(st); + const char *ns[] = {"anode-statusd"}; + anode_signal_procs(ns, 1, SIGUSR1); + } else if (st->focus_idx == 2) { + int nb = st->bri_pct + d; + if (nb < 5) nb = 5; + if (nb > 100) nb = 100; + anode_backlight_set((double)nb / 100.0); + refresh_state(st); + } else { + st->focus_idx = (st->focus_idx + (d > 0 ? 1 : 16)) % 17; + } + gemui_request_redraw(app); + } else if (ks == XK_Return || ks == XK_space) { + if (st->focus_idx == 1) { + anode_audio_toggle_mute(false); + refresh_state(st); + } else if (st->focus_idx >= 3 && st->focus_idx <= 5) { + int pi = st->focus_idx - 3; + if (anode_power_profile_set(PROFILES[pi])) snprintf(st->prof, sizeof(st->prof), "%s", PROFILES[pi]); + else { + 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; + if (strcmp(TOOLS[ti][1], "vkbd-toggle") == 0) { + const char *av[] = {"anode-media-key", "vkbd-toggle", NULL}; + anode_spawn_detached(av); + } else { + const char *av[] = {TOOLS[ti][1], NULL}; + anode_spawn_detached(av); + } + } else if (st->focus_idx >= 12) { + do_action(st, st->focus_idx - 12); + } + gemui_request_redraw(app); + } +} + +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_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); + } + } + refresh_state(st); + } else if (hit->id == HIT_VOL_MUTE) { + anode_audio_toggle_mute(false); + refresh_state(st); + } else if (hit->id == HIT_PROF) { + const char *p = PROFILES[hit->val]; + if (!anode_power_profile_set(p)) { + const char *av[] = {"anode-power-ctl", "profile", p, NULL}; + anode_run_priv_timeout(av, NULL, 0, 2000); + } + refresh_state(st); + } else if (hit->id == HIT_TOOL) { + if (strcmp(TOOLS[hit->val][1], "vkbd-toggle") == 0) { + const char *av[] = {"anode-media-key", "vkbd-toggle", NULL}; + anode_spawn_detached(av); + } else { + const char *av[] = {TOOLS[hit->val][1], NULL}; + anode_spawn_detached(av); + } + } else if (hit->id == HIT_ACT) { + do_action(st, hit->val); + } + gemui_request_redraw(app); +} + +int main(void) { + pwr_state_t st; + memset(&st, 0, sizeof(st)); + st.app = gemui_create("anode-power", "ANODE Control Center", 760, 480, 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 }; + gemui_set_handlers(st.app, &h, &st); + gemui_set_timer_ms(st.app, 5000, on_timer, &st); + int rc = gemui_run(st.app); + gemui_destroy(st.app); + return rc; +} diff --git a/src/apps/anode-themes.c b/src/apps/anode-themes.c new file mode 100644 index 0000000..a786bdd --- /dev/null +++ b/src/apps/anode-themes.c @@ -0,0 +1,260 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" + +#include +#include +#include +#include + +#define MAX_THEMES 64 + +typedef struct { + char name[64]; + char path[512]; + gemui_theme_t preview; +} theme_entry_t; + +typedef struct { + gemui_app_t *app; + theme_entry_t themes[MAX_THEMES]; + int count; + int sel; + int scroll; + char active_name[64]; +} themes_state_t; + +enum { HIT_ROW = 1, HIT_APPLY, HIT_QUIT }; + +static int cmp_theme_entry(const void *a, const void *b) { + const theme_entry_t *ta = (const theme_entry_t *)a; + const theme_entry_t *tb = (const theme_entry_t *)b; + return strcmp(ta->name, tb->name); +} + +static void scan_dir(themes_state_t *st, const char *dir) { + if (!dir || !dir[0]) return; + DIR *d = opendir(dir); + if (!d) return; + struct dirent *de; + while ((de = readdir(d)) != NULL && st->count < MAX_THEMES) { + size_t len = strlen(de->d_name); + if (len < 5 || strcmp(de->d_name + len - 4, ".xth") != 0) continue; + char full[512]; + snprintf(full, sizeof(full), "%s/%s", dir, de->d_name); + gemui_theme_t prev; + if (!gemui_theme_load_file(full, &prev)) continue; + char tname[64]; + if (prev.name[0]) { + snprintf(tname, sizeof(tname), "%s", prev.name); + } else { + size_t nlen = len - 4; + if (nlen >= sizeof(tname)) nlen = sizeof(tname) - 1; + memcpy(tname, de->d_name, nlen); + tname[nlen] = '\0'; + } + int existing = -1; + for (int i = 0; i < st->count; i++) { + if (strcmp(st->themes[i].name, tname) == 0) { + existing = i; + break; + } + } + theme_entry_t *e = (existing >= 0) ? &st->themes[existing] : &st->themes[st->count++]; + snprintf(e->name, sizeof(e->name), "%s", tname); + snprintf(e->path, sizeof(e->path), "%s", full); + e->preview = prev; + } + closedir(d); +} + +static void reload_themes(themes_state_t *st) { + st->count = 0; + char cfg[512], sysdir[512], udir[544]; + anode_config_dir(cfg, sizeof(cfg)); + anode_themes_sys_dir(sysdir, sizeof(sysdir)); + + scan_dir(st, sysdir); + scan_dir(st, "data/themes"); + const char *home = getenv("HOME"); + if (home && home[0]) { + snprintf(udir, sizeof(udir), "%s/.xthemes", home); + scan_dir(st, udir); + } + snprintf(udir, sizeof(udir), "%s/themes", cfg); + scan_dir(st, udir); + + 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 : ""); + for (int i = 0; i < st->count; i++) { + if (strcmp(st->themes[i].name, st->active_name) == 0) { + st->sel = i; + break; + } + } + if (st->sel >= st->count) st->sel = st->count > 0 ? st->count - 1 : 0; +} + +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); + char msg[128]; + snprintf(msg, sizeof(msg), "Applied %s across DE", st->themes[st->sel].name); + gemui_show_toast(st->app, msg, 2000); + } else { + gemui_show_toast(st->app, "Failed to apply theme", 2000); + } + gemui_request_redraw(st->app); +} + +static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { + 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); + + 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); + } + + /* 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]); + } + 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); + } + + /* 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); +} + +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); + } +} + +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); + return; + } + if (type == GEMUI_PTR_SCROLL_DOWN) { + if (st->sel + 1 < st->count) st->sel++; + 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_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_QUIT) { + gemui_quit(app, 0); + } +} + +int main(void) { + themes_state_t st; + memset(&st, 0, sizeof(st)); + st.app = gemui_create("anode-themes", "ANODE Themes", 820, 520, false); + if (!st.app) return 1; + reload_themes(&st); + 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); + gemui_destroy(st.app); + return rc; +} diff --git a/src/apps/anode-vkbd.c b/src/apps/anode-vkbd.c new file mode 100644 index 0000000..6b7eee8 --- /dev/null +++ b/src/apps/anode-vkbd.c @@ -0,0 +1,528 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" +#include "anode_scale.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum { LAYER_LOWER = 0, LAYER_SHIFT = 1, LAYER_SYM = 2, LAYER_NAV = 3 }; +enum { KACT_CHAR = 0, KACT_SHIFT, KACT_SYM, KACT_NAV, KACT_CTRL, KACT_ALT, KACT_SUPER, KACT_HIDE }; + +typedef struct { + const char *label; + KeySym ks; + int weight; + int action; + bool shift_needed; +} vkey_t; + +typedef struct { + int row; + int x, y, w, h; + const vkey_t *k; +} hit_key_t; + +static int g_sig_pipe[2] = {-1, -1}; + +static void sig_handler(int sig) { + int saved = errno; + char c = (sig == SIGUSR1) ? 'T' : (sig == SIGHUP) ? 'R' : 'Q'; + if (g_sig_pipe[1] >= 0) { + ssize_t unused = write(g_sig_pipe[1], &c, 1); + (void)unused; + } + errno = saved; +} + +/* Rows: up to 14 keys per row, 5 rows */ +static const vkey_t ROW0_LOWER[] = { + {"Esc", XK_Escape, 12, KACT_CHAR, false}, {"1", XK_1, 10, KACT_CHAR, false}, + {"2", XK_2, 10, KACT_CHAR, false}, {"3", XK_3, 10, KACT_CHAR, false}, + {"4", XK_4, 10, KACT_CHAR, false}, {"5", XK_5, 10, KACT_CHAR, false}, + {"6", XK_6, 10, KACT_CHAR, false}, {"7", XK_7, 10, KACT_CHAR, false}, + {"8", XK_8, 10, KACT_CHAR, false}, {"9", XK_9, 10, KACT_CHAR, false}, + {"0", XK_0, 10, KACT_CHAR, false}, {"-", XK_minus, 10, KACT_CHAR, false}, + {"=", XK_equal, 10, KACT_CHAR, false}, {"Bksp", XK_BackSpace, 18, KACT_CHAR, false}, + {NULL, 0, 0, 0, false} +}; +static const vkey_t ROW0_SHIFT[] = { + {"~", XK_grave, 12, KACT_CHAR, true}, {"!", XK_1, 10, KACT_CHAR, true}, + {"@", XK_2, 10, KACT_CHAR, true}, {"#", XK_3, 10, KACT_CHAR, true}, + {"$", XK_4, 10, KACT_CHAR, true}, {"%", XK_5, 10, KACT_CHAR, true}, + {"^", XK_6, 10, KACT_CHAR, true}, {"&", XK_7, 10, KACT_CHAR, true}, + {"*", XK_8, 10, KACT_CHAR, true}, {"(", XK_9, 10, KACT_CHAR, true}, + {")", XK_0, 10, KACT_CHAR, true}, {"_", XK_minus, 10, KACT_CHAR, true}, + {"+", XK_equal, 10, KACT_CHAR, true}, {"Bksp", XK_BackSpace, 18, KACT_CHAR, false}, + {NULL, 0, 0, 0, false} +}; +static const vkey_t ROW0_NAV[] = { + {"F1", XK_F1, 10, KACT_CHAR, false}, {"F2", XK_F2, 10, KACT_CHAR, false}, + {"F3", XK_F3, 10, KACT_CHAR, false}, {"F4", XK_F4, 10, KACT_CHAR, false}, + {"F5", XK_F5, 10, KACT_CHAR, false}, {"F6", XK_F6, 10, KACT_CHAR, false}, + {"F7", XK_F7, 10, KACT_CHAR, false}, {"F8", XK_F8, 10, KACT_CHAR, false}, + {"F9", XK_F9, 10, KACT_CHAR, false}, {"F10", XK_F10, 10, KACT_CHAR, false}, + {"F11", XK_F11, 10, KACT_CHAR, false}, {"F12", XK_F12, 10, KACT_CHAR, false}, + {"Del", XK_Delete, 14, KACT_CHAR, false}, {"Bksp", XK_BackSpace, 16, KACT_CHAR, false}, + {NULL, 0, 0, 0, false} +}; + +static const vkey_t ROW1_LOWER[] = { + {"Tab", XK_Tab, 14, KACT_CHAR, false}, {"q", XK_q, 10, KACT_CHAR, false}, + {"w", XK_w, 10, KACT_CHAR, false}, {"e", XK_e, 10, KACT_CHAR, false}, + {"r", XK_r, 10, KACT_CHAR, false}, {"t", XK_t, 10, KACT_CHAR, false}, + {"y", XK_y, 10, KACT_CHAR, false}, {"u", XK_u, 10, KACT_CHAR, false}, + {"i", XK_i, 10, KACT_CHAR, false}, {"o", XK_o, 10, KACT_CHAR, false}, + {"p", XK_p, 10, KACT_CHAR, false}, {"[", XK_bracketleft, 10, KACT_CHAR, false}, + {"]", XK_bracketright, 10, KACT_CHAR, false}, {"\\", XK_backslash, 12, KACT_CHAR, false}, + {NULL, 0, 0, 0, false} +}; +static const vkey_t ROW1_SHIFT[] = { + {"Tab", XK_Tab, 14, KACT_CHAR, false}, {"Q", XK_q, 10, KACT_CHAR, true}, + {"W", XK_w, 10, KACT_CHAR, true}, {"E", XK_e, 10, KACT_CHAR, true}, + {"R", XK_r, 10, KACT_CHAR, true}, {"T", XK_t, 10, KACT_CHAR, true}, + {"Y", XK_y, 10, KACT_CHAR, true}, {"U", XK_u, 10, KACT_CHAR, true}, + {"I", XK_i, 10, KACT_CHAR, true}, {"O", XK_o, 10, KACT_CHAR, true}, + {"P", XK_p, 10, KACT_CHAR, true}, {"{", XK_bracketleft, 10, KACT_CHAR, true}, + {"}", XK_bracketright, 10, KACT_CHAR, true}, {"|", XK_backslash, 12, KACT_CHAR, true}, + {NULL, 0, 0, 0, false} +}; +static const vkey_t ROW1_SYM[] = { + {"`", XK_grave, 12, KACT_CHAR, false}, {"!", XK_1, 10, KACT_CHAR, true}, + {"@", XK_2, 10, KACT_CHAR, true}, {"#", XK_3, 10, KACT_CHAR, true}, + {"$", XK_4, 10, KACT_CHAR, true}, {"%", XK_5, 10, KACT_CHAR, true}, + {"^", XK_6, 10, KACT_CHAR, true}, {"&", XK_7, 10, KACT_CHAR, true}, + {"*", XK_8, 10, KACT_CHAR, true}, {"(", XK_9, 10, KACT_CHAR, true}, + {")", XK_0, 10, KACT_CHAR, true}, {"_", XK_minus, 10, KACT_CHAR, true}, + {"+", XK_equal, 10, KACT_CHAR, true}, {"|", XK_backslash, 12, KACT_CHAR, true}, + {NULL, 0, 0, 0, false} +}; + +static const vkey_t ROW2_LOWER[] = { + {"Shift", XK_Shift_L, 17, KACT_SHIFT, false}, {"a", XK_a, 10, KACT_CHAR, false}, + {"s", XK_s, 10, KACT_CHAR, false}, {"d", XK_d, 10, KACT_CHAR, false}, + {"f", XK_f, 10, KACT_CHAR, false}, {"g", XK_g, 10, KACT_CHAR, false}, + {"h", XK_h, 10, KACT_CHAR, false}, {"j", XK_j, 10, KACT_CHAR, false}, + {"k", XK_k, 10, KACT_CHAR, false}, {"l", XK_l, 10, KACT_CHAR, false}, + {";", XK_semicolon, 10, KACT_CHAR, false}, {"'", XK_apostrophe, 10, KACT_CHAR, false}, + {"Enter", XK_Return, 21, KACT_CHAR, false}, + {NULL, 0, 0, 0, false} +}; +static const vkey_t ROW2_SHIFT[] = { + {"SHIFT", XK_Shift_L, 17, KACT_SHIFT, false}, {"A", XK_a, 10, KACT_CHAR, true}, + {"S", XK_s, 10, KACT_CHAR, true}, {"D", XK_d, 10, KACT_CHAR, true}, + {"F", XK_f, 10, KACT_CHAR, true}, {"G", XK_g, 10, KACT_CHAR, true}, + {"H", XK_h, 10, KACT_CHAR, true}, {"J", XK_j, 10, KACT_CHAR, true}, + {"K", XK_k, 10, KACT_CHAR, true}, {"L", XK_l, 10, KACT_CHAR, true}, + {":", XK_semicolon, 10, KACT_CHAR, true}, {"\"", XK_apostrophe, 10, KACT_CHAR, true}, + {"Enter", XK_Return, 21, KACT_CHAR, false}, + {NULL, 0, 0, 0, false} +}; +static const vkey_t ROW2_NAV[] = { + {"Home", XK_Home, 16, KACT_CHAR, false}, {"PgUp", XK_Prior, 14, KACT_CHAR, false}, + {"Up", XK_Up, 14, KACT_CHAR, false}, {"PgDn", XK_Next, 14, KACT_CHAR, false}, + {"End", XK_End, 16, KACT_CHAR, false}, {"Left", XK_Left, 14, KACT_CHAR, false}, + {"Down", XK_Down, 14, KACT_CHAR, false}, {"Right", XK_Right, 14, KACT_CHAR, false}, + {"Ins", XK_Insert, 12, KACT_CHAR, false}, {"Enter", XK_Return, 20, KACT_CHAR, false}, + {NULL, 0, 0, 0, false} +}; + +static const vkey_t ROW3_LOWER[] = { + {"123", 0, 15, KACT_SYM, false}, {"z", XK_z, 10, KACT_CHAR, false}, + {"x", XK_x, 10, KACT_CHAR, false}, {"c", XK_c, 10, KACT_CHAR, false}, + {"v", XK_v, 10, KACT_CHAR, false}, {"b", XK_b, 10, KACT_CHAR, false}, + {"n", XK_n, 10, KACT_CHAR, false}, {"m", XK_m, 10, KACT_CHAR, false}, + {",", XK_comma, 10, KACT_CHAR, false}, {".", XK_period, 10, KACT_CHAR, false}, + {"/", XK_slash, 10, KACT_CHAR, false}, {"Nav", 0, 15, KACT_NAV, false}, + {NULL, 0, 0, 0, false} +}; +static const vkey_t ROW3_SHIFT[] = { + {"123", 0, 15, KACT_SYM, false}, {"Z", XK_z, 10, KACT_CHAR, true}, + {"X", XK_x, 10, KACT_CHAR, true}, {"C", XK_c, 10, KACT_CHAR, true}, + {"V", XK_v, 10, KACT_CHAR, true}, {"B", XK_b, 10, KACT_CHAR, true}, + {"N", XK_n, 10, KACT_CHAR, true}, {"M", XK_m, 10, KACT_CHAR, true}, + {"<", XK_comma, 10, KACT_CHAR, true}, {">", XK_period, 10, KACT_CHAR, true}, + {"?", XK_slash, 10, KACT_CHAR, true}, {"Nav", 0, 15, KACT_NAV, false}, + {NULL, 0, 0, 0, false} +}; + +static const vkey_t ROW4_BASE[] = { + {"Ctrl", XK_Control_L, 12, KACT_CTRL, false}, {"Alt", XK_Alt_L, 11, KACT_ALT, false}, + {"Super", XK_Super_L, 13, KACT_SUPER, false}, {"Space", XK_space, 46, KACT_CHAR, false}, + {"<", XK_Left, 9, KACT_CHAR, false}, {"v", XK_Down, 9, KACT_CHAR, false}, + {"^", XK_Up, 9, KACT_CHAR, false}, {">", XK_Right, 9, KACT_CHAR, false}, + {"Hide", 0, 12, KACT_HIDE, false}, + {NULL, 0, 0, 0, false} +}; + +typedef struct { + Display *dpy; + int screen; + Window root; + Window win; + Pixmap backbuf; + cairo_surface_t *img_surf; + cairo_t *img_cr; + cairo_surface_t *xlib_surf; + GC gc; + int sw, sh; + int wx, wy, ww, wh; + double scale; + gemui_theme_t theme; + Atom a_wtype, a_wtype_dock, a_strut, a_strut_partial, a_name, a_utf8; + bool visible; + int layer; + bool mod_shift, mod_ctrl, mod_alt, mod_super; + hit_key_t hits[80]; + int n_hits; + const vkey_t *pressed_key; +} vkbd_t; + +static void update_strut(vkbd_t *v, bool reserve) { + if (!v->win) return; + if (reserve) { + 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); + 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}; + XChangeProperty(v->dpy, v->win, v->a_strut, XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)s4, 4); + } else { + XDeleteProperty(v->dpy, v->win, v->a_strut_partial); + XDeleteProperty(v->dpy, v->win, v->a_strut); + } +} + +static void load_theme_and_geom(vkbd_t *v) { + XrmInitialize(); + gemui_theme_defaults(&v->theme); + XrmDatabase db = anode_open_xres_db(v->dpy); + double dpi = 96.0, sc = 1.0; + anode_read_xres_scale_from_db(db, v->dpy, &dpi, &sc, NULL); + if (db) { + /* Load matching colors cleanly via temporary .Xresources or existing gemui parser */ + char *type = NULL; + XrmValue val; + if (XrmGetResource(db, "theme.bgMain", "*", &type, &val) && val.addr) gemui_color_parse(val.addr, &v->theme.bg_main); + if (XrmGetResource(db, "theme.bgHeader", "*", &type, &val) && val.addr) gemui_color_parse(val.addr, &v->theme.bg_header); + if (XrmGetResource(db, "theme.bgButton", "*", &type, &val) && val.addr) gemui_color_parse(val.addr, &v->theme.bg_button); + if (XrmGetResource(db, "theme.fgBright", "*", &type, &val) && val.addr) gemui_color_parse(val.addr, &v->theme.fg_bright); + if (XrmGetResource(db, "theme.selBg", "*", &type, &val) && val.addr) gemui_color_parse(val.addr, &v->theme.sel_bg); + if (XrmGetResource(db, "theme.selFg", "*", &type, &val) && val.addr) gemui_color_parse(val.addr, &v->theme.sel_fg); + if (XrmGetResource(db, "theme.accent", "*", &type, &val) && val.addr) gemui_color_parse(val.addr, &v->theme.accent); + if (XrmGetResource(db, "theme.border", "*", &type, &val) && val.addr) gemui_color_parse(val.addr, &v->theme.border); + if (XrmGetResource(db, "theme.fontFace", "*", &type, &val) && val.addr) { + snprintf(v->theme.font_face, sizeof(v->theme.font_face), "%s", val.addr); + } + XrmDestroyDatabase(db); + } + v->scale = sc; + v->theme.scale = sc; + v->theme.dpi = (int)llround(dpi); + v->theme.base_font_size = anode_scale_px(13, sc); + + v->sw = DisplayWidth(v->dpy, v->screen); + v->sh = DisplayHeight(v->dpy, v->screen); + int kh = anode_scale_px(210, sc); + int max_kh = (v->sh * 42) / 100; + if (kh > max_kh) kh = max_kh; + if (kh < 140 && v->sh >= 360) kh = 140; + v->ww = v->sw; + v->wh = kh; + v->wx = 0; + v->wy = v->sh - v->wh; +} + +static void ensure_buffers(vkbd_t *v) { + if (v->backbuf) { XFreePixmap(v->dpy, v->backbuf); v->backbuf = 0; } + if (v->img_cr) { cairo_destroy(v->img_cr); v->img_cr = NULL; } + if (v->img_surf) { cairo_surface_destroy(v->img_surf); v->img_surf = NULL; } + if (v->xlib_surf) { cairo_surface_destroy(v->xlib_surf); v->xlib_surf = NULL; } + + v->backbuf = XCreatePixmap(v->dpy, v->win, (unsigned int)v->ww, (unsigned int)v->wh, + (unsigned int)DefaultDepth(v->dpy, v->screen)); + v->xlib_surf = cairo_xlib_surface_create(v->dpy, v->backbuf, + DefaultVisual(v->dpy, v->screen), + v->ww, v->wh); + v->img_surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, v->ww, v->wh); + v->img_cr = cairo_create(v->img_surf); +} + +static const vkey_t *get_row(int layer, int r) { + if (r == 0) return (layer == LAYER_SHIFT) ? ROW0_SHIFT : (layer == LAYER_NAV) ? ROW0_NAV : ROW0_LOWER; + if (r == 1) return (layer == LAYER_SHIFT) ? ROW1_SHIFT : (layer == LAYER_SYM) ? ROW1_SYM : ROW1_LOWER; + if (r == 2) return (layer == LAYER_SHIFT) ? ROW2_SHIFT : (layer == LAYER_NAV) ? ROW2_NAV : ROW2_LOWER; + if (r == 3) return (layer == LAYER_SHIFT) ? ROW3_SHIFT : ROW3_LOWER; + return ROW4_BASE; +} + +static void draw_vkbd(vkbd_t *v) { + if (!v->visible || !v->img_cr) return; + cairo_t *cr = v->img_cr; + gemui_fill_rect(cr, (gemui_rect_t){0, 0, v->ww, v->wh}, v->theme.bg_header); + gemui_fill_rect(cr, (gemui_rect_t){0, 0, v->ww, 2}, v->theme.accent); + + int pad = anode_scale_px(4, v->scale); + int top_pad = pad + 2; + int row_h = (v->wh - top_pad - pad * 5) / 5; + double rad = (double)anode_scale_px(5, v->scale); + v->n_hits = 0; + + for (int r = 0; r < 5; r++) { + const vkey_t *row = get_row(v->layer, r); + int total_w = 0, cnt = 0; + for (int i = 0; row[i].label; i++) { total_w += row[i].weight; cnt++; } + if (total_w <= 0) continue; + + int avail = v->ww - pad * (cnt + 1); + int cx = pad; + int cy = top_pad + r * (row_h + pad); + for (int i = 0; row[i].label && v->n_hits < 80; i++) { + int kw = (i + 1 == cnt) ? (v->ww - pad - cx) : ((avail * row[i].weight) / total_w); + bool latched = (row[i].action == KACT_SHIFT && v->mod_shift) || + (row[i].action == KACT_CTRL && v->mod_ctrl) || + (row[i].action == KACT_ALT && v->mod_alt) || + (row[i].action == KACT_SUPER && v->mod_super) || + (row[i].action == KACT_SYM && v->layer == LAYER_SYM) || + (row[i].action == KACT_NAV && v->layer == LAYER_NAV); + 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; + 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); + gemui_draw_text(cr, &v->theme, (gemui_rect_t){cx + 2, cy, kw - 4, row_h}, + row[i].label, 0, row[i].action != KACT_CHAR, GEMUI_ALIGN_CENTER, fg); + + v->hits[v->n_hits++] = (hit_key_t){r, cx, cy, kw, row_h, &row[i]}; + cx += kw + pad; + } + } + + cairo_surface_flush(v->img_surf); + cairo_t *xcr = cairo_create(v->xlib_surf); + cairo_set_operator(xcr, CAIRO_OPERATOR_SOURCE); + cairo_set_source_surface(xcr, v->img_surf, 0, 0); + cairo_paint(xcr); + cairo_destroy(xcr); + cairo_surface_flush(v->xlib_surf); + XCopyArea(v->dpy, v->backbuf, v->win, v->gc, 0, 0, (unsigned int)v->ww, (unsigned int)v->wh, 0, 0); + XFlush(v->dpy); +} + +static void emit_key(vkbd_t *v, const vkey_t *k) { + KeyCode kc = XKeysymToKeycode(v->dpy, k->ks); + if (!kc) return; + + bool need_shift = k->shift_needed || v->mod_shift; + KeyCode kc_sh = XKeysymToKeycode(v->dpy, XK_Shift_L); + KeyCode kc_ct = XKeysymToKeycode(v->dpy, XK_Control_L); + KeyCode kc_al = XKeysymToKeycode(v->dpy, XK_Alt_L); + KeyCode kc_su = XKeysymToKeycode(v->dpy, XK_Super_L); + + if (need_shift && kc_sh) XTestFakeKeyEvent(v->dpy, kc_sh, True, CurrentTime); + if (v->mod_ctrl && kc_ct) XTestFakeKeyEvent(v->dpy, kc_ct, True, CurrentTime); + if (v->mod_alt && kc_al) XTestFakeKeyEvent(v->dpy, kc_al, True, CurrentTime); + if (v->mod_super && kc_su) XTestFakeKeyEvent(v->dpy, kc_su, True, CurrentTime); + + XTestFakeKeyEvent(v->dpy, kc, True, CurrentTime); + XTestFakeKeyEvent(v->dpy, kc, False, CurrentTime); + + if (v->mod_super && kc_su) XTestFakeKeyEvent(v->dpy, kc_su, False, CurrentTime); + if (v->mod_alt && kc_al) XTestFakeKeyEvent(v->dpy, kc_al, False, CurrentTime); + if (v->mod_ctrl && kc_ct) XTestFakeKeyEvent(v->dpy, kc_ct, False, CurrentTime); + if (need_shift && kc_sh) XTestFakeKeyEvent(v->dpy, kc_sh, False, CurrentTime); + XFlush(v->dpy); + + if (v->mod_shift || v->mod_ctrl || v->mod_alt || v->mod_super) { + v->mod_shift = v->mod_ctrl = v->mod_alt = v->mod_super = false; + if (v->layer == LAYER_SHIFT) v->layer = LAYER_LOWER; + } +} + +static void set_visible(vkbd_t *v, bool vis) { + if (v->visible == vis) return; + v->visible = vis; + if (vis) { + load_theme_and_geom(v); + XMoveResizeWindow(v->dpy, v->win, v->wx, v->wy, (unsigned int)v->ww, (unsigned int)v->wh); + ensure_buffers(v); + update_strut(v, true); + XMapRaised(v->dpy, v->win); + draw_vkbd(v); + } else { + update_strut(v, false); + XUnmapWindow(v->dpy, v->win); + XFlush(v->dpy); + } +} + +int main(void) { + setlocale(LC_CTYPE, ""); + if (pipe(g_sig_pipe) != 0) return 1; + for (int i = 0; i < 2; i++) { + fcntl(g_sig_pipe[i], F_SETFL, fcntl(g_sig_pipe[i], F_GETFL, 0) | O_NONBLOCK); + fcntl(g_sig_pipe[i], F_SETFD, fcntl(g_sig_pipe[i], F_GETFD, 0) | FD_CLOEXEC); + } + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = sig_handler; + sigaction(SIGUSR1, &sa, NULL); + sigaction(SIGHUP, &sa, NULL); + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + + vkbd_t v; + memset(&v, 0, sizeof(v)); + v.dpy = XOpenDisplay(NULL); + if (!v.dpy) return 1; + v.screen = DefaultScreen(v.dpy); + v.root = RootWindow(v.dpy, v.screen); + + load_theme_and_geom(&v); + + XSetWindowAttributes swa; + memset(&swa, 0, sizeof(swa)); + swa.override_redirect = True; + swa.event_mask = ExposureMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask; + v.win = XCreateWindow(v.dpy, v.root, v.wx, v.wy, (unsigned int)v.ww, (unsigned int)v.wh, 0, + CopyFromParent, InputOutput, CopyFromParent, + CWOverrideRedirect | CWEventMask, &swa); + v.gc = XCreateGC(v.dpy, v.win, 0, NULL); + + XWMHints *wmh = XAllocWMHints(); + if (wmh) { + wmh->flags = InputHint; + wmh->input = False; /* Never steal keyboard focus */ + XSetWMHints(v.dpy, v.win, wmh); + XFree(wmh); + } + XClassHint ch = {"anode-vkbd", "anode-vkbd"}; + XSetClassHint(v.dpy, v.win, &ch); + + v.a_wtype = XInternAtom(v.dpy, "_NET_WM_WINDOW_TYPE", False); + v.a_wtype_dock = XInternAtom(v.dpy, "_NET_WM_WINDOW_TYPE_DOCK", False); + v.a_strut = XInternAtom(v.dpy, "_NET_WM_STRUT", False); + v.a_strut_partial = XInternAtom(v.dpy, "_NET_WM_STRUT_PARTIAL", False); + v.a_name = XInternAtom(v.dpy, "_NET_WM_NAME", False); + v.a_utf8 = XInternAtom(v.dpy, "UTF8_STRING", False); + + XChangeProperty(v.dpy, v.win, v.a_wtype, XA_ATOM, 32, PropModeReplace, (unsigned char *)&v.a_wtype_dock, 1); + XStoreName(v.dpy, v.win, "ANODE Virtual Keyboard"); + XSelectInput(v.dpy, v.root, PropertyChangeMask); + + set_visible(&v, true); + + int xfd = ConnectionNumber(v.dpy); + bool running = true; + while (running) { + while (XPending(v.dpy) > 0) { + XEvent ev; + XNextEvent(v.dpy, &ev); + if (ev.type == Expose && ev.xexpose.count == 0) { + draw_vkbd(&v); + } else if (ev.type == PropertyNotify && ev.xproperty.window == v.root && + ev.xproperty.atom == XA_RESOURCE_MANAGER) { + if (v.visible) { + load_theme_and_geom(&v); + XMoveResizeWindow(v.dpy, v.win, v.wx, v.wy, (unsigned int)v.ww, (unsigned int)v.wh); + ensure_buffers(&v); + update_strut(&v, true); + draw_vkbd(&v); + } + } else if (ev.type == ButtonPress && ev.xbutton.button == Button1) { + for (int i = 0; i < v.n_hits; i++) { + hit_key_t *hk = &v.hits[i]; + if (ev.xbutton.x >= hk->x && ev.xbutton.x < hk->x + hk->w && + ev.xbutton.y >= hk->y && ev.xbutton.y < hk->y + hk->h) { + v.pressed_key = hk->k; + if (hk->k->action == KACT_HIDE) { + set_visible(&v, false); + } else if (hk->k->action == KACT_SHIFT) { + v.mod_shift = !v.mod_shift; + v.layer = v.mod_shift ? LAYER_SHIFT : LAYER_LOWER; + draw_vkbd(&v); + } else if (hk->k->action == KACT_SYM) { + v.layer = (v.layer == LAYER_SYM) ? LAYER_LOWER : LAYER_SYM; + v.mod_shift = false; + draw_vkbd(&v); + } else if (hk->k->action == KACT_NAV) { + v.layer = (v.layer == LAYER_NAV) ? LAYER_LOWER : LAYER_NAV; + v.mod_shift = false; + draw_vkbd(&v); + } else if (hk->k->action == KACT_CTRL) { + v.mod_ctrl = !v.mod_ctrl; draw_vkbd(&v); + } else if (hk->k->action == KACT_ALT) { + v.mod_alt = !v.mod_alt; draw_vkbd(&v); + } else if (hk->k->action == KACT_SUPER) { + v.mod_super = !v.mod_super; draw_vkbd(&v); + } else { + emit_key(&v, hk->k); + draw_vkbd(&v); + } + break; + } + } + } else if (ev.type == ButtonRelease && v.pressed_key) { + v.pressed_key = NULL; + draw_vkbd(&v); + } + } + + struct pollfd pfds[2] = { + {.fd = xfd, .events = POLLIN}, + {.fd = g_sig_pipe[0], .events = POLLIN} + }; + if (poll(pfds, 2, -1) < 0 && errno != EINTR) break; + if (pfds[1].revents & POLLIN) { + char buf[32]; + ssize_t n; + while ((n = read(g_sig_pipe[0], buf, sizeof(buf))) > 0) { + for (ssize_t i = 0; i < n; i++) { + if (buf[i] == 'Q') running = false; + else if (buf[i] == 'T') set_visible(&v, !v.visible); + else if (buf[i] == 'R' && v.visible) { + load_theme_and_geom(&v); + XMoveResizeWindow(v.dpy, v.win, v.wx, v.wy, (unsigned int)v.ww, (unsigned int)v.wh); + ensure_buffers(&v); + update_strut(&v, true); + draw_vkbd(&v); + } + } + } + } + } + + update_strut(&v, false); + XUnmapWindow(v.dpy, v.win); + if (v.backbuf) XFreePixmap(v.dpy, v.backbuf); + if (v.img_cr) cairo_destroy(v.img_cr); + if (v.img_surf) cairo_surface_destroy(v.img_surf); + if (v.xlib_surf) cairo_surface_destroy(v.xlib_surf); + if (v.gc) XFreeGC(v.dpy, v.gc); + XDestroyWindow(v.dpy, v.win); + XCloseDisplay(v.dpy); + close(g_sig_pipe[0]); + close(g_sig_pipe[1]); + return 0; +} diff --git a/src/common/anode_audio_parse.h b/src/common/anode_audio_parse.h new file mode 100644 index 0000000..4360f45 --- /dev/null +++ b/src/common/anode_audio_parse.h @@ -0,0 +1,355 @@ +/* + * Header-only C11 parsers for PipeWire / PulseAudio / ALSA / sndio / OSS audio endpoints. + */ +#ifndef ANODE_AUDIO_PARSE_H +#define ANODE_AUDIO_PARSE_H + +#include +#include +#include +#include +#include + +#define ANODE_MAX_AUDIO_NODES 24 +#define ANODE_MAX_AUDIO_PROFILES 32 + +typedef struct { + int index; + char name[128]; + char label[128]; + char state[24]; + char port[64]; + int vol_pct; + bool muted; + bool is_default; + bool is_stream; +} anode_audio_node_t; + +typedef struct { + char card_name[128]; + char card_label[128]; + char profile_name[96]; + char profile_desc[128]; + bool active; + bool available; +} anode_audio_profile_t; + +static inline bool anode_parse_wpctl_volume(const char *text, int *vol_pct_out, bool *muted_out) { + if (!text) return false; + const char *p = strstr(text, "Volume:"); + if (!p) return false; + double v = atof(p + 7); + if (v < 0.0) v = 0.0; + if (v > 2.0) v = 2.0; + if (vol_pct_out) *vol_pct_out = (int)(v * 100.0 + 0.5); + if (muted_out) *muted_out = (strstr(text, "[MUTED]") != NULL); + return true; +} + +static inline void anode_parse_pactl_defaults(const char *info_txt, + char *def_sink, size_t sink_sz, + char *def_src, size_t src_sz) { + if (def_sink && sink_sz > 0) def_sink[0] = '\0'; + if (def_src && src_sz > 0) def_src[0] = '\0'; + if (!info_txt) return; + const char *cur = info_txt; + while (*cur) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[256]; + size_t cp = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, cp); + ln[cp] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + while (cp > 0 && (ln[cp - 1] == '\r' || ln[cp - 1] == ' ')) ln[--cp] = '\0'; + if (def_sink && strncmp(ln, "Default Sink:", 13) == 0) { + const char *v = ln + 13; + while (*v == ' ' || *v == '\t') v++; + snprintf(def_sink, sink_sz, "%.*s", (int)(sink_sz - 1), v); + } else if (def_src && strncmp(ln, "Default Source:", 15) == 0) { + const char *v = ln + 15; + while (*v == ' ' || *v == '\t') v++; + snprintf(def_src, src_sz, "%.*s", (int)(src_sz - 1), v); + } + } +} + +static inline int anode_extract_first_pct(const char *s) { + if (!s) return 100; + for (const char *p = s; *p; p++) { + if (*p == '%' && p > s && isdigit((unsigned char)p[-1])) { + const char *q = p; + while (q > s && isdigit((unsigned char)q[-1])) q--; + int pct = atoi(q); + if (pct < 0) pct = 0; + if (pct > 200) pct = 200; + return pct; + } + } + return 100; +} + +static inline bool anode_extract_quoted_prop(const char *line, const char *key, + char *out, size_t out_sz) { + size_t klen = strlen(key); + if (strncmp(line, key, klen) != 0) return false; + const char *p = line + klen; + while (*p == ' ' || *p == '\t') p++; + if (*p != '=') return false; + p++; + while (*p == ' ' || *p == '\t') p++; + if (*p == '"') { + p++; + const char *end = strrchr(p, '"'); + size_t len = end ? (size_t)(end - p) : strlen(p); + if (len >= out_sz) len = out_sz - 1; + memcpy(out, p, len); + out[len] = '\0'; + } else { + snprintf(out, out_sz, "%s", p); + } + return out[0] != '\0'; +} + +static inline int anode_parse_pactl_nodes(const char *txt, const char *header_prefix, + const char *default_name, bool is_stream, + anode_audio_node_t *out, int max_out) { + if (!txt || !header_prefix || !out || max_out <= 0) return 0; + size_t hlen = strlen(header_prefix); + int count = 0; + anode_audio_node_t *cur_node = NULL; + char app_name[64] = {0}; + char media_name[64] = {0}; + bool in_props = false; + + const char *cur = txt; + while (*cur) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[384]; + size_t cp = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, cp); + ln[cp] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + while (cp > 0 && (ln[cp - 1] == '\r' || ln[cp - 1] == ' ')) ln[--cp] = '\0'; + + if (strncmp(ln, header_prefix, hlen) == 0) { + if (count >= max_out) { + cur_node = NULL; + continue; + } + cur_node = &out[count++]; + memset(cur_node, 0, sizeof(*cur_node)); + cur_node->index = atoi(ln + hlen); + cur_node->vol_pct = 100; + cur_node->is_stream = is_stream; + app_name[0] = '\0'; + media_name[0] = '\0'; + in_props = false; + continue; + } + if (!cur_node) continue; + + if (ln[0] == '\t' && ln[1] != '\t') { + in_props = false; + const char *k = ln + 1; + if (strcmp(k, "Properties:") == 0) { + in_props = true; + } else if (strncmp(k, "State: ", 7) == 0) { + snprintf(cur_node->state, sizeof(cur_node->state), "%.23s", k + 7); + } else if (strncmp(k, "Name: ", 6) == 0) { + snprintf(cur_node->name, sizeof(cur_node->name), "%.127s", k + 6); + if (default_name && default_name[0] && strcmp(cur_node->name, default_name) == 0) { + cur_node->is_default = true; + } + if (!cur_node->label[0]) { + snprintf(cur_node->label, sizeof(cur_node->label), "%.127s", cur_node->name); + } + } else if (strncmp(k, "Description: ", 13) == 0) { + snprintf(cur_node->label, sizeof(cur_node->label), "%.127s", k + 13); + } else if (strncmp(k, "Mute: ", 6) == 0) { + cur_node->muted = (strcmp(k + 6, "yes") == 0); + } else if (strncmp(k, "Volume: ", 8) == 0) { + cur_node->vol_pct = anode_extract_first_pct(k + 8); + } else if (strncmp(k, "Active Port: ", 13) == 0) { + snprintf(cur_node->port, sizeof(cur_node->port), "%.63s", k + 13); + } + } else if (in_props && ln[0] == '\t' && ln[1] == '\t') { + const char *k = ln + 2; + if (!anode_extract_quoted_prop(k, "application.name", app_name, sizeof(app_name))) { + anode_extract_quoted_prop(k, "media.name", media_name, sizeof(media_name)); + } + if (is_stream) { + if (app_name[0] && media_name[0] && strcmp(app_name, media_name) != 0) { + snprintf(cur_node->label, sizeof(cur_node->label), "%.56s: %.56s", app_name, media_name); + } else if (app_name[0]) { + snprintf(cur_node->label, sizeof(cur_node->label), "%s", app_name); + } else if (media_name[0]) { + snprintf(cur_node->label, sizeof(cur_node->label), "%s", media_name); + } + } else if (!cur_node->label[0]) { + anode_extract_quoted_prop(k, "device.description", cur_node->label, sizeof(cur_node->label)); + } + } + } + return count; +} + +static inline int anode_parse_pactl_cards(const char *cards_txt, + anode_audio_profile_t *out, int max_out) { + if (!cards_txt || !out || max_out <= 0) return 0; + int total = 0; + int card_start = 0; + char card_name[128] = {0}; + char card_label[128] = {0}; + char active_prof[96] = {0}; + int sec = 0; + + const char *cur = cards_txt; + while (*cur) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[384]; + size_t cp = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, cp); + ln[cp] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + while (cp > 0 && (ln[cp - 1] == '\r' || ln[cp - 1] == ' ')) ln[--cp] = '\0'; + + if (strncmp(ln, "Card #", 6) == 0) { + card_start = total; + card_name[0] = '\0'; + card_label[0] = '\0'; + active_prof[0] = '\0'; + sec = 0; + continue; + } + + if (ln[0] == '\t' && ln[1] != '\t') { + const char *k = ln + 1; + sec = 0; + if (strcmp(k, "Properties:") == 0) { + sec = 1; + } else if (strcmp(k, "Profiles:") == 0) { + sec = 2; + } else if (strncmp(k, "Name: ", 6) == 0) { + snprintf(card_name, sizeof(card_name), "%.127s", k + 6); + if (!card_label[0]) snprintf(card_label, sizeof(card_label), "%.127s", card_name); + for (int i = card_start; i < total; i++) { + snprintf(out[i].card_name, sizeof(out[i].card_name), "%.127s", card_name); + } + } else if (strncmp(k, "Active Profile: ", 16) == 0) { + snprintf(active_prof, sizeof(active_prof), "%.95s", k + 16); + for (int i = card_start; i < total; i++) { + out[i].active = (strcmp(out[i].profile_name, active_prof) == 0); + } + } + } else if (sec == 1 && ln[0] == '\t' && ln[1] == '\t') { + const char *k = ln + 2; + if (anode_extract_quoted_prop(k, "device.description", card_label, sizeof(card_label)) || + (!card_label[0] && anode_extract_quoted_prop(k, "alsa.card_name", card_label, sizeof(card_label)))) { + for (int i = card_start; i < total; i++) { + snprintf(out[i].card_label, sizeof(out[i].card_label), "%s", card_label); + } + } + } else if (sec == 2 && ln[0] == '\t' && ln[1] == '\t' && total < max_out) { + const char *k = ln + 2; + const char *sep = strstr(k, ": "); + if (!sep) continue; + anode_audio_profile_t *p = &out[total++]; + memset(p, 0, sizeof(*p)); + snprintf(p->card_name, sizeof(p->card_name), "%s", card_name); + snprintf(p->card_label, sizeof(p->card_label), "%s", card_label[0] ? card_label : card_name); + size_t idlen = (size_t)(sep - k); + if (idlen >= sizeof(p->profile_name)) idlen = sizeof(p->profile_name) - 1; + memcpy(p->profile_name, k, idlen); + p->profile_name[idlen] = '\0'; + + const char *rhs = sep + 2; + p->available = (strstr(rhs, "available: no") == NULL); + const char *meta = strstr(rhs, " (sinks:"); + if (!meta) meta = strstr(rhs, " (available:"); + size_t dlen = meta ? (size_t)(meta - rhs) : strlen(rhs); + if (dlen >= sizeof(p->profile_desc)) dlen = sizeof(p->profile_desc) - 1; + memcpy(p->profile_desc, rhs, dlen); + p->profile_desc[dlen] = '\0'; + if (active_prof[0] && strcmp(p->profile_name, active_prof) == 0) { + p->active = true; + } + } + } + return total; +} + +static inline int anode_parse_amixer_scontrols(const char *txt, + anode_audio_node_t *out, int max_out) { + if (!txt || !out || max_out <= 0) return 0; + int n = 0; + const char *cur = txt; + while (*cur && n < max_out) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[256]; + size_t cp = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, cp); + ln[cp] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + + const char *q1 = strchr(ln, '\''); + if (!q1) continue; + const char *q2 = strchr(q1 + 1, '\''); + if (!q2 || q2 == q1 + 1) continue; + + anode_audio_node_t *nd = &out[n]; + memset(nd, 0, sizeof(*nd)); + nd->index = n; + size_t len = (size_t)(q2 - (q1 + 1)); + if (len >= sizeof(nd->name)) len = sizeof(nd->name) - 1; + memcpy(nd->name, q1 + 1, len); + nd->name[len] = '\0'; + snprintf(nd->label, sizeof(nd->label), "%s", nd->name); + snprintf(nd->state, sizeof(nd->state), "ALSA"); + nd->vol_pct = 100; + nd->is_default = (strcmp(nd->name, "Master") == 0); + n++; + } + return n; +} + +static inline int anode_parse_sndioctl(const char *txt, bool want_input, + anode_audio_node_t *out, int max_out) { + if (!txt || !out || max_out <= 0) return 0; + int n = 0; + const char *cur = txt; + while (*cur && n < max_out) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[256]; + size_t cp = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, cp); + ln[cp] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + + char *eq = strchr(ln, '='); + if (!eq) continue; + *eq = '\0'; + const char *key = ln; + const char *val = eq + 1; + if (!strstr(key, ".level")) continue; + bool is_in = (strncmp(key, "input.", 6) == 0 || strncmp(key, "record.", 7) == 0); + if (is_in != want_input) continue; + + anode_audio_node_t *nd = &out[n]; + memset(nd, 0, sizeof(*nd)); + nd->index = n; + snprintf(nd->name, sizeof(nd->name), "%.127s", key); + snprintf(nd->label, sizeof(nd->label), "%.127s", key); + snprintf(nd->state, sizeof(nd->state), "sndio"); + nd->vol_pct = (int)(atof(val) * 100.0 + 0.5); + nd->is_default = (n == 0); + n++; + } + return n; +} + +#endif /* ANODE_AUDIO_PARSE_H */ diff --git a/src/common/anode_bt_list.h b/src/common/anode_bt_list.h new file mode 100644 index 0000000..4b414c3 --- /dev/null +++ b/src/common/anode_bt_list.h @@ -0,0 +1,133 @@ +/* + * Header-only C11 helpers for parsing bluetoothctl device listings into sorted entries. + */ +#ifndef ANODE_BT_LIST_H +#define ANODE_BT_LIST_H + +#include +#include +#include +#include +#include + +#define ANODE_MAX_BT_DEVS 32 + +typedef struct { + char mac[24]; + char name[96]; + bool paired; + bool connected; +} anode_bt_dev_t; + +static inline bool anode_bt_is_mac(const char *s) { + if (!s || strlen(s) < 17) return false; + for (int i = 0; i < 17; i++) { + if (i % 3 == 2) { + if (s[i] != ':') return false; + } else if (!isxdigit((unsigned char)s[i])) { + return false; + } + } + return s[17] == '\0' || s[17] == ' ' || s[17] == '\t'; +} + +static inline void anode_bt_strip_ansi(const char *in, char *out, size_t out_sz) { + size_t j = 0; + for (size_t i = 0; in[i] && j + 1 < out_sz; i++) { + if ((unsigned char)in[i] == 0x1b && in[i + 1] == '[') { + i += 2; + while (in[i] && !((in[i] >= 'A' && in[i] <= 'Z') || (in[i] >= 'a' && in[i] <= 'z'))) { + i++; + } + continue; + } + if ((unsigned char)in[i] >= 0x20 || in[i] == '\t') { + out[j++] = in[i]; + } + } + out[j] = '\0'; +} + +static inline void anode_bt_feed_list(const char *text, anode_bt_dev_t *devs, + int *count, int max_devs, + bool mark_paired, bool mark_connected) { + if (!text || !devs || !count || max_devs <= 0) return; + const char *cur = text; + while (*cur) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char raw[256], ln[256]; + size_t cp = raw_len < sizeof(raw) - 1 ? raw_len : sizeof(raw) - 1; + memcpy(raw, cur, cp); + raw[cp] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + + anode_bt_strip_ansi(raw, ln, sizeof(ln)); + char *p = ln; + while (*p == ' ' || *p == '\t') p++; + if (strncmp(p, "[NEW]", 5) == 0 || strncmp(p, "[CHG]", 5) == 0) p += 5; + while (*p == ' ' || *p == '\t') p++; + if (strncmp(p, "Device ", 7) != 0) continue; + p += 7; + if (!anode_bt_is_mac(p)) continue; + + char mac[24]; + memcpy(mac, p, 17); + mac[17] = '\0'; + for (int i = 0; i < 17; i++) mac[i] = (char)toupper((unsigned char)mac[i]); + + const char *name = p + 17; + while (*name == ' ' || *name == '\t') name++; + size_t nlen = strlen(name); + while (nlen > 0 && (name[nlen - 1] == ' ' || name[nlen - 1] == '\r')) nlen--; + + int idx = -1; + for (int i = 0; i < *count; i++) { + if (strcmp(devs[i].mac, mac) == 0) { + idx = i; + break; + } + } + if (idx < 0) { + if (*count >= max_devs) continue; + idx = (*count)++; + memset(&devs[idx], 0, sizeof(devs[idx])); + snprintf(devs[idx].mac, sizeof(devs[idx].mac), "%s", mac); + } + if (nlen > 0) { + size_t keep = nlen < sizeof(devs[idx].name) - 1 ? nlen : sizeof(devs[idx].name) - 1; + memcpy(devs[idx].name, name, keep); + devs[idx].name[keep] = '\0'; + } else if (!devs[idx].name[0]) { + snprintf(devs[idx].name, sizeof(devs[idx].name), "%s", mac); + } + if (mark_paired) devs[idx].paired = true; + if (mark_connected) { + devs[idx].connected = true; + devs[idx].paired = true; + } + } +} + +static inline int anode_bt_dev_cmp(const void *pa, const void *pb) { + const anode_bt_dev_t *a = (const anode_bt_dev_t *)pa; + const anode_bt_dev_t *b = (const anode_bt_dev_t *)pb; + if (a->connected != b->connected) return b->connected ? 1 : -1; + if (a->paired != b->paired) return b->paired ? 1 : -1; + return strcmp(a->name, b->name); +} + +static inline int anode_parse_bt_devices(const char *all_txt, + const char *paired_txt, + const char *conn_txt, + anode_bt_dev_t *devs, + int max_devs) { + int n = 0; + anode_bt_feed_list(all_txt, devs, &n, max_devs, false, false); + anode_bt_feed_list(paired_txt, devs, &n, max_devs, true, false); + anode_bt_feed_list(conn_txt, devs, &n, max_devs, true, true); + if (n > 1) qsort(devs, (size_t)n, sizeof(devs[0]), anode_bt_dev_cmp); + return n; +} + +#endif /* ANODE_BT_LIST_H */ diff --git a/src/common/anode_dns_valid.h b/src/common/anode_dns_valid.h new file mode 100644 index 0000000..ad132f9 --- /dev/null +++ b/src/common/anode_dns_valid.h @@ -0,0 +1,208 @@ +/* + * Header-only C11 helpers for validating DNS resolver presets and custom nameservers. + */ +#ifndef ANODE_DNS_VALID_H +#define ANODE_DNS_VALID_H + +#include +#include +#include +#include +#include +#include + +#define ANODE_DNS_DEFAULT 0 +#define ANODE_DNS_CLOUDFLARE 1 +#define ANODE_DNS_GOOGLE 2 +#define ANODE_DNS_RADICAL 3 +#define ANODE_DNS_QUAD9 4 +#define ANODE_DNS_CUSTOM 5 +#define ANODE_DNS_COUNT 6 + +#define ANODE_DNS_MAX_SERVERS 6 + +typedef struct { + const char *mode; + const char *label; + const char *v4_csv; + const char *v6_csv; +} anode_dns_preset_t; + +static const anode_dns_preset_t ANODE_DNS_PRESETS[ANODE_DNS_COUNT] = { + {"default", "Default (Router / DHCP)", "", ""}, + {"cloudflare", "Cloudflare DNS", "1.1.1.1,1.0.0.1", "2606:4700:4700::1111"}, + {"google", "Google Public DNS", "8.8.8.8,8.8.4.4", "2001:4860:4860::8888"}, + {"radicaldns", "RadicalDNS", "88.198.92.222,192.71.166.92", "2a01:4f8:1c0c:82c0::1"}, + {"quad9", "Quad9 (Filtered)", "9.9.9.9,149.112.112.112", "2620:fe::fe"}, + {"custom", "Custom Nameservers", "", ""}, +}; + +static inline int anode_dns_mode_index(const char *mode) { + if (!mode || !mode[0]) return -1; + for (int i = 0; i < ANODE_DNS_COUNT; i++) { + if (strcmp(mode, ANODE_DNS_PRESETS[i].mode) == 0) return i; + } + return -1; +} + +static inline bool anode_dns_mode_valid(const char *mode) { + return anode_dns_mode_index(mode) >= 0; +} + +static inline bool anode_dns_token_chars_ok(const char *tok) { + if (!tok || !tok[0]) return false; + for (const unsigned char *p = (const unsigned char *)tok; *p; p++) { + bool ok = (*p >= '0' && *p <= '9') || + (*p >= 'a' && *p <= 'f') || + (*p >= 'A' && *p <= 'F') || + *p == '.' || *p == ':'; + if (!ok) return false; + } + return true; +} + +static inline bool anode_dns_v4_valid(const struct in_addr *a) { + uint32_t ip = ntohl(a->s_addr); + if (ip == 0x00000000U || ip == 0xffffffffU) return false; + if ((ip >> 24) == 0U) return false; + if ((ip & 0xf0000000U) == 0xe0000000U) return false; + return true; +} + +static inline bool anode_dns_v6_valid(const struct in6_addr *a) { + static const uint8_t z[16] = {0}; + if (memcmp(a->s6_addr, z, 16) == 0) return false; + if (a->s6_addr[0] == 0xff) return false; + return true; +} + +static inline int anode_parse_dns_servers(const char *raw, + char v4[][16], int *n_v4, int max_v4, + char v6[][46], int *n_v6, int max_v6, + char *norm_csv, size_t norm_sz) { + int c4 = 0, c6 = 0; + char loc_v4[ANODE_DNS_MAX_SERVERS][16]; + char loc_v6[ANODE_DNS_MAX_SERVERS][46]; + + if (n_v4) *n_v4 = 0; + if (n_v6) *n_v6 = 0; + if (norm_csv && norm_sz > 0) norm_csv[0] = '\0'; + if (!raw || !raw[0]) return -1; + + const char *p = raw; + while (*p) { + while (*p == ',' || *p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++; + if (!*p) break; + const char *start = p; + while (*p && *p != ',' && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n') p++; + size_t len = (size_t)(p - start); + if (len == 0 || len >= 46) return -1; + + char tok[48]; + memcpy(tok, start, len); + tok[len] = '\0'; + if (!anode_dns_token_chars_ok(tok)) return -1; + + struct in_addr a4; + struct in6_addr a6; + if (inet_pton(AF_INET, tok, &a4) == 1) { + if (!anode_dns_v4_valid(&a4)) return -1; + char canon[16]; + if (!inet_ntop(AF_INET, &a4, canon, sizeof(canon))) return -1; + bool dup = false; + for (int i = 0; i < c4; i++) { + if (strcmp(loc_v4[i], canon) == 0) { + dup = true; + break; + } + } + if (!dup) { + if (c4 + c6 >= ANODE_DNS_MAX_SERVERS) return -1; + snprintf(loc_v4[c4], sizeof(loc_v4[c4]), "%s", canon); + if (v4 && c4 < max_v4) snprintf(v4[c4], 16, "%s", canon); + c4++; + } + } else if (inet_pton(AF_INET6, tok, &a6) == 1) { + if (!anode_dns_v6_valid(&a6)) return -1; + char canon[46]; + if (!inet_ntop(AF_INET6, &a6, canon, sizeof(canon))) return -1; + bool dup = false; + for (int i = 0; i < c6; i++) { + if (strcmp(loc_v6[i], canon) == 0) { + dup = true; + break; + } + } + if (!dup) { + if (c4 + c6 >= ANODE_DNS_MAX_SERVERS) return -1; + snprintf(loc_v6[c6], sizeof(loc_v6[c6]), "%s", canon); + if (v6 && c6 < max_v6) snprintf(v6[c6], 46, "%s", canon); + c6++; + } + } else { + return -1; + } + } + + int total = c4 + c6; + if (total <= 0) return -1; + if (n_v4) *n_v4 = c4; + if (n_v6) *n_v6 = c6; + + if (norm_csv && norm_sz > 0) { + size_t pos = 0; + for (int i = 0; i < c4; i++) { + int w = snprintf(norm_csv + pos, norm_sz - pos, "%s%s", pos ? "," : "", loc_v4[i]); + if (w < 0 || (size_t)w >= norm_sz - pos) return -1; + pos += (size_t)w; + } + for (int i = 0; i < c6; i++) { + int w = snprintf(norm_csv + pos, norm_sz - pos, "%s%s", pos ? "," : "", loc_v6[i]); + if (w < 0 || (size_t)w >= norm_sz - pos) return -1; + pos += (size_t)w; + } + } + return total; +} + +static inline int anode_parse_resolv_conf(const char *text, char *summary, size_t summary_sz) { + if (summary && summary_sz > 0) summary[0] = '\0'; + if (!text || !text[0]) return 0; + + int count = 0; + size_t pos = 0; + const char *cur = text; + while (*cur && count < 3) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[256]; + size_t cp = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, cp); + ln[cp] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + + char *p = ln; + while (*p == ' ' || *p == '\t') p++; + if (strncmp(p, "nameserver", 10) != 0) continue; + p += 10; + if (*p != ' ' && *p != '\t') continue; + while (*p == ' ' || *p == '\t') p++; + char *end = p; + while (*end && *end != ' ' && *end != '\t' && *end != '\r' && *end != '#') end++; + *end = '\0'; + if (!anode_dns_token_chars_ok(p)) continue; + + struct in_addr a4; + struct in6_addr a6; + if (inet_pton(AF_INET, p, &a4) != 1 && inet_pton(AF_INET6, p, &a6) != 1) continue; + + if (summary && pos + 2 < summary_sz) { + int w = snprintf(summary + pos, summary_sz - pos, "%s%s", count ? ", " : "", p); + if (w > 0 && (size_t)w < summary_sz - pos) pos += (size_t)w; + } + count++; + } + return count; +} + +#endif /* ANODE_DNS_VALID_H */ diff --git a/src/common/anode_plat.c b/src/common/anode_plat.c new file mode 100644 index 0000000..63b5270 --- /dev/null +++ b/src/common/anode_plat.c @@ -0,0 +1,1039 @@ +#define _DEFAULT_SOURCE +#define _POSIX_C_SOURCE 200809L +#include "anode_plat.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef ANODE_PREFIX +#define ANODE_PREFIX "/usr/local" +#endif + +static uint64_t plat_now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); +} + +static int plat_read_line(const char *path, char *buf, size_t sz) { + if (!path || !buf || sz == 0) return -1; + FILE *f = fopen(path, "r"); + if (!f) return -1; + if (!fgets(buf, (int)sz, f)) { + fclose(f); + return -1; + } + fclose(f); + size_t n = strlen(buf); + while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) { + buf[--n] = '\0'; + } + return 0; +} + +static int plat_write_str(const char *path, const char *val) { + int fd = open(path, O_WRONLY | O_CLOEXEC); + if (fd < 0) return -1; + size_t len = strlen(val); + ssize_t w = write(fd, val, len); + close(fd); + return (w == (ssize_t)len) ? 0 : -1; +} + +static void mkdir_p(const char *path, mode_t mode) { + char tmp[512]; + snprintf(tmp, sizeof(tmp), "%s", path); + size_t len = strlen(tmp); + if (len == 0) return; + if (tmp[len - 1] == '/') tmp[len - 1] = '\0'; + for (char *p = tmp + 1; *p; p++) { + if (*p == '/') { + *p = '\0'; + mkdir(tmp, mode); + *p = '/'; + } + } + mkdir(tmp, mode); +} + +void anode_config_dir(char *buf, size_t sz) { + if (!buf || sz == 0) return; + const char *xdg = getenv("XDG_CONFIG_HOME"); + const char *home = getenv("HOME"); + if (xdg && xdg[0]) { + snprintf(buf, sz, "%s/anode", xdg); + } else if (home && home[0]) { + snprintf(buf, sz, "%s/.config/anode", home); + } else { + struct passwd *pw = getpwuid(getuid()); + snprintf(buf, sz, "%s/.config/anode", (pw && pw->pw_dir) ? pw->pw_dir : "/tmp"); + } + mkdir_p(buf, 0755); +} + +void anode_runtime_dir(char *buf, size_t sz) { + if (!buf || sz == 0) return; + const char *xdg = getenv("XDG_RUNTIME_DIR"); + if (xdg && xdg[0]) { + struct stat st; + if (stat(xdg, &st) == 0 && S_ISDIR(st.st_mode)) { + snprintf(buf, sz, "%s/anode", xdg); + mkdir_p(buf, 0700); + chmod(buf, 0700); + return; + } + } + const char *home = getenv("HOME"); + if (!home || !home[0]) { + struct passwd *pw = getpwuid(getuid()); + home = (pw && pw->pw_dir) ? pw->pw_dir : "/tmp"; + } + snprintf(buf, sz, "%s/.cache/anode-run", home); + mkdir_p(buf, 0700); + chmod(buf, 0700); +} + +void anode_themes_sys_dir(char *buf, size_t sz) { + snprintf(buf, sz, "%s/share/anode/themes", ANODE_PREFIX); +} + +void anode_default_xth_path(char *buf, size_t sz) { + snprintf(buf, sz, "%s/share/anode/themes/AnodeDefault.xth", ANODE_PREFIX); +} + +bool anode_have_cmd(const char *cmd) { + if (!cmd || !cmd[0]) return false; + if (strchr(cmd, '/')) return access(cmd, X_OK) == 0; + const char *path = getenv("PATH"); + if (!path || !path[0]) path = "/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin"; + char copy[2048]; + snprintf(copy, sizeof(copy), "%s", path); + char *save = NULL; + for (char *dir = strtok_r(copy, ":", &save); dir; dir = strtok_r(NULL, ":", &save)) { + char full[512]; + snprintf(full, sizeof(full), "%s/%s", dir, cmd); + if (access(full, X_OK) == 0) return true; + } + return false; +} + +int anode_priv_prefix(const char *argv_out[], int max_slots) { + if (!argv_out || max_slots <= 0) return 0; + if (geteuid() == 0) return 0; + if (anode_have_cmd("doas")) { + argv_out[0] = "doas"; + return 1; + } + if (anode_have_cmd("sudo")) { + if (max_slots >= 2) { + argv_out[0] = "sudo"; + argv_out[1] = "-n"; + return 2; + } + argv_out[0] = "sudo"; + return 1; + } + if (anode_have_cmd("pkexec")) { + argv_out[0] = "pkexec"; + return 1; + } + return 0; +} + +int anode_run_cmd_timeout(const char *const argv[], char *out, size_t out_sz, int timeout_ms) { + if (!argv || !argv[0]) return -1; + bool capture = (out != NULL && out_sz > 0); + if (capture) out[0] = '\0'; + int pfd[2] = {-1, -1}; + if (capture && pipe(pfd) < 0) return -1; + + pid_t pid = fork(); + if (pid < 0) { + if (capture) { + close(pfd[0]); + close(pfd[1]); + } + return -1; + } + if (pid == 0) { + setpgid(0, 0); + int devnull_r = open("/dev/null", O_RDONLY); + if (devnull_r >= 0) { + dup2(devnull_r, STDIN_FILENO); + if (devnull_r > 2) close(devnull_r); + } else { + close(STDIN_FILENO); + } + if (capture) { + close(pfd[0]); + dup2(pfd[1], STDOUT_FILENO); + dup2(pfd[1], STDERR_FILENO); + if (pfd[1] > 2) close(pfd[1]); + } else { + int devnull_w = open("/dev/null", O_WRONLY); + if (devnull_w >= 0) { + dup2(devnull_w, STDOUT_FILENO); + dup2(devnull_w, STDERR_FILENO); + if (devnull_w > 2) close(devnull_w); + } + } + execvp(argv[0], (char *const *)argv); + _exit(127); + } + + uint64_t deadline = (timeout_ms > 0) ? (plat_now_ms() + (uint64_t)timeout_ms) : UINT64_MAX; + bool timed_out = false; + int status = 0; + + if (!capture) { + while (1) { + pid_t wp = waitpid(pid, &status, WNOHANG); + if (wp == pid) return WIFEXITED(status) ? WEXITSTATUS(status) : 1; + if (wp < 0) { + if (errno == EINTR) continue; + return -1; + } + int step_ms = 15; + if (timeout_ms > 0) { + uint64_t now = plat_now_ms(); + if (now >= deadline) { + timed_out = true; + break; + } + uint64_t rem = deadline - now; + if (rem < (uint64_t)step_ms) step_ms = (int)rem; + } + poll(NULL, 0, step_ms); + } + kill(-pid, SIGKILL); + kill(pid, SIGKILL); + while (waitpid(pid, &status, 0) < 0) { + if (errno != EINTR) return 124; + } + return 124; + } + + close(pfd[1]); + int fl = fcntl(pfd[0], F_GETFL, 0); + if (fl >= 0) fcntl(pfd[0], F_SETFL, fl | O_NONBLOCK); + int fdfl = fcntl(pfd[0], F_GETFD, 0); + if (fdfl >= 0) fcntl(pfd[0], F_SETFD, fdfl | FD_CLOEXEC); + + size_t off = 0; + char tmp[512]; + bool eof = false; + + while (!eof) { + int wait_ms = -1; + if (timeout_ms > 0) { + uint64_t now = plat_now_ms(); + if (now >= deadline) { + timed_out = true; + break; + } + uint64_t rem = deadline - now; + wait_ms = rem > 60000ULL ? 60000 : (int)rem; + } + struct pollfd pf = { .fd = pfd[0], .events = POLLIN | POLLHUP, .revents = 0 }; + int pr = poll(&pf, 1, wait_ms); + if (pr < 0) { + if (errno == EINTR) continue; + break; + } + if (pr == 0) { + timed_out = true; + break; + } + while (1) { + ssize_t n = read(pfd[0], tmp, sizeof(tmp)); + if (n > 0) { + if (off + 1 < out_sz) { + size_t cp = (size_t)n; + if (cp > out_sz - 1 - off) cp = out_sz - 1 - off; + memcpy(out + off, tmp, cp); + off += cp; + } + } else if (n == 0) { + eof = true; + break; + } else { + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) break; + eof = true; + break; + } + } + } + out[off] = '\0'; + close(pfd[0]); + if (timed_out) { + kill(-pid, SIGKILL); + kill(pid, SIGKILL); + } + while (waitpid(pid, &status, 0) < 0) { + if (errno != EINTR) return timed_out ? 124 : -1; + } + if (timed_out) return 124; + return WIFEXITED(status) ? WEXITSTATUS(status) : 1; +} + +int anode_run_priv_timeout(const char *const cmd_argv[], char *out, size_t out_sz, int timeout_ms) { + if (!cmd_argv || !cmd_argv[0]) return -1; + const char *full[32]; + int pfx = anode_priv_prefix(full, 4); + int i = 0; + while (cmd_argv[i] && (pfx + i) < 31) { + full[pfx + i] = cmd_argv[i]; + i++; + } + full[pfx + i] = NULL; + return anode_run_cmd_timeout(full, out, out_sz, timeout_ms); +} + +int anode_spawn_detached(const char *const argv[]) { + if (!argv || !argv[0]) return -1; + pid_t pid = fork(); + if (pid < 0) return -1; + if (pid == 0) { + setsid(); + pid_t pid2 = fork(); + if (pid2 == 0) { + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + dup2(devnull, STDIN_FILENO); + dup2(devnull, STDOUT_FILENO); + dup2(devnull, STDERR_FILENO); + if (devnull > 2) close(devnull); + } + execvp(argv[0], (char *const *)argv); + _exit(127); + } + _exit(0); + } + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {} + return 0; +} + +void anode_signal_procs(const char *const names[], int num_names, int sig) { + if (!names || num_names <= 0) return; + char uid_str[32]; + snprintf(uid_str, sizeof(uid_str), "%u", (unsigned)getuid()); + char out[8192] = {0}; + const char *ps_cmd[] = {"ps", "-u", uid_str, "-o", "pid=,comm=", NULL}; + if (anode_run_cmd_timeout(ps_cmd, out, sizeof(out), 800) != 0 || !out[0]) return; + + pid_t me = getpid(); + char *save = NULL; + for (char *ln = strtok_r(out, "\n", &save); ln; ln = strtok_r(NULL, "\n", &save)) { + while (*ln == ' ' || *ln == '\t') ln++; + if (!isdigit((unsigned char)*ln)) continue; + char *endp = NULL; + long pid = strtol(ln, &endp, 10); + if (pid <= 1 || (pid_t)pid == me || !endp) continue; + while (*endp == ' ' || *endp == '\t') endp++; + size_t clen = strlen(endp); + while (clen > 0 && (endp[clen - 1] == ' ' || endp[clen - 1] == '\r')) { + endp[--clen] = '\0'; + } + const char *base = strrchr(endp, '/'); + base = base ? base + 1 : endp; + for (int i = 0; i < num_names; i++) { + if (strcmp(base, names[i]) == 0 || strcmp(endp, names[i]) == 0) { + kill((pid_t)pid, sig); + break; + } + } + } +} + +void anode_read_battery(anode_battery_info_t *out) { + if (!out) return; + memset(out, 0, sizeof(*out)); + out->capacity = -1; + snprintf(out->status, sizeof(out->status), "AC"); + snprintf(out->detail, sizeof(out->detail), "AC Power"); + +#if defined(__linux__) || defined(__linux) + DIR *d = opendir("/sys/class/power_supply"); + if (d) { + bool found_bat = false; + bool ac_online = false; + char cap[16] = {0}, st[32] = {0}; + struct dirent *de; + while ((de = readdir(d)) != NULL) { + if (de->d_name[0] == '.') continue; + char p[320], typ[32] = {0}; + snprintf(p, sizeof(p), "/sys/class/power_supply/%s/type", de->d_name); + if (plat_read_line(p, typ, sizeof(typ)) != 0) continue; + if (strcmp(typ, "Battery") == 0 && !found_bat) { + snprintf(p, sizeof(p), "/sys/class/power_supply/%s/capacity", de->d_name); + if (plat_read_line(p, cap, sizeof(cap)) == 0 && cap[0]) { + out->capacity = atoi(cap); + if (out->capacity < 0) out->capacity = 0; + if (out->capacity > 100) out->capacity = 100; + } + snprintf(p, sizeof(p), "/sys/class/power_supply/%s/status", de->d_name); + plat_read_line(p, st, sizeof(st)); + found_bat = true; + } else if (strcmp(typ, "Battery") != 0) { + char onl[16] = {0}; + snprintf(p, sizeof(p), "/sys/class/power_supply/%s/online", de->d_name); + if (plat_read_line(p, onl, sizeof(onl)) == 0 && atoi(onl) == 1) { + ac_online = true; + } + } + } + closedir(d); + out->on_ac = ac_online; + if (found_bat) { + out->present = true; + snprintf(out->status, sizeof(out->status), "%s", st[0] ? st : "Idle"); + if (out->capacity >= 0) { + snprintf(out->detail, sizeof(out->detail), "%d%% %s", + out->capacity, + strcmp(out->status, "Charging") == 0 ? "+CHG" + : strcmp(out->status, "Full") == 0 ? "=FULL" + : (ac_online ? "~AC" : "BAT")); + } else { + snprintf(out->detail, sizeof(out->detail), "%s", out->status); + } + } else if (ac_online) { + snprintf(out->detail, sizeof(out->detail), "AC Online"); + } + return; + } +#elif defined(__FreeBSD__) || defined(__DragonFly__) + { + char life[32] = {0}, state[32] = {0}, acline[32] = {0}; + const char *c1[] = {"sysctl", "-n", "hw.acpi.acline", NULL}; + if (anode_run_cmd_timeout(c1, acline, sizeof(acline), 400) == 0 && acline[0]) { + out->on_ac = (atoi(acline) == 1); + } + const char *c2[] = {"sysctl", "-n", "hw.acpi.battery.life", NULL}; + if (anode_run_cmd_timeout(c2, life, sizeof(life), 400) == 0 && life[0] && atoi(life) >= 0) { + out->present = true; + out->capacity = atoi(life); + const char *c3[] = {"sysctl", "-n", "hw.acpi.battery.state", NULL}; + int bstate = 0; + if (anode_run_cmd_timeout(c3, state, sizeof(state), 400) == 0) bstate = atoi(state); + if (bstate & 2) snprintf(out->status, sizeof(out->status), "Charging"); + else if (bstate & 1) snprintf(out->status, sizeof(out->status), "Discharging"); + else snprintf(out->status, sizeof(out->status), out->on_ac ? "Full" : "Idle"); + snprintf(out->detail, sizeof(out->detail), "%d%% %s", + out->capacity, + strcmp(out->status, "Charging") == 0 ? "+CHG" + : strcmp(out->status, "Full") == 0 ? "=FULL" : "BAT"); + return; + } + } +#elif defined(__OpenBSD__) + { + char apm_out[64] = {0}; + const char *c[] = {"apm", "-l", "-a", "-b", NULL}; + if (anode_run_cmd_timeout(c, apm_out, sizeof(apm_out), 400) == 0 && apm_out[0]) { + int pct = -1, ac = 0, bs = 4; + if (sscanf(apm_out, "%d %d %d", &pct, &ac, &bs) >= 2) { + out->on_ac = (ac == 1); + if (pct >= 0 && pct <= 100 && bs != 4) { + out->present = true; + out->capacity = pct; + snprintf(out->status, sizeof(out->status), "%s", + bs == 3 ? "Charging" : (ac ? "Full" : "Discharging")); + snprintf(out->detail, sizeof(out->detail), "%d%% %s", + pct, bs == 3 ? "+CHG" : (ac ? "=AC" : "BAT")); + return; + } + } + } + } +#endif +} + +static bool get_primary_xrandr_output(char *out_name, size_t sz, double *bri_out) { + char out[4096] = {0}; + const char *cmd[] = {"xrandr", "--verbose", NULL}; + if (anode_run_cmd_timeout(cmd, out, sizeof(out), 900) != 0) return false; + char current[64] = {0}; + char first[64] = {0}; + double first_bri = 1.0; + char *save = NULL; + for (char *ln = strtok_r(out, "\n", &save); ln; ln = strtok_r(NULL, "\n", &save)) { + if (ln[0] != ' ' && ln[0] != '\t') { + current[0] = '\0'; + if (strstr(ln, " connected")) { + char name[64] = {0}; + if (sscanf(ln, "%63s", name) == 1) { + snprintf(current, sizeof(current), "%s", name); + if (!first[0]) snprintf(first, sizeof(first), "%s", name); + if (strstr(ln, " primary ")) { + snprintf(out_name, sz, "%s", name); + } + } + } + } else if (current[0]) { + char *bp = strstr(ln, "Brightness:"); + if (bp) { + double bv = atof(bp + 11); + if (strcmp(current, first) == 0) first_bri = bv; + if (strcmp(current, out_name) == 0 && bri_out) { + *bri_out = bv; + return true; + } + } + } + } + if (first[0]) { + snprintf(out_name, sz, "%s", first); + if (bri_out) *bri_out = first_bri; + return true; + } + return false; +} + +bool anode_backlight_get(int *cur_out, int *max_out, char *backend_out, size_t bsz) { + int cur = 100, mx = 100; + if (backend_out && bsz > 0) snprintf(backend_out, bsz, "xrandr"); + +#if defined(__linux__) || defined(__linux) + DIR *d = opendir("/sys/class/backlight"); + if (d) { + struct dirent *de; + while ((de = readdir(d)) != NULL) { + if (de->d_name[0] == '.') continue; + char p[320], b[64]; + snprintf(p, sizeof(p), "/sys/class/backlight/%s/max_brightness", de->d_name); + if (plat_read_line(p, b, sizeof(b)) == 0 && atoi(b) > 0) { + mx = atoi(b); + snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); + if (plat_read_line(p, b, sizeof(b)) == 0) { + cur = atoi(b); + if (cur_out) *cur_out = cur; + if (max_out) *max_out = mx; + if (backend_out && bsz > 0) snprintf(backend_out, bsz, "sysfs:%s", de->d_name); + closedir(d); + return true; + } + } + } + closedir(d); + } + if (anode_have_cmd("brightnessctl")) { + char cbuf[64] = {0}, mbuf[64] = {0}; + const char *gc[] = {"brightnessctl", "get", NULL}; + const char *gm[] = {"brightnessctl", "max", NULL}; + if (anode_run_cmd_timeout(gc, cbuf, sizeof(cbuf), 500) == 0 && + anode_run_cmd_timeout(gm, mbuf, sizeof(mbuf), 500) == 0 && atoi(mbuf) > 0) { + if (cur_out) *cur_out = atoi(cbuf); + if (max_out) *max_out = atoi(mbuf); + if (backend_out && bsz > 0) snprintf(backend_out, bsz, "brightnessctl"); + return true; + } + } +#elif defined(__FreeBSD__) || defined(__DragonFly__) + if (anode_have_cmd("backlight")) { + char out[64] = {0}; + const char *c[] = {"backlight", "-q", NULL}; + if (anode_run_cmd_timeout(c, out, sizeof(out), 500) == 0 && out[0]) { + if (cur_out) *cur_out = atoi(out); + if (max_out) *max_out = 100; + if (backend_out && bsz > 0) snprintf(backend_out, bsz, "backlight"); + return true; + } + } +#elif defined(__OpenBSD__) + if (anode_have_cmd("wsconsctl")) { + char out[64] = {0}; + const char *c[] = {"wsconsctl", "-n", "display.brightness", NULL}; + if (anode_run_cmd_timeout(c, out, sizeof(out), 500) == 0 && out[0]) { + if (cur_out) *cur_out = (int)(atof(out) + 0.5); + if (max_out) *max_out = 100; + if (backend_out && bsz > 0) snprintf(backend_out, bsz, "wsconsctl"); + return true; + } + } +#endif + + char out_name[64] = {0}; + double bri = 1.0; + if (get_primary_xrandr_output(out_name, sizeof(out_name), &bri)) { + if (bri < 0.1) bri = 0.1; + if (bri > 1.0) bri = 1.0; + if (cur_out) *cur_out = (int)(bri * 100.0 + 0.5); + if (max_out) *max_out = 100; + if (backend_out && bsz > 0) snprintf(backend_out, bsz, "xrandr:%s", out_name); + return true; + } + if (cur_out) *cur_out = 100; + if (max_out) *max_out = 100; + return false; +} + +bool anode_backlight_set(double norm) { + if (norm < 0.05) norm = 0.05; + if (norm > 1.0) norm = 1.0; + +#if defined(__linux__) || defined(__linux) + DIR *d = opendir("/sys/class/backlight"); + if (d) { + struct dirent *de; + while ((de = readdir(d)) != NULL) { + if (de->d_name[0] == '.') continue; + char p[320], b[64]; + snprintf(p, sizeof(p), "/sys/class/backlight/%s/max_brightness", de->d_name); + int mx = 0; + if (plat_read_line(p, b, sizeof(b)) == 0 && (mx = atoi(b)) > 0) { + int val = (int)(norm * mx + 0.5); + if (val < 1) val = 1; + if (val > mx) val = mx; + char vbuf[32]; + snprintf(vbuf, sizeof(vbuf), "%d\n", val); + snprintf(p, sizeof(p), "/sys/class/backlight/%s/brightness", de->d_name); + if (plat_write_str(p, vbuf) == 0) { + closedir(d); + return true; + } + } + } + closedir(d); + } + if (anode_have_cmd("brightnessctl")) { + char pct[16]; + snprintf(pct, sizeof(pct), "%d%%", (int)(norm * 100.0 + 0.5)); + const char *c[] = {"brightnessctl", "-q", "set", pct, NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 800) == 0) return true; + } +#elif defined(__FreeBSD__) || defined(__DragonFly__) + if (anode_have_cmd("backlight")) { + char pct[16]; + snprintf(pct, sizeof(pct), "%d", (int)(norm * 100.0 + 0.5)); + const char *c[] = {"backlight", pct, NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 800) == 0) return true; + } +#elif defined(__OpenBSD__) + if (anode_have_cmd("wsconsctl")) { + char arg[48]; + snprintf(arg, sizeof(arg), "display.brightness=%d%%", (int)(norm * 100.0 + 0.5)); + const char *c[] = {"wsconsctl", arg, NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 800) == 0) return true; + } +#endif + + char out_name[64] = {0}; + if (get_primary_xrandr_output(out_name, sizeof(out_name), NULL)) { + char bstr[16]; + snprintf(bstr, sizeof(bstr), "%.2f", norm); + const char *c[] = {"xrandr", "--output", out_name, "--brightness", bstr, NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 900) == 0; + } + return false; +} + +anode_audio_backend_t anode_detect_audio_backend(void) { + char out[256] = {0}; + if (anode_have_cmd("wpctl")) { + const char *c[] = {"wpctl", "get-volume", "@DEFAULT_AUDIO_SINK@", NULL}; + if (anode_run_cmd_timeout(c, out, sizeof(out), 600) == 0 && strstr(out, "Volume:")) { + return ANODE_AUDIO_PIPEWIRE; + } + } + if (anode_have_cmd("pactl")) { + const char *c[] = {"pactl", "info", NULL}; + if (anode_run_cmd_timeout(c, out, sizeof(out), 600) == 0 && strstr(out, "Default Sink:")) { + return ANODE_AUDIO_PULSE; + } + } +#if defined(__OpenBSD__) + if (anode_have_cmd("sndioctl")) return ANODE_AUDIO_SNDIO; +#endif + if (anode_have_cmd("sndioctl")) return ANODE_AUDIO_SNDIO; +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) + if (anode_have_cmd("mixer")) return ANODE_AUDIO_OSS; +#endif + if (anode_have_cmd("amixer")) return ANODE_AUDIO_ALSA; + return ANODE_AUDIO_NONE; +} + +const char *anode_audio_backend_name(anode_audio_backend_t b) { + switch (b) { + case ANODE_AUDIO_PIPEWIRE: return "PipeWire"; + case ANODE_AUDIO_PULSE: return "PulseAudio"; + case ANODE_AUDIO_ALSA: return "ALSA"; + case ANODE_AUDIO_SNDIO: return "sndio"; + case ANODE_AUDIO_OSS: return "OSS"; + default: return "Unavailable"; + } +} + +bool anode_audio_get_default(bool input, int *pct_out, bool *muted_out) { + anode_audio_backend_t b = anode_detect_audio_backend(); + char out[1024] = {0}; + if (b == ANODE_AUDIO_PIPEWIRE) { + const char *tgt = input ? "@DEFAULT_AUDIO_SOURCE@" : "@DEFAULT_AUDIO_SINK@"; + const char *c[] = {"wpctl", "get-volume", tgt, NULL}; + if (anode_run_cmd_timeout(c, out, sizeof(out), 600) == 0) { + const char *p = strstr(out, "Volume:"); + if (p) { + if (pct_out) *pct_out = (int)(atof(p + 7) * 100.0 + 0.5); + if (muted_out) *muted_out = (strstr(out, "[MUTED]") != NULL); + return true; + } + } + } else if (b == ANODE_AUDIO_PULSE) { + const char *tgt = input ? "@DEFAULT_SOURCE@" : "@DEFAULT_SINK@"; + const char *gv[] = {"pactl", input ? "get-source-volume" : "get-sink-volume", tgt, NULL}; + const char *gm[] = {"pactl", input ? "get-source-mute" : "get-sink-mute", tgt, NULL}; + if (anode_run_cmd_timeout(gv, out, sizeof(out), 600) == 0) { + const char *pctp = strchr(out, '%'); + if (pctp && pctp > out) { + const char *q = pctp; + while (q > out && isdigit((unsigned char)q[-1])) q--; + if (pct_out) *pct_out = atoi(q); + } + out[0] = '\0'; + if (muted_out && anode_run_cmd_timeout(gm, out, sizeof(out), 600) == 0) { + *muted_out = (strstr(out, "yes") != NULL); + } + return true; + } + } else if (b == ANODE_AUDIO_ALSA) { + const char *c[] = {"amixer", "get", input ? "Capture" : "Master", NULL}; + if (anode_run_cmd_timeout(c, out, sizeof(out), 600) == 0) { + const char *pctp = strchr(out, '%'); + if (pctp && pctp > out) { + const char *q = pctp; + while (q > out && isdigit((unsigned char)q[-1])) q--; + if (pct_out) *pct_out = atoi(q); + } + if (muted_out) *muted_out = (strstr(out, "[off]") != NULL); + return true; + } + } else if (b == ANODE_AUDIO_SNDIO) { + const char *lvl_k = input ? "input.level" : "output.level"; + const char *mut_k = input ? "input.mute" : "output.mute"; + const char *c1[] = {"sndioctl", "-n", lvl_k, NULL}; + if (anode_run_cmd_timeout(c1, out, sizeof(out), 500) == 0 && out[0]) { + if (pct_out) *pct_out = (int)(atof(out) * 100.0 + 0.5); + out[0] = '\0'; + const char *c2[] = {"sndioctl", "-n", mut_k, NULL}; + if (muted_out && anode_run_cmd_timeout(c2, out, sizeof(out), 500) == 0) { + *muted_out = (atoi(out) != 0); + } + return true; + } + } else if (b == ANODE_AUDIO_OSS) { + const char *c[] = {"mixer", "-S", input ? "mic" : "vol", NULL}; + if (anode_run_cmd_timeout(c, out, sizeof(out), 500) == 0 && out[0]) { + int l = 0, r = 0; + const char *colon = strchr(out, ':'); + if (colon && sscanf(colon + 1, "%d:%d", &l, &r) >= 1) { + if (pct_out) *pct_out = l; + if (muted_out) *muted_out = (l == 0); + return true; + } + } + } + return false; +} + +bool anode_audio_set_vol(bool input, int pct) { + if (pct < 0) pct = 0; + if (pct > 150) pct = 150; + anode_audio_backend_t b = anode_detect_audio_backend(); + char arg[32]; + + if (b == ANODE_AUDIO_PIPEWIRE) { + snprintf(arg, sizeof(arg), "%d%%", pct); + const char *c[] = {"wpctl", "set-volume", "-l", input ? "1.5" : "1.25", + input ? "@DEFAULT_AUDIO_SOURCE@" : "@DEFAULT_AUDIO_SINK@", arg, NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 600) == 0; + } else if (b == ANODE_AUDIO_PULSE) { + snprintf(arg, sizeof(arg), "%d%%", pct); + const char *c[] = {"pactl", input ? "set-source-volume" : "set-sink-volume", + input ? "@DEFAULT_SOURCE@" : "@DEFAULT_SINK@", arg, NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 600) == 0; + } else if (b == ANODE_AUDIO_ALSA) { + if (pct > 100) pct = 100; + snprintf(arg, sizeof(arg), "%d%%", pct); + const char *c[] = {"amixer", "-q", "set", input ? "Capture" : "Master", arg, NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 600) == 0; + } else if (b == ANODE_AUDIO_SNDIO) { + if (pct > 100) pct = 100; + snprintf(arg, sizeof(arg), "%s=%.2f", input ? "input.level" : "output.level", pct / 100.0); + const char *c[] = {"sndioctl", arg, NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 500) == 0; + } else if (b == ANODE_AUDIO_OSS) { + if (pct > 100) pct = 100; + snprintf(arg, sizeof(arg), "%d:%d", pct, pct); + const char *c[] = {"mixer", input ? "mic" : "vol", arg, NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 500) == 0; + } + return false; +} + +bool anode_audio_toggle_mute(bool input) { + anode_audio_backend_t b = anode_detect_audio_backend(); + if (b == ANODE_AUDIO_PIPEWIRE) { + const char *c[] = {"wpctl", "set-mute", + input ? "@DEFAULT_AUDIO_SOURCE@" : "@DEFAULT_AUDIO_SINK@", "toggle", NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 600) == 0; + } else if (b == ANODE_AUDIO_PULSE) { + const char *c[] = {"pactl", input ? "set-source-mute" : "set-sink-mute", + input ? "@DEFAULT_SOURCE@" : "@DEFAULT_SINK@", "toggle", NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 600) == 0; + } else if (b == ANODE_AUDIO_ALSA) { + const char *c[] = {"amixer", "-q", "set", input ? "Capture" : "Master", "toggle", NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 600) == 0; + } else if (b == ANODE_AUDIO_SNDIO) { + const char *c[] = {"sndioctl", input ? "input.mute=!" : "output.mute=!", NULL}; + return anode_run_cmd_timeout(c, NULL, 0, 500) == 0; + } + return false; +} + +bool anode_power_profile_get(char *out, size_t sz) { + if (!out || sz == 0) return false; + snprintf(out, sz, "balanced"); + + char rdir[512]; + anode_runtime_dir(rdir, sizeof(rdir)); + char pfile[544]; + snprintf(pfile, sizeof(pfile), "%s/power-profile", rdir); + if (plat_read_line(pfile, out, sz) == 0 && out[0]) return true; + + if (anode_have_cmd("powerprofilesctl")) { + char pbuf[64] = {0}; + const char *c[] = {"powerprofilesctl", "get", NULL}; + if (anode_run_cmd_timeout(c, pbuf, sizeof(pbuf), 600) == 0 && pbuf[0]) { + if (strstr(pbuf, "power-saver")) snprintf(out, sz, "eco"); + else if (strstr(pbuf, "performance")) snprintf(out, sz, "performance"); + else snprintf(out, sz, "balanced"); + return true; + } + } +#if defined(__linux__) || defined(__linux) + { + char pbuf[64] = {0}; + if (plat_read_line("/sys/firmware/acpi/platform_profile", pbuf, sizeof(pbuf)) == 0) { + if (strcmp(pbuf, "low-power") == 0) snprintf(out, sz, "eco"); + else if (strcmp(pbuf, "performance") == 0) snprintf(out, sz, "performance"); + else snprintf(out, sz, "balanced"); + return true; + } + } +#endif + return false; +} + +bool anode_power_profile_set(const char *profile) { + if (!profile) return false; + const char *norm = "balanced"; + const char *ppd = "balanced"; + const char *acpi = "balanced"; + if (strcmp(profile, "eco") == 0 || strcmp(profile, "power-saver") == 0) { + norm = "eco"; + ppd = "power-saver"; + acpi = "low-power"; + } else if (strcmp(profile, "performance") == 0) { + norm = "performance"; + ppd = "performance"; + acpi = "performance"; + } + + char rdir[512], pfile[544]; + anode_runtime_dir(rdir, sizeof(rdir)); + snprintf(pfile, sizeof(pfile), "%s/power-profile", rdir); + FILE *f = fopen(pfile, "w"); + if (f) { + fprintf(f, "%s\n", norm); + fclose(f); + } + + if (anode_have_cmd("powerprofilesctl")) { + const char *c[] = {"powerprofilesctl", "set", ppd, NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 1200) == 0) return true; + } +#if defined(__linux__) || defined(__linux) + if (access("/sys/firmware/acpi/platform_profile", W_OK) == 0) { + if (plat_write_str("/sys/firmware/acpi/platform_profile", acpi) == 0) return true; + } else if (access("/sys/firmware/acpi/platform_profile", F_OK) == 0) { + const char *c[] = {"sh", "-c", "printf '%s\\n' \"$1\" > /sys/firmware/acpi/platform_profile", + "sh", acpi, NULL}; + if (anode_run_priv_timeout(c, NULL, 0, 1500) == 0) return true; + } +#elif defined(__OpenBSD__) + if (anode_have_cmd("apm")) { + const char *flag = strcmp(norm, "eco") == 0 ? "-L" : (strcmp(norm, "performance") == 0 ? "-H" : "-A"); + const char *c[] = {"apm", flag, NULL}; + if (anode_run_priv_timeout(c, NULL, 0, 1000) == 0) return true; + } +#else + (void)acpi; +#endif + return true; +} + +int anode_power_action(const char *action) { + if (!action) return 1; + if (strcmp(action, "suspend") == 0) { + if (anode_have_cmd("systemctl")) { + const char *c[] = {"systemctl", "suspend", NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 3000) == 0) return 0; + } + if (anode_have_cmd("loginctl")) { + const char *c[] = {"loginctl", "suspend", NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 3000) == 0) return 0; + } + if (anode_have_cmd("zzz")) { + const char *c[] = {"zzz", NULL}; + if (anode_run_priv_timeout(c, NULL, 0, 3000) == 0) return 0; + } + if (anode_have_cmd("acpiconf")) { + const char *c[] = {"acpiconf", "-s", "3", NULL}; + if (anode_run_priv_timeout(c, NULL, 0, 3000) == 0) return 0; + } +#if defined(__linux__) || defined(__linux) + const char *c[] = {"sh", "-c", "printf mem > /sys/power/state", NULL}; + return anode_run_priv_timeout(c, NULL, 0, 3000); +#else + return 1; +#endif + } else if (strcmp(action, "hibernate") == 0) { + if (anode_have_cmd("systemctl")) { + const char *c[] = {"systemctl", "hibernate", NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 3000) == 0) return 0; + } + if (anode_have_cmd("loginctl")) { + const char *c[] = {"loginctl", "hibernate", NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 3000) == 0) return 0; + } + if (anode_have_cmd("ZZZ")) { + const char *c[] = {"ZZZ", NULL}; + if (anode_run_priv_timeout(c, NULL, 0, 3000) == 0) return 0; + } + return 1; + } else if (strcmp(action, "reboot") == 0) { + if (anode_have_cmd("systemctl")) { + const char *c[] = {"systemctl", "reboot", NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 3000) == 0) return 0; + } + if (anode_have_cmd("loginctl")) { + const char *c[] = {"loginctl", "reboot", NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 3000) == 0) return 0; + } + const char *c[] = {"reboot", NULL}; + return anode_run_priv_timeout(c, NULL, 0, 3000); + } else if (strcmp(action, "poweroff") == 0) { + if (anode_have_cmd("systemctl")) { + const char *c[] = {"systemctl", "poweroff", NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 3000) == 0) return 0; + } + if (anode_have_cmd("loginctl")) { + const char *c[] = {"loginctl", "poweroff", NULL}; + if (anode_run_cmd_timeout(c, NULL, 0, 3000) == 0) return 0; + } +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) + const char *c[] = {"shutdown", "-p", "now", NULL}; + return anode_run_priv_timeout(c, NULL, 0, 3000); +#else + const char *c[] = {"poweroff", NULL}; + return anode_run_priv_timeout(c, NULL, 0, 3000); +#endif + } + return 1; +} + +static bool iface_looks_wireless(const char *name) { + if (!name || !name[0]) return false; +#if defined(__linux__) || defined(__linux) + char p[128]; + snprintf(p, sizeof(p), "/sys/class/net/%s/wireless", name); + if (access(p, F_OK) == 0) return true; + snprintf(p, sizeof(p), "/sys/class/net/%s/phy80211", name); + if (access(p, F_OK) == 0) return true; +#endif + if (strncmp(name, "wlan", 4) == 0 || strncmp(name, "wlp", 3) == 0 || + strncmp(name, "iwm", 3) == 0 || strncmp(name, "iwn", 3) == 0 || + strncmp(name, "iwlwifi", 7) == 0 || strncmp(name, "ath", 3) == 0 || + strncmp(name, "rtw", 3) == 0 || strncmp(name, "urtwn", 5) == 0) { + return true; + } + return false; +} + +int anode_list_net_ifaces(anode_net_iface_t *out, int max_ifaces) { + if (!out || max_ifaces <= 0) return 0; + struct ifaddrs *ifap = NULL; + if (getifaddrs(&ifap) != 0 || !ifap) return 0; + + int count = 0; + for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (!ifa->ifa_name || !ifa->ifa_name[0]) continue; + int idx = -1; + for (int i = 0; i < count; i++) { + if (strcmp(out[i].name, ifa->ifa_name) == 0) { + idx = i; + break; + } + } + if (idx < 0) { + if (count >= max_ifaces) continue; + idx = count++; + memset(&out[idx], 0, sizeof(out[idx])); + snprintf(out[idx].name, sizeof(out[idx].name), "%s", ifa->ifa_name); + out[idx].is_up = (ifa->ifa_flags & IFF_UP) != 0; +#ifdef IFF_RUNNING + out[idx].is_running = (ifa->ifa_flags & IFF_RUNNING) != 0; +#else + out[idx].is_running = out[idx].is_up; +#endif + out[idx].is_loopback = (ifa->ifa_flags & IFF_LOOPBACK) != 0; + out[idx].is_wireless = iface_looks_wireless(ifa->ifa_name); + } + if (!ifa->ifa_addr) continue; + if (ifa->ifa_addr->sa_family == AF_INET && !out[idx].ipv4[0]) { + const struct sockaddr_in *sin = (const struct sockaddr_in *)ifa->ifa_addr; + inet_ntop(AF_INET, &sin->sin_addr, out[idx].ipv4, sizeof(out[idx].ipv4)); + } else if (ifa->ifa_addr->sa_family == AF_INET6 && !out[idx].ipv6[0]) { + const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)ifa->ifa_addr; + if (!IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) { + inet_ntop(AF_INET6, &sin6->sin6_addr, out[idx].ipv6, sizeof(out[idx].ipv6)); + } + } + } + freeifaddrs(ifap); + return count; +} + +bool anode_find_wifi_iface(char *out, size_t sz) { + if (!out || sz == 0) return false; + out[0] = '\0'; + anode_net_iface_t ifaces[ANODE_MAX_IFACES]; + int n = anode_list_net_ifaces(ifaces, ANODE_MAX_IFACES); + for (int i = 0; i < n; i++) { + if (!ifaces[i].is_loopback && ifaces[i].is_wireless) { + snprintf(out, sz, "%s", ifaces[i].name); + return true; + } + } + return false; +} diff --git a/src/common/anode_plat.h b/src/common/anode_plat.h new file mode 100644 index 0000000..27fbf1a --- /dev/null +++ b/src/common/anode_plat.h @@ -0,0 +1,84 @@ +/* + * ANODE Cross-Unix Platform Abstraction (Linux, FreeBSD, OpenBSD, NetBSD, POSIX) + */ +#ifndef ANODE_PLAT_H +#define ANODE_PLAT_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ANODE_MAX_IFACES 32 + +typedef enum { + ANODE_AUDIO_NONE = 0, + ANODE_AUDIO_PIPEWIRE, + ANODE_AUDIO_PULSE, + ANODE_AUDIO_ALSA, + ANODE_AUDIO_SNDIO, + ANODE_AUDIO_OSS +} anode_audio_backend_t; + +typedef struct { + bool present; + bool on_ac; + int capacity; /* 0..100, or -1 if unknown */ + char status[32]; /* Charging, Discharging, Full, AC, Unknown */ + char detail[64]; +} anode_battery_info_t; + +typedef struct { + char name[32]; + bool is_up; + bool is_running; + bool is_loopback; + bool is_wireless; + char ipv4[48]; + char ipv6[64]; +} anode_net_iface_t; + +/* Directories & environment */ +void anode_config_dir(char *buf, size_t sz); +void anode_runtime_dir(char *buf, size_t sz); +void anode_themes_sys_dir(char *buf, size_t sz); +void anode_default_xth_path(char *buf, size_t sz); + +/* Process execution & privilege escalation */ +bool anode_have_cmd(const char *cmd); +int anode_priv_prefix(const char *argv_out[], int max_slots); +int anode_run_cmd_timeout(const char *const argv[], char *out, size_t out_sz, int timeout_ms); +int anode_run_priv_timeout(const char *const cmd_argv[], char *out, size_t out_sz, int timeout_ms); +int anode_spawn_detached(const char *const argv[]); +void anode_signal_procs(const char *const names[], int num_names, int sig); + +/* Battery & AC status */ +void anode_read_battery(anode_battery_info_t *out); + +/* Backlight (sysfs / brightnessctl / BSD backlight / wsconsctl / xrandr fallback) */ +bool anode_backlight_get(int *cur_out, int *max_out, char *backend_out, size_t bsz); +bool anode_backlight_set(double norm); + +/* Audio backend abstraction */ +anode_audio_backend_t anode_detect_audio_backend(void); +const char *anode_audio_backend_name(anode_audio_backend_t b); +bool anode_audio_get_default(bool input, int *pct_out, bool *muted_out); +bool anode_audio_set_vol(bool input, int pct); +bool anode_audio_toggle_mute(bool input); + +/* Power profiles & system power transitions */ +bool anode_power_profile_get(char *out, size_t sz); +bool anode_power_profile_set(const char *profile); +int anode_power_action(const char *action); /* suspend, hibernate, reboot, poweroff */ + +/* Network interfaces (POSIX getifaddrs across Linux & BSDs) */ +int anode_list_net_ifaces(anode_net_iface_t *out, int max_ifaces); +bool anode_find_wifi_iface(char *out, size_t sz); + +#ifdef __cplusplus +} +#endif + +#endif /* ANODE_PLAT_H */ diff --git a/src/common/anode_power_policy.h b/src/common/anode_power_policy.h new file mode 100644 index 0000000..2da07e1 --- /dev/null +++ b/src/common/anode_power_policy.h @@ -0,0 +1,107 @@ +/* + * ANODE Power Policy State Machine (shared across anode-powerd and tests) + */ +#ifndef ANODE_POWER_POLICY_H +#define ANODE_POWER_POLICY_H + +#include +#include + +typedef enum { + ANODE_PWR_ACTIVE = 0, + ANODE_PWR_DIMMED, + ANODE_PWR_LOCKED, + ANODE_PWR_SUSPENDED +} anode_pwr_state_t; + +typedef struct { + uint32_t dim_ms; + uint32_t lock_ms; + uint32_t suspend_ms; + int crit_batt_pct; + bool suspend_on_ac; +} anode_power_cfg_t; + +typedef struct { + bool dim_now; + bool restore_brightness; + bool lock_now; + bool suspend_now; + bool warn_low_batt; +} anode_power_actions_t; + +static inline anode_power_cfg_t anode_power_cfg_default(void) { + anode_power_cfg_t c; + c.dim_ms = 60000U; + c.lock_ms = 180000U; + c.suspend_ms = 600000U; + c.crit_batt_pct = 5; + c.suspend_on_ac = false; + return c; +} + +static inline void anode_power_policy_step(const anode_power_cfg_t *cfg, + anode_pwr_state_t *state, + uint32_t idle_ms, + bool on_ac, + int batt_pct, + bool batt_present, + bool screen_locked, + anode_power_actions_t *out) { + anode_power_actions_t a = {0}; + if (!cfg || !state) { + if (out) *out = a; + return; + } + + /* Critical battery check takes precedence on battery */ + if (batt_present && !on_ac && batt_pct >= 0 && batt_pct <= cfg->crit_batt_pct) { + a.warn_low_batt = true; + if (batt_pct <= (cfg->crit_batt_pct > 2 ? cfg->crit_batt_pct - 2 : 1)) { + if (*state != ANODE_PWR_SUSPENDED) { + *state = ANODE_PWR_SUSPENDED; + a.suspend_now = true; + } + if (out) *out = a; + return; + } + } + + /* User activity resumes from dimmed/suspended */ + if (idle_ms < cfg->dim_ms) { + if (*state == ANODE_PWR_DIMMED || *state == ANODE_PWR_SUSPENDED) { + a.restore_brightness = true; + } + *state = screen_locked ? ANODE_PWR_LOCKED : ANODE_PWR_ACTIVE; + if (out) *out = a; + return; + } + + if (cfg->suspend_ms > 0 && idle_ms >= cfg->suspend_ms && (cfg->suspend_on_ac || !on_ac)) { + if (*state != ANODE_PWR_SUSPENDED) { + if (!screen_locked) a.lock_now = true; + a.suspend_now = true; + *state = ANODE_PWR_SUSPENDED; + } + if (out) *out = a; + return; + } + + if (cfg->lock_ms > 0 && idle_ms >= cfg->lock_ms) { + if (*state < ANODE_PWR_LOCKED) { + if (!screen_locked) a.lock_now = true; + *state = ANODE_PWR_LOCKED; + } + if (out) *out = a; + return; + } + + if (cfg->dim_ms > 0 && idle_ms >= cfg->dim_ms && *state == ANODE_PWR_ACTIVE) { + *state = ANODE_PWR_DIMMED; + a.dim_now = true; + } + + if (out) *out = a; +} + +#endif /* ANODE_POWER_POLICY_H */ diff --git a/src/common/anode_scale.h b/src/common/anode_scale.h new file mode 100644 index 0000000..1786f89 --- /dev/null +++ b/src/common/anode_scale.h @@ -0,0 +1,173 @@ +/* + * ANODE Fractional DPI Scaling & Xresources Helpers + */ +#ifndef ANODE_SCALE_H +#define ANODE_SCALE_H + +#include +#include +#include +#include +#include +#include +#include +#include + +static inline double anode_clamp_scale(double s) { + if (s < 0.5) return 0.5; + if (s > 4.0) return 4.0; + return s; +} + +static inline double anode_clamp_dpi(double d) { + if (d < 48.0) return 48.0; + if (d > 384.0) return 384.0; + return d; +} + +static inline double anode_scale_from_dpi(double dpi) { + if (dpi <= 1.0) return 1.0; + return anode_clamp_scale(dpi / 96.0); +} + +static inline int anode_scale_px(int logical_px, double scale) { + if (logical_px <= 0) return 0; + double s = anode_clamp_scale(scale); + int v = (int)floor((double)logical_px * s + 0.5); + return v < 1 ? 1 : v; +} + +static inline int anode_parse_positive_double(const char *s, double *out) { + if (!s || !s[0] || !out) return 0; + char *end = NULL; + double v = strtod(s, &end); + if (end == s || v <= 0.0) return 0; + *out = v; + return 1; +} + +static inline int anode_parse_bool_str(const char *s, int defval) { + if (!s || !s[0]) return defval; + if (s[0] == '1' || s[0] == 'y' || s[0] == 'Y' || s[0] == 't' || s[0] == 'T') return 1; + if (s[0] == '0' || s[0] == 'n' || s[0] == 'N' || s[0] == 'f' || s[0] == 'F') return 0; + return defval; +} + +static inline double anode_detect_edid_dpi(Display *dpy) { + if (!dpy) return 96.0; + int scr = DefaultScreen(dpy); + int pw = DisplayWidth(dpy, scr); + int mm = DisplayWidthMM(dpy, scr); + if (pw > 0 && mm > 20) { + double dpi = (double)pw * 25.4 / (double)mm; + if (dpi >= 72.0 && dpi <= 384.0) { + return dpi; + } + } + return 96.0; +} + +static inline XrmDatabase anode_open_xres_db(Display *dpy) { + XrmInitialize(); + XrmDatabase db = NULL; + const char *override = getenv("ANODE_XRESOURCES"); + if (override && override[0]) { + db = XrmGetFileDatabase(override); + if (db) return db; + } + + const char *home = getenv("HOME"); + if (home && home[0]) { + char path[512]; + snprintf(path, sizeof(path), "%s/.Xresources", home); + db = XrmGetFileDatabase(path); + } + + if (dpy) { + char *xrm = XResourceManagerString(dpy); + XrmDatabase mdb = NULL; + if (xrm && xrm[0]) { + mdb = XrmGetStringDatabase(xrm); + } else { + Atom actual_type = None; + int actual_format = 0; + unsigned long nitems = 0, bytes_after = 0; + unsigned char *prop = NULL; + if (XGetWindowProperty(dpy, DefaultRootWindow(dpy), XA_RESOURCE_MANAGER, + 0L, 65536L, False, XA_STRING, &actual_type, + &actual_format, &nitems, &bytes_after, &prop) == Success && prop) { + if (actual_type == XA_STRING && actual_format == 8 && nitems > 0) { + mdb = XrmGetStringDatabase((const char *)prop); + } + XFree(prop); + } + } + if (mdb) { + if (db) { + XrmMergeDatabases(mdb, &db); + } else { + db = mdb; + } + } + } + return db; +} + +static inline void anode_read_xres_scale_from_db(XrmDatabase db, Display *dpy, + double *dpi_out, double *scale_out, + int *touch_out) { + double dpi = 0.0; + double scale = 0.0; + int touch = 0; + int have_dpi = 0; + int have_scale = 0; + + if (db) { + char *type = NULL; + XrmValue val; + double v = 0.0; + if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &val) && val.addr && + anode_parse_positive_double(val.addr, &v)) { + dpi = anode_clamp_dpi(v); + have_dpi = 1; + } + if (XrmGetResource(db, "anode.scale", "Anode.Scale", &type, &val) && val.addr && + anode_parse_positive_double(val.addr, &v)) { + scale = anode_clamp_scale(v); + have_scale = 1; + } + if (XrmGetResource(db, "anode.touchMode", "Anode.TouchMode", &type, &val) && val.addr) { + touch = anode_parse_bool_str(val.addr, 0); + } + } + + if (!have_scale && !have_dpi) { + double env_s = 0.0; + if (anode_parse_positive_double(getenv("ANODE_SCALE"), &env_s)) { + scale = anode_clamp_scale(env_s); + dpi = 96.0 * scale; + } else { + dpi = anode_detect_edid_dpi(dpy); + /* Avoid tiny/odd virtual screen DPI shifts on standard ~96 DPI displays */ + if (dpi >= 84.0 && dpi <= 108.0) dpi = 96.0; + scale = anode_scale_from_dpi(dpi); + } + } else if (have_scale && !have_dpi) { + dpi = anode_clamp_dpi(96.0 * scale); + } else if (have_dpi && !have_scale) { + scale = anode_scale_from_dpi(dpi); + } + + if (dpi_out) *dpi_out = dpi; + if (scale_out) *scale_out = scale; + if (touch_out) *touch_out = touch; +} + +static inline void anode_read_xres_scale(Display *dpy, double *dpi_out, + double *scale_out, int *touch_out) { + XrmDatabase db = anode_open_xres_db(dpy); + anode_read_xres_scale_from_db(db, dpy, dpi_out, scale_out, touch_out); + if (db) XrmDestroyDatabase(db); +} + +#endif /* ANODE_SCALE_H */ diff --git a/src/common/anode_tz_valid.h b/src/common/anode_tz_valid.h new file mode 100644 index 0000000..dfbb73d --- /dev/null +++ b/src/common/anode_tz_valid.h @@ -0,0 +1,45 @@ +/* + * Header-only C11 helpers for validating IANA timezone names and TZif files. + */ +#ifndef ANODE_TZ_VALID_H +#define ANODE_TZ_VALID_H + +#include +#include +#include +#include +#include +#include + +static inline bool anode_tz_name_valid(const char *tz) { + size_t len; + if (!tz) return false; + len = strlen(tz); + if (len == 0 || len > 95) return false; + if (tz[0] == '/' || tz[len - 1] == '/') return false; + if (strstr(tz, "..") != NULL || strstr(tz, "//") != NULL) return false; + for (size_t i = 0; i < len; i++) { + unsigned char c = (unsigned char)tz[i]; + bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || c == '_' || c == '+' || c == '-' || c == '/'; + if (!ok) return false; + } + return true; +} + +static inline bool anode_tz_file_valid(const char *zoneinfo_root, const char *tz) { + if (!zoneinfo_root || !zoneinfo_root[0] || !anode_tz_name_valid(tz)) return false; + char path[512]; + int n = snprintf(path, sizeof(path), "%s/%s", zoneinfo_root, tz); + if (n < 0 || (size_t)n >= sizeof(path)) return false; + struct stat st; + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) return false; + int fd = open(path, O_RDONLY); + if (fd < 0) return false; + char hdr[4]; + ssize_t r = read(fd, hdr, sizeof(hdr)); + close(fd); + return r == 4 && memcmp(hdr, "TZif", 4) == 0; +} + +#endif /* ANODE_TZ_VALID_H */ diff --git a/src/common/anode_wifi_list.h b/src/common/anode_wifi_list.h new file mode 100644 index 0000000..532dd5a --- /dev/null +++ b/src/common/anode_wifi_list.h @@ -0,0 +1,301 @@ +/* + * Header-only C11 helpers for parsing and grouping Wi-Fi scan output + * (nmcli terse, wpa_cli scan_results, and BSD ifconfig list scan). + */ +#ifndef ANODE_WIFI_LIST_H +#define ANODE_WIFI_LIST_H + +#include +#include +#include +#include + +#define ANODE_MAX_WIFI_GROUPS 32 + +typedef struct { + char ssid[96]; + char best_bssid[24]; + char security[48]; + int best_signal; + int best_chan; + int ap_count; + bool best_joinable; + bool in_use; +} anode_wifi_group_t; + +static inline int anode_split_nmcli_terse(char *line, char **fields, int max_fields) { + if (!line || !fields || max_fields <= 0) return 0; + int count = 0; + fields[count++] = line; + char *rd = line; + char *wr = line; + while (*rd) { + if (rd[0] == '\\' && (rd[1] == ':' || rd[1] == '\\')) { + *wr++ = rd[1]; + rd += 2; + } else if (rd[0] == ':' && count < max_fields) { + *wr++ = '\0'; + fields[count++] = wr; + rd++; + } else { + *wr++ = *rd++; + } + } + *wr = '\0'; + return count; +} + +static inline bool anode_wifi_chan_joinable(int chan) { + return (chan >= 1 && chan <= 13) || + (chan >= 36 && chan <= 48) || + (chan >= 149 && chan <= 165); +} + +static inline int anode_wifi_group_cmp(const void *pa, const void *pb) { + const anode_wifi_group_t *a = (const anode_wifi_group_t *)pa; + const anode_wifi_group_t *b = (const anode_wifi_group_t *)pb; + if (a->in_use != b->in_use) return b->in_use ? 1 : -1; + if (a->best_signal != b->best_signal) return (b->best_signal > a->best_signal) ? 1 : -1; + return strcmp(a->ssid, b->ssid); +} + +static inline int anode_wifi_freq_to_chan(int mhz) { + if (mhz == 2484) return 14; + if (mhz >= 2412 && mhz <= 2472) return (mhz - 2407) / 5; + if (mhz >= 5000 && mhz <= 5895) return (mhz - 5000) / 5; + return 0; +} + +static inline void anode_wifi_upsert_ap(anode_wifi_group_t *groups, int *count, int max_groups, + const char *ssid, const char *bssid, + int chan, int sig, const char *sec, bool active) { + if (!ssid || !ssid[0] || !groups || !count || max_groups <= 0) return; + if (!sec || !sec[0] || strcmp(sec, "--") == 0) sec = "Open"; + bool joinable = anode_wifi_chan_joinable(chan); + + int idx = -1; + for (int i = 0; i < *count; i++) { + if (strcmp(groups[i].ssid, ssid) == 0) { + idx = i; + break; + } + } + + if (idx < 0) { + if (*count >= max_groups) return; + anode_wifi_group_t *g = &groups[(*count)++]; + memset(g, 0, sizeof(*g)); + snprintf(g->ssid, sizeof(g->ssid), "%s", ssid); + snprintf(g->best_bssid, sizeof(g->best_bssid), "%s", bssid ? bssid : ""); + snprintf(g->security, sizeof(g->security), "%s", sec); + g->best_signal = sig; + g->best_chan = chan; + g->best_joinable = joinable; + g->ap_count = 1; + g->in_use = active; + } else { + anode_wifi_group_t *g = &groups[idx]; + g->ap_count++; + if (active) g->in_use = true; + if (strcmp(g->security, "Open") == 0 && strcmp(sec, "Open") != 0) { + snprintf(g->security, sizeof(g->security), "%s", sec); + } + bool better = false; + if (joinable && !g->best_joinable) { + better = true; + } else if (joinable == g->best_joinable) { + if (sig > g->best_signal) better = true; + else if (sig == g->best_signal && chan >= 36 && g->best_chan < 36) better = true; + } + if (better) { + snprintf(g->best_bssid, sizeof(g->best_bssid), "%s", bssid ? bssid : ""); + g->best_signal = sig; + g->best_chan = chan; + g->best_joinable = joinable; + snprintf(g->security, sizeof(g->security), "%s", sec); + } + } +} + +static inline int anode_parse_wifi_scan(const char *nmcli_out, + anode_wifi_group_t *groups, + int max_groups) { + if (!nmcli_out || !groups || max_groups <= 0) return 0; + int n = 0; + const char *cur = nmcli_out; + while (*cur) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[512]; + size_t l = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, l); + ln[l] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + while (l > 0 && ln[l - 1] == '\r') ln[--l] = '\0'; + if (!ln[0]) continue; + + char *fields[6] = {0}; + if (anode_split_nmcli_terse(ln, fields, 6) < 6) continue; + anode_wifi_upsert_ap(groups, &n, max_groups, + fields[2], fields[1], atoi(fields[3]), atoi(fields[4]), + fields[5], fields[0][0] == '*'); + } + if (n > 1) qsort(groups, (size_t)n, sizeof(groups[0]), anode_wifi_group_cmp); + return n; +} + +static inline int anode_parse_wpa_scan(const char *wpa_out, const char *active_ssid, + anode_wifi_group_t *groups, int max_groups) { + if (!wpa_out || !groups || max_groups <= 0) return 0; + int n = 0; + const char *cur = wpa_out; + while (*cur) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[512]; + size_t l = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, l); + ln[l] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + while (l > 0 && ln[l - 1] == '\r') ln[--l] = '\0'; + if (!ln[0] || strncmp(ln, "bssid", 5) == 0) continue; + + char *bssid = ln; + char *t1 = strchr(bssid, '\t'); + if (!t1) continue; + *t1++ = '\0'; + char *t2 = strchr(t1, '\t'); + if (!t2) continue; + *t2++ = '\0'; + char *t3 = strchr(t2, '\t'); + if (!t3) continue; + *t3++ = '\0'; + char *t4 = strchr(t3, '\t'); + if (!t4) continue; + *t4++ = '\0'; + + int chan = anode_wifi_freq_to_chan(atoi(t1)); + int dbm = atoi(t2); + int pct = 2 * (dbm + 100); + if (pct < 5) pct = 5; + if (pct > 100) pct = 100; + const char *sec = strstr(t3, "WPA") ? "WPA2" : (strstr(t3, "WEP") ? "WEP" : "Open"); + bool act = (active_ssid && active_ssid[0] && strcmp(t4, active_ssid) == 0); + anode_wifi_upsert_ap(groups, &n, max_groups, t4, bssid, chan, pct, sec, act); + } + if (n > 1) qsort(groups, (size_t)n, sizeof(groups[0]), anode_wifi_group_cmp); + return n; +} + +static inline bool anode_parse_iw_link(const char *iw_out, + char *bssid, size_t bssid_sz, + char *ssid, size_t ssid_sz, + int *chan_out, int *sig_pct_out) { + if (bssid && bssid_sz > 0) bssid[0] = '\0'; + if (ssid && ssid_sz > 0) ssid[0] = '\0'; + if (chan_out) *chan_out = 0; + if (sig_pct_out) *sig_pct_out = 0; + if (!iw_out || !iw_out[0]) return false; + + bool connected = false; + const char *cur = iw_out; + while (*cur) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[256]; + size_t l = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, l); + ln[l] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + while (l > 0 && ln[l - 1] == '\r') ln[--l] = '\0'; + + const char *p = ln; + while (*p == ' ' || *p == '\t') p++; + if (strncmp(p, "Not connected", 13) == 0) return false; + + if (strncmp(p, "Connected to ", 13) == 0) { + connected = true; + p += 13; + if (bssid && bssid_sz > 0) { + size_t i = 0; + while (p[i] && p[i] != ' ' && p[i] != '\t' && i + 1 < bssid_sz) { + bssid[i] = p[i]; + i++; + } + bssid[i] = '\0'; + } + } else if (strncmp(p, "SSID: ", 6) == 0) { + if (ssid && ssid_sz > 0) snprintf(ssid, ssid_sz, "%s", p + 6); + } else if (strncmp(p, "freq: ", 6) == 0) { + int ch = anode_wifi_freq_to_chan(atoi(p + 6)); + if (chan_out && ch > 0) *chan_out = ch; + } else if (strncmp(p, "signal: ", 8) == 0) { + int dbm = atoi(p + 8); + int pct = 2 * (dbm + 100); + if (pct < 5) pct = 5; + if (pct > 100) pct = 100; + if (sig_pct_out) *sig_pct_out = pct; + } + } + return connected; +} + +static inline int anode_merge_active_wifi(anode_wifi_group_t *groups, + int count, + int max_groups, + const char *active_ssid, + const char *active_bssid, + int active_chan, + int active_signal, + const char *active_security) { + if (!groups || max_groups <= 0) return 0; + if (count < 0) count = 0; + if (count > max_groups) count = max_groups; + if (!active_ssid || !active_ssid[0]) return count; + + int idx = -1; + for (int i = 0; i < count; i++) { + if (strcmp(groups[i].ssid, active_ssid) == 0) { + groups[i].in_use = true; + idx = i; + } else { + groups[i].in_use = false; + } + } + + if (idx >= 0) { + anode_wifi_group_t *g = &groups[idx]; + if (g->best_signal <= 0 && active_signal > 0) g->best_signal = active_signal; + if (g->best_chan <= 0 && active_chan > 0) { + g->best_chan = active_chan; + g->best_joinable = anode_wifi_chan_joinable(active_chan); + } + if (!g->best_bssid[0] && active_bssid && active_bssid[0]) { + snprintf(g->best_bssid, sizeof(g->best_bssid), "%s", active_bssid); + } + if ((!g->security[0] || strcmp(g->security, "--") == 0) && + active_security && active_security[0]) { + snprintf(g->security, sizeof(g->security), "%s", active_security); + } + } else { + int pos = (count < max_groups) ? count++ : max_groups - 1; + anode_wifi_group_t *g = &groups[pos]; + memset(g, 0, sizeof(*g)); + snprintf(g->ssid, sizeof(g->ssid), "%s", active_ssid); + if (active_bssid && active_bssid[0]) { + snprintf(g->best_bssid, sizeof(g->best_bssid), "%s", active_bssid); + } + snprintf(g->security, sizeof(g->security), "%s", + (active_security && active_security[0]) ? active_security : "Connected"); + g->best_signal = (active_signal > 0) ? active_signal : 0; + g->best_chan = active_chan; + g->best_joinable = anode_wifi_chan_joinable(active_chan); + g->ap_count = 1; + g->in_use = true; + } + + if (count > 1) qsort(groups, (size_t)count, sizeof(groups[0]), anode_wifi_group_cmp); + return count; +} + +#endif /* ANODE_WIFI_LIST_H */ diff --git a/src/daemons/anode-checkpw.c b/src/daemons/anode-checkpw.c new file mode 100644 index 0000000..4a88174 --- /dev/null +++ b/src/daemons/anode-checkpw.c @@ -0,0 +1,108 @@ +#define _XOPEN_SOURCE 700 +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_SHADOW_H +#include +#endif +#ifdef HAVE_CRYPT_H +#include +#endif + +static void wipe_mem(void *p, size_t len) { + volatile unsigned char *vp = (volatile unsigned char *)p; + if (!vp) return; + while (len--) *vp++ = 0; +} + +static bool const_time_eq(const char *a, const char *b) { + if (!a || !b) return false; + size_t la = strlen(a), lb = strlen(b); + if (la == 0 || la != lb) return false; + unsigned char diff = 0; + for (size_t i = 0; i < la; i++) { + diff |= (unsigned char)a[i] ^ (unsigned char)b[i]; + } + return diff == 0; +} + +static void strip_eol(char *s) { + size_t n = strlen(s); + while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r')) { + s[--n] = '\0'; + } +} + +int main(int argc, char *argv[]) { + const char *user_arg = (argc > 1 && argv[1][0]) ? argv[1] : NULL; + char line1[256] = {0}; + char line2[256] = {0}; + const char *username = NULL; + const char *password = NULL; + + /* Read credentials from stdin: either "password\n" (with user argv) or "user\npassword\n" */ + if (!fgets(line1, sizeof(line1), stdin)) { + wipe_mem(line1, sizeof(line1)); + return 1; + } + strip_eol(line1); + if (user_arg) { + username = user_arg; + password = line1; + } else { + if (!fgets(line2, sizeof(line2), stdin)) { + wipe_mem(line1, sizeof(line1)); + wipe_mem(line2, sizeof(line2)); + return 1; + } + strip_eol(line2); + username = line1; + password = line2; + } + + if (!username[0]) { + const struct passwd *pw = getpwuid(getuid()); + username = pw ? pw->pw_name : NULL; + } + if (!username || !username[0] || !password[0]) { + wipe_mem(line1, sizeof(line1)); + wipe_mem(line2, sizeof(line2)); + return 1; + } + + const char *stored_hash = NULL; +#ifdef HAVE_SHADOW_H + struct spwd *sp = getspnam(username); + if (sp && sp->sp_pwdp) { + stored_hash = sp->sp_pwdp; + } +#endif + if (!stored_hash || !stored_hash[0] || + strcmp(stored_hash, "x") == 0 || strcmp(stored_hash, "*") == 0) { + struct passwd *pw = getpwnam(username); + if (pw && pw->pw_passwd) { + stored_hash = pw->pw_passwd; + } + } + + bool ok = false; + if (stored_hash && stored_hash[0] && + stored_hash[0] != '!' && stored_hash[0] != '*' && + strcmp(stored_hash, "x") != 0) { + char *computed = crypt(password, stored_hash); + if (computed) { + ok = const_time_eq(computed, stored_hash); + wipe_mem(computed, strlen(computed)); + } + } + + wipe_mem(line1, sizeof(line1)); + wipe_mem(line2, sizeof(line2)); + return ok ? 0 : 1; +} diff --git a/src/daemons/anode-dnsctl.c b/src/daemons/anode-dnsctl.c new file mode 100644 index 0000000..d4e110c --- /dev/null +++ b/src/daemons/anode-dnsctl.c @@ -0,0 +1,132 @@ +#define _POSIX_C_SOURCE 200809L +#include "anode_dns_valid.h" +#include "anode_plat.h" + +#include +#include +#include +#include +#include +#include +#include + +static void print_usage(void) { + fprintf(stderr, "Usage: anode-dnsctl | custom >\n"); +} + +static int write_resolv_conf(const char v4[][16], int n4, const char v6[][46], int n6, const char *tag) { + char content[1024]; + size_t off = 0; + off += (size_t)snprintf(content + off, sizeof(content) - off, + "# Managed by anode-dnsctl (%s)\n", tag ? tag : "custom"); + for (int i = 0; i < n4 && off + 32 < sizeof(content); i++) { + off += (size_t)snprintf(content + off, sizeof(content) - off, "nameserver %s\n", v4[i]); + } + for (int i = 0; i < n6 && off + 64 < sizeof(content); i++) { + off += (size_t)snprintf(content + off, sizeof(content) - off, "nameserver %s\n", v6[i]); + } + + if (n4 + n6 == 0) { + if (anode_have_cmd("resolvconf")) { + const char *rm_args[] = {"resolvconf", "-d", "anode", NULL}; + anode_run_cmd_timeout(rm_args, NULL, 0, 2000); + } + /* Leave router/DHCP fallback comment only if managing /etc/resolv.conf directly */ + off += (size_t)snprintf(content + off, sizeof(content) - off, "# Using DHCP/router resolvers\n"); + } else if (anode_have_cmd("resolvconf")) { + FILE *p = popen("resolvconf -a anode 2>/dev/null", "w"); + if (p) { + fwrite(content, 1, off, p); + if (pclose(p) == 0) return 0; + } + } + + const char *tmp = "/etc/resolv.conf.anode.tmp"; + int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) { + fprintf(stderr, "anode-dnsctl: cannot write %s: %s\n", tmp, strerror(errno)); + return 1; + } + ssize_t w = write(fd, content, off); + int fs_rc = fsync(fd); + close(fd); + if (w < 0 || (size_t)w != off || fs_rc != 0) { + unlink(tmp); + return 1; + } + chmod(tmp, 0644); + if (rename(tmp, "/etc/resolv.conf") != 0) { + unlink(tmp); + fprintf(stderr, "anode-dnsctl: rename failed: %s\n", strerror(errno)); + return 1; + } + return 0; +} + +int main(int argc, char *argv[]) { + if (argc < 2) { + print_usage(); + return 2; + } + if (strcmp(argv[1], "get") == 0) { + char rbuf[4096] = {0}; + char csv[256] = {0}; + FILE *rf = fopen("/etc/resolv.conf", "r"); + if (rf) { + size_t rd = fread(rbuf, 1, sizeof(rbuf) - 1, rf); + rbuf[rd] = '\0'; + fclose(rf); + anode_parse_resolv_conf(rbuf, csv, sizeof(csv)); + } + const char *mode = "custom"; + if (!csv[0]) { + mode = "default"; + } else { + for (int i = 1; i < ANODE_DNS_COUNT - 1; i++) { + if (ANODE_DNS_PRESETS[i].v4_csv[0] && + strstr(csv, ANODE_DNS_PRESETS[i].v4_csv) != NULL) { + mode = ANODE_DNS_PRESETS[i].mode; + break; + } + } + } + printf("mode=%s\nservers=%s\n", mode, csv); + return 0; + } + + char v4[ANODE_DNS_MAX_SERVERS][16]; + char v6[ANODE_DNS_MAX_SERVERS][46]; + int n4 = 0, n6 = 0; + const char *tag = "custom"; + + if (strcmp(argv[1], "preset") == 0 && argc >= 3) { + int idx = anode_dns_mode_index(argv[2]); + if (idx < 0 || idx == ANODE_DNS_CUSTOM) { + fprintf(stderr, "anode-dnsctl: unknown preset '%s'\n", argv[2]); + return 2; + } + tag = ANODE_DNS_PRESETS[idx].mode; + if (ANODE_DNS_PRESETS[idx].v4_csv[0]) { + char combined[256]; + snprintf(combined, sizeof(combined), "%s%s%s", + ANODE_DNS_PRESETS[idx].v4_csv, + ANODE_DNS_PRESETS[idx].v6_csv[0] ? "," : "", + ANODE_DNS_PRESETS[idx].v6_csv); + anode_parse_dns_servers(combined, v4, &n4, ANODE_DNS_MAX_SERVERS, + v6, &n6, ANODE_DNS_MAX_SERVERS, NULL, 0); + } + } else if (strcmp(argv[1], "custom") == 0 && argc >= 3) { + tag = "custom"; + if (anode_parse_dns_servers(argv[2], v4, &n4, ANODE_DNS_MAX_SERVERS, + v6, &n6, ANODE_DNS_MAX_SERVERS, NULL, 0) < 0 || + (n4 + n6) == 0) { + fprintf(stderr, "anode-dnsctl: invalid nameserver list '%s'\n", argv[2]); + return 2; + } + } else { + print_usage(); + return 2; + } + + return write_resolv_conf(v4, n4, v6, n6, tag); +} diff --git a/src/daemons/anode-power-ctl.c b/src/daemons/anode-power-ctl.c new file mode 100644 index 0000000..ae20f1d --- /dev/null +++ b/src/daemons/anode-power-ctl.c @@ -0,0 +1,46 @@ +#define _POSIX_C_SOURCE 200809L +#include "anode_plat.h" + +#include +#include +#include + +static void print_usage(void) { + fprintf(stderr, "Usage: anode-power-ctl |backlight <0-100>>\n"); +} + +int main(int argc, char *argv[]) { + if (argc < 2) { + print_usage(); + return 2; + } + const char *cmd = argv[1]; + if (strcmp(cmd, "suspend") == 0 || strcmp(cmd, "hibernate") == 0 || + strcmp(cmd, "reboot") == 0 || strcmp(cmd, "poweroff") == 0) { + return anode_power_action(cmd) == 0 ? 0 : 1; + } + if (strcmp(cmd, "profile") == 0) { + if (argc < 3) { + char prof[64] = {0}; + if (anode_power_profile_get(prof, sizeof(prof))) { + printf("%s\n", prof); + return 0; + } + return 1; + } + if (strcmp(argv[2], "low-power") != 0 && strcmp(argv[2], "power-saver") != 0 && + strcmp(argv[2], "balanced") != 0 && strcmp(argv[2], "performance") != 0) { + fprintf(stderr, "anode-power-ctl: invalid profile '%s'\n", argv[2]); + return 2; + } + return anode_power_profile_set(argv[2]) ? 0 : 1; + } + if (strcmp(cmd, "backlight") == 0 && argc >= 3) { + double pct = strtod(argv[2], NULL); + if (pct < 1.0) pct = 1.0; + if (pct > 100.0) pct = 100.0; + return anode_backlight_set(pct / 100.0) ? 0 : 1; + } + print_usage(); + return 2; +} diff --git a/src/daemons/anode-powerd.c b/src/daemons/anode-powerd.c new file mode 100644 index 0000000..cdf78b7 --- /dev/null +++ b/src/daemons/anode-powerd.c @@ -0,0 +1,159 @@ +#define _POSIX_C_SOURCE 200809L +#include "anode_plat.h" +#include "anode_power_policy.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_XSCRNSAVER +#include +#endif + +static int g_sig_pipe[2] = {-1, -1}; + +static void sig_handler(int sig) { + int saved = errno; + char c = (sig == SIGUSR1 || sig == SIGHUP) ? 'R' : 'Q'; + if (g_sig_pipe[1] >= 0) { + ssize_t unused = write(g_sig_pipe[1], &c, 1); + (void)unused; + } + errno = saved; +} + +static uint32_t query_idle_ms(Display *dpy) { +#ifdef HAVE_XSCRNSAVER + int ev_base = 0, err_base = 0; + if (dpy && XScreenSaverQueryExtension(dpy, &ev_base, &err_base)) { + XScreenSaverInfo *info = XScreenSaverAllocInfo(); + if (info) { + uint32_t res = 0; + if (XScreenSaverQueryInfo(dpy, DefaultRootWindow(dpy), info)) { + res = (uint32_t)info->idle; + } + XFree(info); + return res; + } + } +#else + (void)dpy; +#endif + return 0; +} + +static bool lock_running(void) { + const char *cmd[] = {"sh", "-c", "(ps -eo comm= 2>/dev/null || ps -ax -o comm= 2>/dev/null) | grep -qx anode-lock", NULL}; + return anode_run_cmd_timeout(cmd, NULL, 0, 1000) == 0; +} + +int main(void) { + if (pipe(g_sig_pipe) != 0) return 1; + for (int i = 0; i < 2; i++) { + fcntl(g_sig_pipe[i], F_SETFL, fcntl(g_sig_pipe[i], F_GETFL, 0) | O_NONBLOCK); + fcntl(g_sig_pipe[i], F_SETFD, fcntl(g_sig_pipe[i], F_GETFD, 0) | FD_CLOEXEC); + } + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = sig_handler; + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + sigaction(SIGUSR1, &sa, NULL); + sigaction(SIGHUP, &sa, NULL); + + Display *dpy = XOpenDisplay(NULL); + anode_power_cfg_t cfg = anode_power_cfg_default(); + anode_pwr_state_t state = ANODE_PWR_ACTIVE; + double saved_bright = 0.7; + + bool running = true; + while (running) { + uint32_t idle_ms = dpy ? query_idle_ms(dpy) : 0; + anode_battery_info_t bat; + anode_read_battery(&bat); + bool locked = lock_running(); + + anode_power_actions_t act; + anode_power_policy_step(&cfg, &state, idle_ms, bat.on_ac, + bat.capacity, bat.present, locked, &act); + + if (act.dim_now) { + int cur = 0, maxv = 0; + if (anode_backlight_get(&cur, &maxv, NULL, 0) && maxv > 0) { + saved_bright = (double)cur / (double)maxv; + } + anode_backlight_set(0.15); + } + if (act.restore_brightness) { + anode_backlight_set(saved_bright >= 0.15 ? saved_bright : 0.7); + } + if (act.warn_low_batt) { + const char *nt[] = { + "notify-send", "-u", "critical", "-h", "string:x-dunst-stack-tag:anode-batt", + "ANODE Power", "Battery critically low", NULL + }; + anode_spawn_detached(nt); + } + if (act.lock_now) { + const char *lk[] = {"anode-lock", NULL}; + anode_spawn_detached(lk); + } + if (act.suspend_now) { + const char *sp[] = {"anode-power-ctl", "suspend", NULL}; + if (anode_run_priv_timeout(sp, NULL, 0, 5000) != 0) { + anode_power_action("suspend"); + } + } + + int timeout_ms = 15000; + if (idle_ms < cfg.dim_ms) { + uint32_t rem = cfg.dim_ms - idle_ms; + if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; + } else if (idle_ms < cfg.lock_ms) { + uint32_t rem = cfg.lock_ms - idle_ms; + if (rem < (uint32_t)timeout_ms) timeout_ms = (int)rem; + } else if (!bat.on_ac && idle_ms < cfg.suspend_ms) { + 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; + + struct pollfd pfds[2]; + nfds_t nfds = 0; + pfds[nfds++] = (struct pollfd){.fd = g_sig_pipe[0], .events = POLLIN}; + if (dpy) { + pfds[nfds++] = (struct pollfd){.fd = ConnectionNumber(dpy), .events = POLLIN}; + } + + int pr = poll(pfds, nfds, timeout_ms); + if (pr < 0 && errno != EINTR) break; + if (pfds[0].revents & POLLIN) { + char buf[32]; + ssize_t n; + while ((n = read(g_sig_pipe[0], buf, sizeof(buf))) > 0) { + for (ssize_t i = 0; i < n; i++) { + if (buf[i] == 'Q') running = false; + } + } + } + if (dpy) { + while (XPending(dpy) > 0) { + XEvent ev; + XNextEvent(dpy, &ev); + } + } + } + + if (dpy) XCloseDisplay(dpy); + close(g_sig_pipe[0]); + close(g_sig_pipe[1]); + return 0; +} diff --git a/src/daemons/anode-statusd.c b/src/daemons/anode-statusd.c new file mode 100644 index 0000000..7e0f772 --- /dev/null +++ b/src/daemons/anode-statusd.c @@ -0,0 +1,192 @@ +#define _POSIX_C_SOURCE 200809L +#include "anode_plat.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __linux__ +#include +#include +#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +#include +#endif + +static int g_sig_pipe[2] = {-1, -1}; + +static void sig_handler(int sig) { + int saved = errno; + char c = (sig == SIGUSR1 || sig == SIGHUP) ? 'R' : 'Q'; + if (g_sig_pipe[1] >= 0) { + ssize_t unused = write(g_sig_pipe[1], &c, 1); + (void)unused; + } + errno = saved; +} + +static int open_net_watch_fd(void) { +#ifdef __linux__ + int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); + if (fd >= 0) { + struct sockaddr_nl sa; + memset(&sa, 0, sizeof(sa)); + sa.nl_family = AF_NETLINK; + sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; + if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) == 0) { + fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); + fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); + return fd; + } + close(fd); + } +#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) + int fd = socket(PF_ROUTE, SOCK_RAW, 0); + if (fd >= 0) { + fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); + fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); + return fd; + } +#endif + return -1; +} + +static void build_status(char *out, size_t sz) { + int vol = 0; + bool muted = false; + char vol_str[32] = ""; + if (anode_audio_get_default(false, &vol, &muted)) { + if (muted) snprintf(vol_str, sizeof(vol_str), "VOL MUTE"); + else snprintf(vol_str, sizeof(vol_str), "VOL %d%%", vol); + } + + anode_net_iface_t ifaces[ANODE_MAX_IFACES]; + int n_if = anode_list_net_ifaces(ifaces, ANODE_MAX_IFACES); + const anode_net_iface_t *best = NULL; + for (int i = 0; i < n_if; i++) { + if (ifaces[i].is_loopback || !ifaces[i].is_up) continue; + if (ifaces[i].ipv4[0]) { + best = &ifaces[i]; + if (ifaces[i].is_wireless) break; + } else if (!best && ifaces[i].ipv6[0]) { + best = &ifaces[i]; + } + } + char net_str[128]; + if (best) { + snprintf(net_str, sizeof(net_str), "%s %s", + best->is_wireless ? "WiFi" : best->name, + best->ipv4[0] ? best->ipv4 : best->ipv6); + } else { + snprintf(net_str, sizeof(net_str), "NET off"); + } + + anode_battery_info_t bat; + anode_read_battery(&bat); + char bat_str[48] = ""; + if (bat.present) { + const char *tag = bat.on_ac ? "+" : "-"; + if (bat.capacity >= 0) snprintf(bat_str, sizeof(bat_str), "BAT %d%%%s", bat.capacity, tag); + else snprintf(bat_str, sizeof(bat_str), "BAT %s", bat.status); + } else { + snprintf(bat_str, sizeof(bat_str), "AC"); + } + + time_t now = time(NULL); + struct tm tmbuf; + localtime_r(&now, &tmbuf); + char time_str[32]; + strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M", &tmbuf); + + if (vol_str[0]) { + snprintf(out, sz, " %s | %s | %s | %s ", vol_str, net_str, bat_str, time_str); + } else { + snprintf(out, sz, " %s | %s | %s ", net_str, bat_str, time_str); + } +} + +int main(void) { + if (pipe(g_sig_pipe) != 0) return 1; + for (int i = 0; i < 2; i++) { + fcntl(g_sig_pipe[i], F_SETFL, fcntl(g_sig_pipe[i], F_GETFL, 0) | O_NONBLOCK); + fcntl(g_sig_pipe[i], F_SETFD, fcntl(g_sig_pipe[i], F_GETFD, 0) | FD_CLOEXEC); + } + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = sig_handler; + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + sigaction(SIGUSR1, &sa, NULL); + sigaction(SIGHUP, &sa, NULL); + + Display *dpy = XOpenDisplay(NULL); + if (!dpy) { + fprintf(stderr, "anode-statusd: cannot open X11 display\n"); + return 1; + } + Window root = DefaultRootWindow(dpy); + int xfd = ConnectionNumber(dpy); + int netfd = open_net_watch_fd(); + + char last_status[512] = {0}; + bool running = true; + + while (running) { + char cur[512]; + build_status(cur, sizeof(cur)); + if (strcmp(cur, last_status) != 0) { + snprintf(last_status, sizeof(last_status), "%s", cur); + XStoreName(dpy, root, cur); + XFlush(dpy); + } + + while (XPending(dpy) > 0) { + XEvent ev; + XNextEvent(dpy, &ev); + } + + time_t now = time(NULL); + struct tm tmbuf; + localtime_r(&now, &tmbuf); + int timeout_ms = (60 - tmbuf.tm_sec) * 1000 + 50; + if (timeout_ms < 1000) timeout_ms = 60000; + + struct pollfd pfds[3]; + nfds_t nfds = 0; + pfds[nfds++] = (struct pollfd){.fd = g_sig_pipe[0], .events = POLLIN}; + pfds[nfds++] = (struct pollfd){.fd = xfd, .events = POLLIN}; + if (netfd >= 0) pfds[nfds++] = (struct pollfd){.fd = netfd, .events = POLLIN}; + + int pr = poll(pfds, nfds, timeout_ms); + if (pr < 0 && errno != EINTR) break; + + if (pfds[0].revents & POLLIN) { + char buf[32]; + ssize_t n; + while ((n = read(g_sig_pipe[0], buf, sizeof(buf))) > 0) { + for (ssize_t i = 0; i < n; i++) { + if (buf[i] == 'Q') running = false; + } + } + } + if (netfd >= 0 && nfds > 2 && (pfds[2].revents & POLLIN)) { + char nbuf[1024]; + while (read(netfd, nbuf, sizeof(nbuf)) > 0) {} + } + } + + if (netfd >= 0) close(netfd); + close(g_sig_pipe[0]); + close(g_sig_pipe[1]); + XCloseDisplay(dpy); + return 0; +} diff --git a/src/daemons/anode-touch-gesture.c b/src/daemons/anode-touch-gesture.c new file mode 100644 index 0000000..b7c7305 --- /dev/null +++ b/src/daemons/anode-touch-gesture.c @@ -0,0 +1,59 @@ +#include "anode-touch-gesture.h" +#include +#include + +void anode_touch_begin(anode_touch_track_t *tr, unsigned int detail, + double x, double y, uint64_t now_ms) { + if (!tr) return; + tr->active = true; + tr->detail = detail; + tr->start_x = tr->last_x = x; + tr->start_y = tr->last_y = y; + tr->start_ms = now_ms; +} + +void anode_touch_update(anode_touch_track_t *tr, double x, double y) { + if (!tr || !tr->active) return; + tr->last_x = x; + tr->last_y = y; +} + +anode_gesture_t anode_touch_finish(anode_touch_track_t *tr, + double x, double y, uint64_t now_ms, + int screen_w, int screen_h, double scale) { + if (!tr || !tr->active) return ANODE_GEST_NONE; + tr->active = false; + + if (scale < 0.5) scale = 0.5; + if (scale > 4.0) scale = 4.0; + uint64_t dur = (now_ms >= tr->start_ms) ? (now_ms - tr->start_ms) : 0; + if (dur > 900) return ANODE_GEST_NONE; + + double dx = x - tr->start_x; + double dy = y - tr->start_y; + double adx = fabs(dx); + double ady = fabs(dy); + + double edge = 36.0 * scale; + double min_dist = 72.0 * scale; + + /* Top edge swipe down -> launcher */ + if (tr->start_y <= edge && dy >= min_dist && ady > adx * 1.4) { + return ANODE_GEST_LAUNCHER; + } + /* Bottom edge swipe up -> toggle virtual keyboard */ + if (screen_h > 0 && tr->start_y >= (double)screen_h - edge && + dy <= -min_dist && ady > adx * 1.4) { + return ANODE_GEST_VKBD_TOGGLE; + } + /* Right edge swipe left -> Control Center / Power */ + if (screen_w > 0 && tr->start_x >= (double)screen_w - edge && + dx <= -min_dist && adx > ady * 1.4) { + return ANODE_GEST_CONTROL; + } + /* Left edge swipe right -> cycle focus/launcher shortcut */ + if (tr->start_x <= edge && dx >= min_dist && adx > ady * 1.4) { + return ANODE_GEST_CYCLE_WIN; + } + return ANODE_GEST_NONE; +} diff --git a/src/daemons/anode-touch-gesture.h b/src/daemons/anode-touch-gesture.h new file mode 100644 index 0000000..616f688 --- /dev/null +++ b/src/daemons/anode-touch-gesture.h @@ -0,0 +1,35 @@ +/* + * ANODE touch gesture classification engine + */ +#ifndef ANODE_TOUCH_GESTURE_H +#define ANODE_TOUCH_GESTURE_H + +#include +#include + +typedef enum { + ANODE_GEST_NONE = 0, + ANODE_GEST_LAUNCHER, + ANODE_GEST_VKBD_TOGGLE, + ANODE_GEST_CONTROL, + ANODE_GEST_CYCLE_WIN +} anode_gesture_t; + +typedef struct { + bool active; + unsigned int detail; + double start_x; + double start_y; + double last_x; + double last_y; + uint64_t start_ms; +} anode_touch_track_t; + +void anode_touch_begin(anode_touch_track_t *tr, unsigned int detail, + double x, double y, uint64_t now_ms); +void anode_touch_update(anode_touch_track_t *tr, double x, double y); +anode_gesture_t anode_touch_finish(anode_touch_track_t *tr, + double x, double y, uint64_t now_ms, + int screen_w, int screen_h, double scale); + +#endif /* ANODE_TOUCH_GESTURE_H */ diff --git a/src/daemons/anode-touchd.c b/src/daemons/anode-touchd.c new file mode 100644 index 0000000..c4bc900 --- /dev/null +++ b/src/daemons/anode-touchd.c @@ -0,0 +1,181 @@ +#define _POSIX_C_SOURCE 200809L +#include "anode-touch-gesture.h" +#include "anode_scale.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int g_sig_pipe[2] = {-1, -1}; + +static void sig_handler(int sig) { + int saved = errno; + char c = (sig == SIGUSR1) ? 'R' : 'Q'; + if (g_sig_pipe[1] >= 0) { + ssize_t unused = write(g_sig_pipe[1], &c, 1); + (void)unused; + } + errno = saved; +} + +static uint64_t now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); +} + +static void spawn_detached(const char *const argv[]) { + pid_t p = fork(); + if (p == 0) { + setsid(); + pid_t p2 = fork(); + if (p2 == 0) { + int fd = open("/dev/null", O_RDWR); + if (fd >= 0) { + dup2(fd, STDIN_FILENO); + dup2(fd, STDOUT_FILENO); + dup2(fd, STDERR_FILENO); + if (fd > 2) close(fd); + } + execvp(argv[0], (char *const *)argv); + _exit(127); + } + _exit(0); + } else if (p > 0) { + waitpid(p, NULL, 0); + } +} + +static void send_mod_key(Display *dpy, KeySym ks) { + KeyCode mod = XKeysymToKeycode(dpy, XK_Super_L); + KeyCode key = XKeysymToKeycode(dpy, ks); + if (!mod || !key) return; + XTestFakeKeyEvent(dpy, mod, True, CurrentTime); + XTestFakeKeyEvent(dpy, key, True, CurrentTime); + XTestFakeKeyEvent(dpy, key, False, CurrentTime); + XTestFakeKeyEvent(dpy, mod, False, CurrentTime); + XFlush(dpy); +} + +int main(void) { + if (pipe(g_sig_pipe) != 0) return 1; + for (int i = 0; i < 2; i++) { + fcntl(g_sig_pipe[i], F_SETFL, fcntl(g_sig_pipe[i], F_GETFL, 0) | O_NONBLOCK); + fcntl(g_sig_pipe[i], F_SETFD, fcntl(g_sig_pipe[i], F_GETFD, 0) | FD_CLOEXEC); + } + + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = sig_handler; + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + sigaction(SIGUSR1, &sa, NULL); + + Display *dpy = XOpenDisplay(NULL); + if (!dpy) { + fprintf(stderr, "anode-touchd: cannot open X11 display\n"); + return 1; + } + + int screen = DefaultScreen(dpy); + Window root = RootWindow(dpy, screen); + double dpi = 96.0, scale = 1.0; + anode_read_xres_scale(dpy, &dpi, &scale, NULL); + + int xi_op = -1, xi_ev = 0, xi_err = 0; + if (XQueryExtension(dpy, "XInputExtension", &xi_op, &xi_ev, &xi_err)) { + int maj = 2, min = 2; + if (XIQueryVersion(dpy, &maj, &min) == Success) { + unsigned char mask[XIMaskLen(XI_LASTEVENT)]; + memset(mask, 0, sizeof(mask)); + XISetMask(mask, XI_TouchBegin); + XISetMask(mask, XI_TouchUpdate); + XISetMask(mask, XI_TouchEnd); + XIEventMask evm; + evm.deviceid = XIAllMasterDevices; + evm.mask_len = sizeof(mask); + evm.mask = mask; + XISelectEvents(dpy, root, &evm, 1); + XFlush(dpy); + } else { + xi_op = -1; + } + } + + anode_touch_track_t track; + memset(&track, 0, sizeof(track)); + + int xfd = ConnectionNumber(dpy); + bool running = true; + while (running) { + while (XPending(dpy) > 0) { + XEvent ev; + XNextEvent(dpy, &ev); + if (ev.type == GenericEvent && xi_op >= 0 && ev.xcookie.extension == xi_op) { + if (XGetEventData(dpy, &ev.xcookie)) { + XIDeviceEvent *dev = (XIDeviceEvent *)ev.xcookie.data; + if (ev.xcookie.evtype == XI_TouchBegin) { + anode_touch_begin(&track, (unsigned int)dev->detail, dev->root_x, dev->root_y, now_ms()); + } else if (ev.xcookie.evtype == XI_TouchUpdate) { + if (track.active && track.detail == (unsigned int)dev->detail) { + anode_touch_update(&track, dev->root_x, dev->root_y); + } + } else if (ev.xcookie.evtype == XI_TouchEnd) { + if (track.active && track.detail == (unsigned int)dev->detail) { + int sw = DisplayWidth(dpy, screen); + int sh = DisplayHeight(dpy, screen); + anode_gesture_t g = anode_touch_finish(&track, dev->root_x, dev->root_y, + now_ms(), sw, sh, scale); + if (g == ANODE_GEST_LAUNCHER) { + const char *av[] = {"anode-launcher", NULL}; + spawn_detached(av); + } else if (g == ANODE_GEST_VKBD_TOGGLE) { + const char *av[] = {"anode-media-key", "vkbd-toggle", NULL}; + spawn_detached(av); + } else if (g == ANODE_GEST_CONTROL) { + const char *av[] = {"anode-power", NULL}; + spawn_detached(av); + } else if (g == ANODE_GEST_CYCLE_WIN) { + send_mod_key(dpy, XK_j); + } + } + } + XFreeEventData(dpy, &ev.xcookie); + } + } + } + + struct pollfd pfds[2] = { + {.fd = xfd, .events = POLLIN}, + {.fd = g_sig_pipe[0], .events = POLLIN} + }; + int pr = poll(pfds, 2, -1); + if (pr < 0 && errno != EINTR) break; + if (pfds[1].revents & POLLIN) { + char buf[32]; + ssize_t n; + while ((n = read(g_sig_pipe[0], buf, sizeof(buf))) > 0) { + for (ssize_t i = 0; i < n; i++) { + if (buf[i] == 'Q') running = false; + else if (buf[i] == 'R') anode_read_xres_scale(dpy, &dpi, &scale, NULL); + } + } + } + } + + XCloseDisplay(dpy); + close(g_sig_pipe[0]); + close(g_sig_pipe[1]); + return 0; +} diff --git a/src/daemons/anode-tzctl.c b/src/daemons/anode-tzctl.c new file mode 100644 index 0000000..6896a2f --- /dev/null +++ b/src/daemons/anode-tzctl.c @@ -0,0 +1,85 @@ +#define _POSIX_C_SOURCE 200809L +#include "anode_tz_valid.h" +#include "anode_plat.h" + +#include +#include +#include +#include +#include + +static const char *find_zoneinfo_root(void) { + static const char *roots[] = {"/usr/share/zoneinfo", "/usr/lib/zoneinfo", NULL}; + for (int i = 0; roots[i]; i++) { + if (access(roots[i], R_OK | X_OK) == 0) return roots[i]; + } + return "/usr/share/zoneinfo"; +} + +int main(int argc, char *argv[]) { + if (argc < 2) { + fprintf(stderr, "Usage: anode-tzctl | set-time >\n"); + return 2; + } + if (strcmp(argv[1], "get") == 0) { + char linkbuf[256] = {0}; + ssize_t n = readlink("/etc/localtime", linkbuf, sizeof(linkbuf) - 1); + if (n > 0) { + linkbuf[n] = '\0'; + const char *zi = strstr(linkbuf, "zoneinfo/"); + printf("%s\n", zi ? (zi + 9) : linkbuf); + return 0; + } + const char *tz = getenv("TZ"); + printf("%s\n", (tz && tz[0]) ? tz : "UTC"); + return 0; + } + + if (strcmp(argv[1], "set") == 0 && argc >= 3) { + const char *tz = argv[2]; + const char *root = find_zoneinfo_root(); + if (!anode_tz_file_valid(root, tz)) { + fprintf(stderr, "anode-tzctl: invalid timezone '%s'\n", tz); + return 2; + } + char target[512]; + snprintf(target, sizeof(target), "%s/%s", root, tz); + const char *tmp = "/etc/localtime.anode.tmp"; + unlink(tmp); + if (symlink(target, tmp) != 0 || rename(tmp, "/etc/localtime") != 0) { + unlink(tmp); + fprintf(stderr, "anode-tzctl: failed to update /etc/localtime: %s\n", strerror(errno)); + return 1; + } + FILE *f = fopen("/etc/timezone", "w"); + if (f) { + fprintf(f, "%s\n", tz); + fclose(f); + } + return 0; + } + + if (strcmp(argv[1], "set-time") == 0 && argc >= 3) { + if (anode_have_cmd("timedatectl")) { + const char *av[] = {"timedatectl", "set-time", argv[2], NULL}; + return anode_run_cmd_timeout(av, NULL, 0, 3000) == 0 ? 0 : 1; + } + /* Strict validation: "YYYY-MM-DD HH:MM:SS" */ + const char *s = argv[2]; + if (strlen(s) != 19 || s[4] != '-' || s[7] != '-' || s[10] != ' ' || + s[13] != ':' || s[16] != ':') { + fprintf(stderr, "anode-tzctl: expected YYYY-MM-DD HH:MM:SS\n"); + return 2; + } + const char *av[] = {"date", "-s", s, NULL}; + int rc = anode_run_cmd_timeout(av, NULL, 0, 2000); + if (rc == 0 && anode_have_cmd("hwclock")) { + const char *hw[] = {"hwclock", "--systohc", NULL}; + anode_run_cmd_timeout(hw, NULL, 0, 2000); + } + return rc == 0 ? 0 : 1; + } + + fprintf(stderr, "anode-tzctl: invalid command\n"); + return 2; +} diff --git a/src/dmenu/arg.h b/src/dmenu/arg.h new file mode 100644 index 0000000..e94e02b --- /dev/null +++ b/src/dmenu/arg.h @@ -0,0 +1,49 @@ +/* + * Copy me if you can. + * by 20h + */ + +#ifndef ARG_H__ +#define ARG_H__ + +extern char *argv0; + +/* use main(int argc, char *argv[]) */ +#define ARGBEGIN for (argv0 = *argv, argv++, argc--;\ + argv[0] && argv[0][0] == '-'\ + && argv[0][1];\ + argc--, argv++) {\ + char argc_;\ + char **argv_;\ + int brk_;\ + if (argv[0][1] == '-' && argv[0][2] == '\0') {\ + argv++;\ + argc--;\ + break;\ + }\ + for (brk_ = 0, argv[0]++, argv_ = argv;\ + argv[0][0] && !brk_;\ + argv[0]++) {\ + if (argv_ != argv)\ + break;\ + argc_ = argv[0][0];\ + switch (argc_) + +#define ARGEND }\ + } + +#define ARGC() argc_ + +#define EARGF(x) ((argv[0][1] == '\0' && argv[1] == NULL)?\ + ((x), abort(), (char *)0) :\ + (brk_ = 1, (argv[0][1] != '\0')?\ + (&argv[0][1]) :\ + (argc--, argv++, argv[0]))) + +#define ARGF() ((argv[0][1] == '\0' && argv[1] == NULL)?\ + (char *)0 :\ + (brk_ = 1, (argv[0][1] != '\0')?\ + (&argv[0][1]) :\ + (argc--, argv++, argv[0]))) + +#endif diff --git a/src/dmenu/config.def.h b/src/dmenu/config.def.h new file mode 100644 index 0000000..9ee7c98 --- /dev/null +++ b/src/dmenu/config.def.h @@ -0,0 +1,19 @@ +/* See LICENSE file for copyright and license details. */ +/* ANODE dmenu configuration (logical 96-DPI base values, scaled dynamically via Xresources / EDID) */ + +static int topbar = 1; +static int fuzzy = 1; +static const char *fonts[] = { + "Fira Code, DejaVuSansM Nerd Font 15px" +}; +static const char *prompt = NULL; +static const char *colors[SchemeLast][2] = { + /* fg bg */ + [SchemeNorm] = { "#e6e1cf", "#0b0e14" }, + [SchemeSel] = { "#ffffff", "#2b5278" }, + [SchemeOut] = { "#ffffff", "#243040" }, +}; +static unsigned int lines = 12; +static unsigned int lineheight = 36; +static unsigned int min_lineheight = 36; +static const char worddelimiters[] = " "; diff --git a/src/dmenu/config.h b/src/dmenu/config.h new file mode 100644 index 0000000..9ee7c98 --- /dev/null +++ b/src/dmenu/config.h @@ -0,0 +1,19 @@ +/* See LICENSE file for copyright and license details. */ +/* ANODE dmenu configuration (logical 96-DPI base values, scaled dynamically via Xresources / EDID) */ + +static int topbar = 1; +static int fuzzy = 1; +static const char *fonts[] = { + "Fira Code, DejaVuSansM Nerd Font 15px" +}; +static const char *prompt = NULL; +static const char *colors[SchemeLast][2] = { + /* fg bg */ + [SchemeNorm] = { "#e6e1cf", "#0b0e14" }, + [SchemeSel] = { "#ffffff", "#2b5278" }, + [SchemeOut] = { "#ffffff", "#243040" }, +}; +static unsigned int lines = 12; +static unsigned int lineheight = 36; +static unsigned int min_lineheight = 36; +static const char worddelimiters[] = " "; diff --git a/src/dmenu/dmenu.1 b/src/dmenu/dmenu.1 new file mode 100644 index 0000000..7467883 --- /dev/null +++ b/src/dmenu/dmenu.1 @@ -0,0 +1,252 @@ +.TH DMENU 1 dmenu\-VERSION +.SH NAME +dmenu \- dynamic menu +.SH SYNOPSIS +.B dmenu +.RB [ \-bfitv ] +.RB [ \-l +.IR lines ] +.RB [ \-m +.IR monitor ] +.RB [ \-p +.IR prompt ] +.RB [ \-fn +.IR font ] +.RB [ \-nb +.IR color ] +.RB [ \-nf +.IR color ] +.RB [ \-sb +.IR color ] +.RB [ \-sf +.IR color ] +.RB [ \-H +.IR height ] +.RB [ \-w +.IR windowid ] +.RB [ \-idx +.IR index ] +.RB [ \-wm ] +.P +.BR dmenu_run " ..." +.SH DESCRIPTION +.B dmenu +is a dynamic menu for X, which reads a list of newline\-separated items from +stdin. When the user selects an item and presses Return, their choice is printed +to stdout and dmenu terminates. Entering text will narrow the items to those +matching the tokens in the input. +.P +.B dmenu_run +is a script used by +.IR dwm (1) +which lists programs in the user's $PATH and runs the result in their $SHELL. +.SH OPTIONS +.TP +.B \-b +dmenu appears at the bottom of the screen. +.TP +.B \-nc +dmenu appears not centered on the screen. +.TP +.B \-f +dmenu grabs the keyboard before reading stdin if not reading from a tty. This +is faster, but will lock up X until stdin reaches end\-of\-file. +.TP +.B \-i +dmenu matches menu items case insensitively. +.TP +.BI \-l " lines" +dmenu lists items vertically, with the given number of lines. +.TP +.BI \-H " height" +dmenu uses a menu line of at least 'height' pixels tall, but no less than 8 +.TP +.BI \-m " monitor" +dmenu is displayed on the monitor number supplied. Monitor numbers are starting +from 0. +.TP +.BI \-p " prompt" +defines the prompt to be displayed to the left of the input field. +.TP +.BI \-fn " font" +defines the font or font set used. +.TP +.BI \-nb " color" +defines the normal background color. +.IR #RGB , +.IR #RRGGBB , +and X color names are supported. +.TP +.BI \-nf " color" +defines the normal foreground color. +.TP +.BI \-sb " color" +defines the selected background color. +.TP +.BI \-sf " color" +defines the selected foreground color. +.TP +.B \-t +Return key prints input text instead of selection. +.TP +.B \-v +prints version information to stdout, then exits. +.TP +.BI \-w " windowid" +embed into windowid. +.TP +.BI \-idx " index" +specify the initial selection index number. +.TP +.BI \-wm +Display as a managed WM window (e.g. don't set overide_redirect flag) +.SH USAGE +dmenu is completely controlled by the keyboard. Items are selected using the +arrow keys, page up, page down, home, and end. +.TP +.B Tab +Copy the selected item to the input field. +.TP +.B Return +Confirm selection. Prints the selected item to stdout and exits, returning +success. If \-t option is given it confirms input instead of selection. +.TP +.B Ctrl-Return +Confirm selection. Prints the selected item to stdout and continues. +.TP +.B Shift\-Return +Confirm input. Prints the input text to stdout and exits, returning success. +If \-t option is given it confirms selection instead of input. +.TP +.B Escape +Exit without selecting an item, returning failure. +.TP +.B Ctrl-Left +Move cursor to the start of the current word +.TP +.B Ctrl-Right +Move cursor to the end of the current word +.TP +.B C\-a +Home +.TP +.B C\-b +Left +.TP +.B C\-nc +Escape +.TP +.B C\-d +Delete +.TP +.B C\-e +End +.TP +.B C\-f +Right +.TP +.B C\-g +Escape +.TP +.B C\-h +Backspace +.TP +.B C\-i +Tab +.TP +.B C\-j +Return +.TP +.B C\-J +Shift-Return +.TP +.B C\-k +Delete line right +.TP +.B C\-m +Return +.TP +.B C\-M +Shift-Return +.TP +.B C\-n +Down +.TP +.B C\-p +Up +.TP +.B C\-u +Delete line left +.TP +.B C\-w +Delete word left +.TP +.B C\-y +Paste from primary X selection +.TP +.B C\-Y +Paste from X clipboard +.TP +.B M\-b +Move cursor to the start of the current word +.TP +.B M\-f +Move cursor to the end of the current word +.TP +.B M\-g +Home +.TP +.B M\-G +End +.TP +.B M\-h +Up +.TP +.B M\-j +Page down +.TP +.B M\-k +Page up +.TP +.B M\-l +Down +.SH X Resources +.TP +.BI dmenu.font +defines the font or font set used. +.TP +.BI dmenu.background +defines the normal background color. +.IR #RGB , +.IR #RRGGBB , +and X color names are supported. +.TP +.BI dmenu.foreground +defines the normal foreground color. +.TP +.BI dmenu.selbackground +defines the selected background color. +.TP +.BI dmenu.selforeground +defines the selected foreground color. +.TP +.BI dmenu.selhighlightbackground +defines the highlighted selected background color. +.TP +.BI dmenu.selhighlightforeground +defines the highlighted selected foreground color. +.TP +.BI dmenu.highlightbackground +defines the highlighted background color. +.TP +.BI dmenu.highlightforeground +defines the highlighted foreground color. +.TP +.BI dmenu.outbackground +defines the out background color. +.TP +.BI dmenu.outforeground +defines the out foreground color. +.SH SEE ALSO +.IR dwm (1), +.IR stest (1) diff --git a/src/dmenu/dmenu.c b/src/dmenu/dmenu.c new file mode 100644 index 0000000..c264fcc --- /dev/null +++ b/src/dmenu/dmenu.c @@ -0,0 +1,1044 @@ +/* See LICENSE file for copyright and license details. */ +/* Geminux dmenu - Pango/HarfBuzz + .Xresources + HiDPI touch & keyboard */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#ifdef XINERAMA +#include +#endif +#include + +#include "drw.h" +#include "util.h" +#include "anode_scale.h" + +#define INTERSECT(x, y, w, h, r) \ + (MAX(0, MIN((x) + (w), (r).x_org + (r).width) - MAX((x), (r).x_org)) * \ + MAX(0, MIN((y) + (h), (r).y_org + (r).height) - MAX((y), (r).y_org))) +#define LENGTH(X) (sizeof(X) / sizeof(X)[0]) +#define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad) + +enum { SchemeNorm, SchemeSel, SchemeOut, SchemeLast }; + +struct item { + char *text; + struct item *left, *right; + int out; + double distance; +}; + +static char text[BUFSIZ] = ""; +static char *embed = NULL; +static int bh, mw, mh; +static int inputw = 0, promptw; +static int lrpad; +static size_t cursor = 0; +static struct item *items = NULL; +static struct item *matches = NULL, *matchend = NULL; +static struct item *prev = NULL, *curr = NULL, *next = NULL, *sel = NULL; +static int mon = -1, screen; +static int explicit_lines = 0; + +static Atom clip, utf8; +static Display *dpy; +static Window root, parentwin, win; +static XIC xic; + +static Drw *drw; +static Clr *scheme[SchemeLast]; +static char xres_font[256] = ""; +static char *dyn_colors[SchemeLast][2] = { {NULL, NULL}, {NULL, NULL}, {NULL, NULL} }; +static Cursor vpointer = None, bpointer = None; +static int pointer_hidden = 0, xi_opcode = -1, xfixes_ok = 0; + +#include "config.h" + +static int (*fstrncmp)(const char *, const char *, size_t) = strncmp; +static char *(*fstrstr)(const char *, const char *) = strstr; + +static int cistrncmp(const char *s1, const char *s2, size_t n) { + for (; n > 0 && *s1 && *s2; s1++, s2++, n--) { + int d = tolower((unsigned char)*s1) - tolower((unsigned char)*s2); + if (d != 0) return d; + } + if (n == 0) return 0; + return tolower((unsigned char)*s1) - tolower((unsigned char)*s2); +} + +static char *cistrstr(const char *s, const char *sub) { + size_t len; + if (!sub[0]) return (char *)s; + for (len = strlen(sub); *s; s++) { + if (!cistrncmp(s, sub, len)) return (char *)s; + } + return NULL; +} + +static const char *xrm_get(XrmDatabase xdb, const char *k1, const char *k2, const char *k3) { + char *type = NULL; + XrmValue xval; + if (k1 && XrmGetResource(xdb, k1, "*", &type, &xval) && xval.addr && xval.addr[0]) + return xval.addr; + if (k2 && XrmGetResource(xdb, k2, "*", &type, &xval) && xval.addr && xval.addr[0]) + return xval.addr; + if (k3 && XrmGetResource(xdb, k3, "*", &type, &xval) && xval.addr && xval.addr[0]) + return xval.addr; + return NULL; +} + +static double ui_scale = 1.0; +static int explicit_lineheight = 0; + +static void load_xresources(void) { + XrmInitialize(); + XrmDatabase xdb = anode_open_xres_db(dpy); + double dpi = 96.0; + anode_read_xres_scale_from_db(xdb, dpy, &dpi, &ui_scale, NULL); + + lineheight = (unsigned int)anode_scale_px(36, ui_scale); + min_lineheight = lineheight; + + const char *dm_lh = xdb ? xrm_get(xdb, "dmenu.lineheight", NULL, NULL) : NULL; + if (dm_lh && atoi(dm_lh) >= 16) { + lineheight = (unsigned int)atoi(dm_lh); + min_lineheight = lineheight; + } + + const char *dm_font = xdb ? xrm_get(xdb, "dmenu.font", NULL, NULL) : NULL; + const char *th_face = xdb ? xrm_get(xdb, "theme.fontFace", NULL, NULL) : NULL; + const char *th_icon = xdb ? xrm_get(xdb, "theme.iconFontFace", NULL, NULL) : NULL; + const char *th_size = xdb ? xrm_get(xdb, "theme.baseFontSize", NULL, NULL) : NULL; + if (dm_font) { + snprintf(xres_font, sizeof(xres_font), "%s", dm_font); + fonts[0] = xres_font; + } else { + int px = th_size ? atoi(th_size) : anode_scale_px(15, ui_scale); + if (px < 8 || px > 96) px = anode_scale_px(15, ui_scale); + snprintf(xres_font, sizeof(xres_font), "%s, %s %dpx", + th_face ? th_face : "Fira Code", + th_icon ? th_icon : "DejaVuSansM Nerd Font", px); + fonts[0] = xres_font; + } + + if (xdb) { + struct { int scm; int col; const char *k1; const char *k2; } map[] = { + { SchemeNorm, ColFg, "dmenu.foreground", "theme.fgBright" }, + { SchemeNorm, ColBg, "dmenu.background", "theme.bgHeader" }, + { SchemeSel, ColFg, "dmenu.selforeground", "theme.selFg" }, + { SchemeSel, ColBg, "dmenu.selbackground", "theme.selBg" }, + { SchemeOut, ColFg, "dmenu.outforeground", "theme.fgMain" }, + { SchemeOut, ColBg, "dmenu.outbackground", "theme.bgSearch" }, + }; + for (size_t i = 0; i < LENGTH(map); i++) { + const char *v = xrm_get(xdb, map[i].k1, map[i].k2, NULL); + if (v) { + free(dyn_colors[map[i].scm][map[i].col]); + dyn_colors[map[i].scm][map[i].col] = strdup(v); + colors[map[i].scm][map[i].col] = dyn_colors[map[i].scm][map[i].col]; + } + } + XrmDestroyDatabase(xdb); + } +} + +static void appenditem(struct item *item, struct item **list, struct item **last) { + if (*last) + (*last)->right = item; + else + *list = item; + item->left = *last; + item->right = NULL; + *last = item; +} + +static void calcoffsets(void) { + int i, n; + if (lines > 0) + n = (int)(lines * bh); + else + n = mw - (promptw + inputw + TEXTW("<") + TEXTW(">")); + for (i = 0, next = curr; next; next = next->right) { + int step = (lines > 0) ? bh : (int)TEXTW(next->text); + if ((i += MIN(step, n)) > n) + break; + } + for (i = 0, prev = curr; prev && prev->left; prev = prev->left) { + int step = (lines > 0) ? bh : (int)TEXTW(prev->left->text); + if ((i += MIN(step, n)) > n) + break; + } +} + +static int max_textw(void) __attribute__((unused)); +static int max_textw(void) { + int len = 0; + for (struct item *item = items; item && item->text; item++) + len = MAX((int)TEXTW(item->text), len); + return len; +} + +static void dmenu_xi_raw_select(int enable) { + unsigned char mask[XIMaskLen(XI_LASTEVENT)]; + XIEventMask evmask; + + if (xi_opcode < 0) return; + memset(mask, 0, sizeof(mask)); + if (enable) { + XISetMask(mask, XI_RawMotion); + XISetMask(mask, XI_RawButtonPress); + XISetMask(mask, XI_RawTouchBegin); + } + evmask.deviceid = XIAllMasterDevices; + evmask.mask_len = (int)sizeof(mask); + evmask.mask = mask; + XISelectEvents(dpy, root, &evmask, 1); +} + +static void hidecursor(void) { + if (pointer_hidden) return; + if (bpointer != None) XDefineCursor(dpy, win, bpointer); + if (xfixes_ok) XFixesHideCursor(dpy, root); + dmenu_xi_raw_select(1); + pointer_hidden = 1; + XFlush(dpy); +} + +static void showcursor(void) { + if (!pointer_hidden) return; + pointer_hidden = 0; + dmenu_xi_raw_select(0); + if (xfixes_ok) XFixesShowCursor(dpy, root); + if (vpointer != None) XDefineCursor(dpy, win, vpointer); + XFlush(dpy); +} + +static void cleanup(void) { + size_t i; + showcursor(); + XUngrabKey(dpy, AnyKey, AnyModifier, root); + if (vpointer != None) { + XFreeCursor(dpy, vpointer); + vpointer = None; + } + if (bpointer != None) { + XFreeCursor(dpy, bpointer); + bpointer = None; + } + for (i = 0; i < SchemeLast; i++) { + free(scheme[i]); + free(dyn_colors[i][0]); + free(dyn_colors[i][1]); + } + for (i = 0; items && items[i].text; i++) + free(items[i].text); + free(items); + drw_free(drw); + XSync(dpy, False); + XCloseDisplay(dpy); +} + +static int drawitem(struct item *item, int x, int y, int w) { + if (item == sel) + drw_setscheme(drw, scheme[SchemeSel]); + else if (item->out) + drw_setscheme(drw, scheme[SchemeOut]); + else + drw_setscheme(drw, scheme[SchemeNorm]); + return drw_text(drw, x, y, (unsigned int)w, (unsigned int)bh, lrpad / 2, item->text, 0); +} + +static void drawmenu(void) { + unsigned int curpos; + struct item *item; + int x = 0, y = 0, w; + + drw_setscheme(drw, scheme[SchemeNorm]); + drw_rect(drw, 0, 0, (unsigned int)mw, (unsigned int)mh, 1, 1); + + if (prompt && *prompt) { + drw_setscheme(drw, scheme[SchemeSel]); + x = drw_text(drw, x, 0, (unsigned int)promptw, (unsigned int)bh, lrpad / 2, prompt, 0); + } + w = (lines > 0 || !matches) ? mw - x : inputw; + drw_setscheme(drw, scheme[SchemeNorm]); + drw_text(drw, x, 0, (unsigned int)w, (unsigned int)bh, lrpad / 2, text, 0); + + curpos = TEXTW(text) - TEXTW(&text[cursor]); + if ((int)(curpos += lrpad / 2 - 1) < w) { + drw_setscheme(drw, scheme[SchemeNorm]); + drw_rect(drw, x + (int)curpos, 4, 2, (unsigned int)bh - 8, 1, 0); + } + + if (lines > 0) { + for (item = curr; item != next; item = item->right) + drawitem(item, x, y += bh, mw - x); + } else if (matches) { + x += inputw; + w = (int)TEXTW("<"); + if (curr->left) { + drw_setscheme(drw, scheme[SchemeNorm]); + drw_text(drw, x, 0, (unsigned int)w, (unsigned int)bh, lrpad / 2, "<", 0); + } + x += w; + for (item = curr; item != next; item = item->right) + x = drawitem(item, x, 0, TEXTW(item->text)); + if (next) { + w = (int)TEXTW(">"); + drw_setscheme(drw, scheme[SchemeNorm]); + drw_text(drw, mw - w, 0, (unsigned int)w, (unsigned int)bh, lrpad / 2, ">", 0); + } + } + drw_map(drw, win, 0, 0, (unsigned int)mw, (unsigned int)mh); +} + +static void grabfocus(void) { + struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 }; + Window focuswin; + int i, revertwin; + for (i = 0; i < 100; ++i) { + XGetInputFocus(dpy, &focuswin, &revertwin); + if (focuswin == win) return; + XSetInputFocus(dpy, win, RevertToParent, CurrentTime); + nanosleep(&ts, NULL); + } +} + +static void grabkeyboard(void) { + struct timespec ts = { .tv_sec = 0, .tv_nsec = 1000000 }; + int i; + if (embed) return; + for (i = 0; i < 1000; i++) { + if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), True, GrabModeAsync, + GrabModeAsync, CurrentTime) == GrabSuccess) + return; + nanosleep(&ts, NULL); + } + die("cannot grab keyboard"); +} + +static int compare_distance(const void *a, const void *b) { + const struct item *da = *(const struct item *const *)a; + const struct item *db = *(const struct item *const *)b; + if (!db) return 1; + if (!da) return -1; + return da->distance == db->distance ? 0 : da->distance < db->distance ? -1 : 1; +} + +static void fuzzymatch(void) { + struct item *it; + struct item **fuzzymatches = NULL; + char c; + int number_of_matches = 0, i, pidx, sidx, eidx; + int text_len = (int)strlen(text), itext_len; + + matches = matchend = NULL; + for (it = items; it && it->text; it++) { + if (text_len) { + itext_len = (int)strlen(it->text); + pidx = 0; + sidx = eidx = -1; + for (i = 0; i < itext_len && (c = it->text[i]); i++) { + if (!fstrncmp(&text[pidx], &c, 1)) { + if (sidx == -1) sidx = i; + pidx++; + if (pidx == text_len) { + eidx = i; + break; + } + } + } + if (eidx != -1) { + it->distance = log(sidx + 2) + (double)(eidx - sidx - text_len); + appenditem(it, &matches, &matchend); + number_of_matches++; + } + } else { + appenditem(it, &matches, &matchend); + } + } + if (number_of_matches) { + fuzzymatches = realloc(fuzzymatches, (size_t)number_of_matches * sizeof(struct item *)); + if (!fuzzymatches) die("cannot realloc:"); + for (i = 0, it = matches; it && i < number_of_matches; i++, it = it->right) + fuzzymatches[i] = it; + qsort(fuzzymatches, (size_t)number_of_matches, sizeof(struct item *), compare_distance); + matches = matchend = NULL; + for (i = 0; i < number_of_matches; i++) + appenditem(fuzzymatches[i], &matches, &matchend); + free(fuzzymatches); + } + curr = sel = matches; + calcoffsets(); +} + +static void match(void) { + if (fuzzy) { + fuzzymatch(); + return; + } + static char **tokv = NULL; + static int tokn = 0; + char buf[sizeof text], *s; + int i, tokc = 0; + size_t len, textsize; + struct item *item, *lprefix, *lsubstr, *prefixend, *substrend; + + strcpy(buf, text); + for (s = strtok(buf, " "); s; tokv[tokc - 1] = s, s = strtok(NULL, " ")) { + if (++tokc > tokn && !(tokv = realloc(tokv, (size_t)(++tokn) * sizeof(*tokv)))) + die("cannot realloc %zu bytes:", tokn * sizeof(*tokv)); + } + len = tokc ? strlen(tokv[0]) : 0; + + matches = lprefix = lsubstr = matchend = prefixend = substrend = NULL; + textsize = strlen(text) + 1; + for (item = items; item && item->text; item++) { + for (i = 0; i < tokc; i++) { + if (!fstrstr(item->text, tokv[i])) + break; + } + if (i != tokc) continue; + if (!tokc || !fstrncmp(text, item->text, textsize)) + appenditem(item, &matches, &matchend); + else if (!fstrncmp(tokv[0], item->text, len)) + appenditem(item, &lprefix, &prefixend); + else + appenditem(item, &lsubstr, &substrend); + } + if (lprefix) { + if (matches) { + matchend->right = lprefix; + lprefix->left = matchend; + } else { + matches = lprefix; + } + matchend = prefixend; + } + if (lsubstr) { + if (matches) { + matchend->right = lsubstr; + lsubstr->left = matchend; + } else { + matches = lsubstr; + } + matchend = substrend; + } + curr = sel = matches; + calcoffsets(); +} + +static void insert(const char *str, ssize_t n) { + if (strlen(text) + (size_t)n > sizeof text - 1) return; + memmove(&text[cursor + (size_t)n], &text[cursor], sizeof text - cursor - (size_t)MAX(n, 0)); + if (n > 0) memcpy(&text[cursor], str, (size_t)n); + cursor += (size_t)n; + match(); +} + +static size_t nextrune(int inc) { + ssize_t n; + for (n = (ssize_t)cursor + inc; n + inc >= 0 && (text[n] & 0xc0) == 0x80; n += inc) + ; + return (size_t)n; +} + +static void movewordedge(int dir) { + if (dir < 0) { + while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)])) + cursor = nextrune(-1); + while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)])) + cursor = nextrune(-1); + } else { + while (text[cursor] && strchr(worddelimiters, text[cursor])) + cursor = nextrune(+1); + while (text[cursor] && !strchr(worddelimiters, text[cursor])) + cursor = nextrune(+1); + } +} + +static void keypress(XKeyEvent *ev) { + char buf[64]; + int len; + KeySym ksym = NoSymbol; + Status status; + + len = Xutf8LookupString(xic, ev, buf, sizeof buf - 1, &ksym, &status); + switch (status) { + default: + return; + case XLookupChars: + hidecursor(); + goto insert_chars; + case XLookupKeySym: + case XLookupBoth: + break; + } + if (!IsModifierKey(ksym)) hidecursor(); + + if (ev->state & ControlMask) { + switch (ksym) { + case XK_a: ksym = XK_Home; break; + case XK_b: ksym = XK_Left; break; + case XK_c: ksym = XK_Escape; break; + case XK_d: ksym = XK_Delete; break; + case XK_e: ksym = XK_End; break; + case XK_f: ksym = XK_Right; break; + case XK_g: ksym = XK_Escape; break; + case XK_h: ksym = XK_BackSpace; break; + case XK_i: ksym = XK_Tab; break; + case XK_j: + case XK_J: + case XK_m: + case XK_M: ksym = XK_Return; ev->state &= ~ControlMask; break; + case XK_n: ksym = XK_Down; break; + case XK_p: ksym = XK_Up; break; + case XK_k: + text[cursor] = '\0'; + match(); + break; + case XK_u: + insert(NULL, -(ssize_t)cursor); + break; + case XK_w: + while (cursor > 0 && strchr(worddelimiters, text[nextrune(-1)])) + insert(NULL, (ssize_t)(nextrune(-1) - cursor)); + while (cursor > 0 && !strchr(worddelimiters, text[nextrune(-1)])) + insert(NULL, (ssize_t)(nextrune(-1) - cursor)); + break; + case XK_v: + case XK_V: + case XK_y: + case XK_Y: + XConvertSelection(dpy, (ev->state & ShiftMask) ? clip : XA_PRIMARY, + utf8, utf8, win, CurrentTime); + return; + case XK_Left: + case XK_KP_Left: + movewordedge(-1); + goto draw; + case XK_Right: + case XK_KP_Right: + movewordedge(+1); + goto draw; + case XK_Return: + case XK_KP_Enter: + break; + default: + return; + } + } else if (ev->state & Mod1Mask) { + switch (ksym) { + case XK_b: movewordedge(-1); goto draw; + case XK_f: movewordedge(+1); goto draw; + case XK_g: ksym = XK_Home; break; + case XK_G: ksym = XK_End; break; + case XK_h: ksym = XK_Up; break; + case XK_j: ksym = XK_Next; break; + case XK_k: ksym = XK_Prior; break; + case XK_l: ksym = XK_Down; break; + default: return; + } + } + + switch (ksym) { + default: + insert_chars: + buf[len] = '\0'; + if (len > 0 && !iscntrl((unsigned char)*buf)) + insert(buf, len); + break; + case XK_Delete: + case XK_KP_Delete: + if (text[cursor] == '\0') return; + cursor = nextrune(+1); + /* fallthrough */ + case XK_BackSpace: + if (cursor == 0) return; + insert(NULL, (ssize_t)(nextrune(-1) - cursor)); + break; + case XK_End: + case XK_KP_End: + if (text[cursor] != '\0') { + cursor = strlen(text); + break; + } + if (next) { + curr = matchend; + calcoffsets(); + curr = prev; + calcoffsets(); + while (next && (curr = curr->right)) + calcoffsets(); + } + sel = matchend; + break; + case XK_Escape: + cleanup(); + exit(1); + case XK_Home: + case XK_KP_Home: + if (sel == matches) { + cursor = 0; + break; + } + sel = curr = matches; + calcoffsets(); + break; + case XK_Left: + case XK_KP_Left: + if (cursor > 0 && (!sel || !sel->left || lines > 0)) { + cursor = nextrune(-1); + break; + } + if (lines > 0) return; + /* fallthrough */ + case XK_Up: + case XK_KP_Up: + if (sel && sel->left && (sel = sel->left)->right == curr) { + curr = prev; + calcoffsets(); + } + break; + case XK_Next: + case XK_KP_Next: + if (!next) return; + sel = curr = next; + calcoffsets(); + break; + case XK_Prior: + case XK_KP_Prior: + if (!prev) return; + sel = curr = prev; + calcoffsets(); + break; + case XK_Return: + case XK_KP_Enter: + puts((sel && !(ev->state & ShiftMask)) ? sel->text : text); + if (!(ev->state & ControlMask)) { + cleanup(); + exit(0); + } + if (sel) sel->out = 1; + break; + case XK_Right: + case XK_KP_Right: + if (text[cursor] != '\0') { + cursor = nextrune(+1); + break; + } + if (lines > 0) return; + /* fallthrough */ + case XK_Down: + case XK_KP_Down: + if (sel && sel->right && (sel = sel->right) == next) { + curr = next; + calcoffsets(); + } + break; + case XK_Tab: + if (!sel) return; + strncpy(text, sel->text, sizeof text - 1); + text[sizeof text - 1] = '\0'; + cursor = strlen(text); + match(); + break; + } + +draw: + drawmenu(); +} + +static void buttonpress(XEvent *e) { + struct item *item; + XButtonPressedEvent *ev = &e->xbutton; + int x = 0, y = 0, w; + + showcursor(); + if (ev->window != win) return; + if (ev->button == Button4) { + if (sel && sel->left) { + sel = sel->left; + if (sel->right == curr) { + curr = prev; + calcoffsets(); + } + drawmenu(); + } + return; + } + if (ev->button == Button5) { + if (sel && sel->right) { + sel = sel->right; + if (sel == next) { + curr = next; + calcoffsets(); + } + drawmenu(); + } + return; + } + if (ev->button != Button1) { + if (ev->button == Button3) { + cleanup(); + exit(1); + } + return; + } + + if (prompt && *prompt) + x += promptw; + + if (lines > 0) { + if (ev->y < bh) { + drawmenu(); + return; + } + w = mw - x; + for (item = curr; item != next; item = item->right) { + y += bh; + if (ev->y >= y && ev->y < y + bh) { + puts(item->text); + cleanup(); + exit(0); + } + } + return; + } + + if (!matches) return; + if (ev->x < x + inputw) return; + w = (int)TEXTW("<"); + if (curr->left && ev->x >= x + inputw && ev->x < x + inputw + w) { + if (prev) { + sel = curr = prev; + calcoffsets(); + drawmenu(); + } + return; + } + x += inputw + w; + for (item = curr; item != next; item = item->right) { + int iw = (int)TEXTW(item->text); + if (ev->x >= x && ev->x < x + iw) { + puts(item->text); + cleanup(); + exit(0); + } + x += iw; + } + if (next && ev->x >= mw - (int)TEXTW(">")) { + sel = curr = next; + calcoffsets(); + drawmenu(); + } +} + +static void pastesel(void) { + char *p, *q; + int di; + unsigned long dl; + Atom da; + if (XGetWindowProperty(dpy, win, utf8, 0, (sizeof text / 4) + 1, False, + utf8, &da, &di, &dl, &dl, (unsigned char **)&p) == Success && p) { + insert(p, (q = strchr(p, '\n')) ? (ssize_t)(q - p) : (ssize_t)strlen(p)); + XFree(p); + } + drawmenu(); +} + +static void readstdin(void) { + char buf[sizeof text], *p; + size_t i, itemsiz = 0; + ssize_t len; + char *line = NULL; + size_t linesiz = 0; + + for (i = 0; (len = getline(&line, &linesiz, stdin)) > 0; i++) { + if (i + 1 >= itemsiz) { + itemsiz += 256; + if (!(items = realloc(items, itemsiz * sizeof(*items)))) + die("cannot realloc %zu bytes:", itemsiz * sizeof(*items)); + } + if (line[len - 1] == '\n') + line[len - 1] = '\0'; + else { + strncpy(buf, line, sizeof buf - 1); + buf[sizeof buf - 1] = '\0'; + p = buf; + line = strdup(p); + } + if (!(items[i].text = strdup(line))) + die("cannot strdup %zu bytes:", strlen(line) + 1); + items[i].out = 0; + } + free(line); + if (items) items[i].text = NULL; +} + +static void run(void) { + XEvent ev; + while (!XNextEvent(dpy, &ev)) { + if (ev.type == GenericEvent) { + if (ev.xcookie.extension == xi_opcode && + XGetEventData(dpy, &ev.xcookie)) { + if (ev.xcookie.evtype == XI_RawMotion || + ev.xcookie.evtype == XI_RawButtonPress || + ev.xcookie.evtype == XI_RawTouchBegin) + showcursor(); + XFreeEventData(dpy, &ev.xcookie); + } + continue; + } + if (XFilterEvent(&ev, win)) continue; + switch (ev.type) { + case DestroyNotify: + if (ev.xdestroywindow.window != win) break; + cleanup(); + exit(1); + case Expose: + if (ev.xexpose.count == 0) + drw_map(drw, win, 0, 0, (unsigned int)mw, (unsigned int)mh); + break; + case FocusIn: + if (ev.xfocus.window != win) grabfocus(); + break; + case KeyPress: + keypress(&ev.xkey); + break; + case ButtonPress: + buttonpress(&ev); + break; + case MotionNotify: + showcursor(); + break; + case SelectionNotify: + if (ev.xselection.property == utf8) pastesel(); + break; + case VisibilityNotify: + if (ev.xvisibility.state != VisibilityUnobscured) + XRaiseWindow(dpy, win); + break; + } + } +} + +static void setup(void) { + int x, y, i, j; + unsigned int du; + XSetWindowAttributes swa; + XIM xim; + Window w, dw, *dws; + XWindowAttributes wa; + XClassHint ch = {"dmenu", "dmenu"}; +#ifdef XINERAMA + XineramaScreenInfo *info; + Window pw; + int a, di, n, area = 0; +#endif + + scheme[SchemeNorm] = drw_scm_create(drw, colors[SchemeNorm], 2); + scheme[SchemeSel] = drw_scm_create(drw, colors[SchemeSel], 2); + scheme[SchemeOut] = drw_scm_create(drw, colors[SchemeOut], 2); + + clip = XInternAtom(dpy, "CLIPBOARD", False); + utf8 = XInternAtom(dpy, "UTF8_STRING", False); + + int sx = 0, sy = 0, sw = 0, sh = 0; + + bh = MAX((int)drw->fonts->h + anode_scale_px(9, ui_scale), (int)lineheight); + if (!explicit_lineheight && bh < (int)min_lineheight) bh = (int)min_lineheight; + promptw = (prompt && *prompt) ? (int)TEXTW(prompt) : 0; + +#ifdef XINERAMA + i = 0; + if (parentwin == root && (info = XineramaQueryScreens(dpy, &n))) { + XGetInputFocus(dpy, &w, &di); + if (mon >= 0 && mon < n) { + i = mon; + } else if (w != root && w != PointerRoot && w != None) { + do { + if (XQueryTree(dpy, w, &dw, &pw, &dws, &du) && dws) XFree(dws); + if (XGetWindowAttributes(dpy, w, &wa)) break; + w = pw; + } while (w != root && pw != None); + if (XGetWindowAttributes(dpy, w, &wa)) { + for (j = 0; j < n; j++) { + if ((a = INTERSECT(wa.x, wa.y, wa.width, wa.height, info[j])) > area) { + area = a; + i = j; + } + } + } + } + sx = info[i].x_org; + sy = info[i].y_org; + sw = info[i].width; + sh = info[i].height; + XFree(info); + } else +#endif + { + if (!XGetWindowAttributes(dpy, parentwin, &wa)) + die("could not get embedding window attributes: 0x%lx", parentwin); + sx = 0; + sy = 0; + sw = wa.width; + sh = wa.height; + } + x = sx; + y = sy; + mw = sw; + mh = sh; + { + int avail_lines = (mh - bh) / bh; + if (avail_lines < 1) avail_lines = 1; + if (!explicit_lines || lines == 0 || (int)lines > avail_lines) + lines = (unsigned int)avail_lines; + } + inputw = mw / 3; + match(); + + swa.override_redirect = True; + swa.background_pixel = scheme[SchemeNorm][ColBg].pixel; + swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | PointerMotionMask | VisibilityChangeMask; + win = XCreateWindow(dpy, parentwin, x, y, (unsigned int)mw, (unsigned int)mh, 0, + CopyFromParent, CopyFromParent, CopyFromParent, + CWOverrideRedirect | CWBackPixel | CWEventMask, &swa); + XSetClassHint(dpy, win, &ch); + + { + int ev_base = 0, err_base = 0; + char blank_bits[1] = {0}; + Pixmap blank = XCreateBitmapFromData(dpy, win, blank_bits, 1, 1); + XColor black; + memset(&black, 0, sizeof(black)); + xfixes_ok = XFixesQueryExtension(dpy, &ev_base, &err_base) ? 1 : 0; + xi_opcode = -1; + if (XQueryExtension(dpy, "XInputExtension", &xi_opcode, &ev_base, &err_base)) { + int maj = 2, min = 2; + if (XIQueryVersion(dpy, &maj, &min) != Success) + xi_opcode = -1; + } else { + xi_opcode = -1; + } + vpointer = XCreateFontCursor(dpy, XC_left_ptr); + bpointer = XCreatePixmapCursor(dpy, blank, blank, &black, &black, 0, 0); + XFreePixmap(dpy, blank); + if (vpointer != None) XDefineCursor(dpy, win, vpointer); + } + + if ((xim = XOpenIM(dpy, NULL, NULL, NULL)) == NULL) + die("XOpenIM failed: could not open input device"); + xic = XCreateIC(xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, + XNClientWindow, win, XNFocusWindow, win, NULL); + + XMapRaised(dpy, win); + if (embed) { + XSelectInput(dpy, parentwin, FocusChangeMask | SubstructureNotifyMask); + if (XQueryTree(dpy, parentwin, &dw, &w, &dws, &du) && dws) { + for (i = 0; (unsigned int)i < du && dws[i] != win; ++i) + XSelectInput(dpy, dws[i], FocusChangeMask); + XFree(dws); + } + grabfocus(); + } + drw_resize(drw, (unsigned int)mw, (unsigned int)mh); + drawmenu(); +} + +static void usage(void) { + die("usage: dmenu [-bfiv] [-l lines] [-p prompt] [-fn font] [-m monitor]\n" + " [-nb color] [-nf color] [-sb color] [-sf color]\n" + " [-h height] [-w windowid]"); +} + +int main(int argc, char *argv[]) { + XWindowAttributes wa; + int i, fast = 0; + + if (!setlocale(LC_CTYPE, "") || !XSupportsLocale()) + fputs("warning: no locale support\n", stderr); + if (!(dpy = XOpenDisplay(NULL))) + die("cannot open display"); + screen = DefaultScreen(dpy); + root = RootWindow(dpy, screen); + + load_xresources(); + + for (i = 1; i < argc; i++) { + if (!strcmp(argv[i], "-v")) { + puts("dmenu-" VERSION); + return 0; + } else if (!strcmp(argv[i], "-b")) { + topbar = 0; + } else if (!strcmp(argv[i], "-f")) { + fast = 1; + } else if (!strcmp(argv[i], "-F")) { + fuzzy = 0; + } else if (!strcmp(argv[i], "-i")) { + fstrncmp = cistrncmp; + fstrstr = cistrstr; + } else if (i + 1 == argc) { + usage(); + } else if (!strcmp(argv[i], "-l")) { + lines = (unsigned int)atoi(argv[++i]); + explicit_lines = 1; + } else if (!strcmp(argv[i], "-m")) { + mon = atoi(argv[++i]); + } else if (!strcmp(argv[i], "-p")) { + prompt = argv[++i]; + } else if (!strcmp(argv[i], "-fn")) { + fonts[0] = argv[++i]; + } else if (!strcmp(argv[i], "-nb")) { + colors[SchemeNorm][ColBg] = argv[++i]; + } else if (!strcmp(argv[i], "-nf")) { + colors[SchemeNorm][ColFg] = argv[++i]; + } else if (!strcmp(argv[i], "-sb")) { + colors[SchemeSel][ColBg] = argv[++i]; + } else if (!strcmp(argv[i], "-sf")) { + colors[SchemeSel][ColFg] = argv[++i]; + } else if (!strcmp(argv[i], "-h")) { + lineheight = (unsigned int)atoi(argv[++i]); + explicit_lineheight = 1; + } else if (!strcmp(argv[i], "-w")) { + embed = argv[++i]; + } else { + usage(); + } + } + + if (!embed || !(parentwin = (Window)strtol(embed, NULL, 0))) + parentwin = root; + if (!XGetWindowAttributes(dpy, parentwin, &wa)) + die("could not get embedding window attributes: 0x%lx", parentwin); + drw = drw_create(dpy, screen, root, (unsigned int)wa.width, (unsigned int)wa.height); + if (!drw_fontset_create(drw, fonts, LENGTH(fonts))) + die("no fonts could be loaded."); + lrpad = (int)drw->fonts->h; + + if (fast && !isatty(0)) { + grabkeyboard(); + readstdin(); + } else { + readstdin(); + grabkeyboard(); + } + setup(); + run(); + return 1; +} diff --git a/src/dmenu/dmenu_path b/src/dmenu/dmenu_path new file mode 100755 index 0000000..3a7cda7 --- /dev/null +++ b/src/dmenu/dmenu_path @@ -0,0 +1,13 @@ +#!/bin/sh + +cachedir="${XDG_CACHE_HOME:-"$HOME/.cache"}" +cache="$cachedir/dmenu_run" + +[ ! -e "$cachedir" ] && mkdir -p "$cachedir" + +IFS=: +if stest -dqr -n "$cache" $PATH; then + stest -flx $PATH | sort -u | tee "$cache" +else + cat "$cache" +fi diff --git a/src/dmenu/dmenu_run b/src/dmenu/dmenu_run new file mode 100755 index 0000000..36d20a1 --- /dev/null +++ b/src/dmenu/dmenu_run @@ -0,0 +1,2 @@ +#!/bin/sh +dmenu_path | dmenu "$@" | ${SHELL:-/bin/sh} & diff --git a/src/dmenu/drw.c b/src/dmenu/drw.c new file mode 100644 index 0000000..0a7a653 --- /dev/null +++ b/src/dmenu/drw.c @@ -0,0 +1,231 @@ +/* See LICENSE file for copyright and license details. */ +/* Pango + HarfBuzz + Xft drawing backend for Geminux dmenu */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "drw.h" +#include "util.h" + +Drw *drw_create(Display *dpy, int screen, Window root, unsigned int w, unsigned int h) { + Drw *drw = ecalloc(1, sizeof(Drw)); + drw->dpy = dpy; + drw->screen = screen; + drw->root = root; + drw->w = w; + drw->h = h; + drw->drawable = XCreatePixmap(dpy, root, w, h, DefaultDepth(dpy, screen)); + drw->gc = XCreateGC(dpy, root, 0, NULL); + XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter); + return drw; +} + +void drw_resize(Drw *drw, unsigned int w, unsigned int h) { + if (!drw) return; + drw->w = w; + drw->h = h; + if (drw->drawable) + XFreePixmap(drw->dpy, drw->drawable); + drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, DefaultDepth(drw->dpy, drw->screen)); +} + +void drw_free(Drw *drw) { + if (!drw) return; + if (drw->drawable) + XFreePixmap(drw->dpy, drw->drawable); + if (drw->gc) + XFreeGC(drw->dpy, drw->gc); + drw_fontset_free(drw->fonts); + free(drw); +} + +Fnt *drw_fontset_create(Drw *drw, const char *fonts[], size_t fontcount) { + Fnt *fnt = ecalloc(1, sizeof(Fnt)); + PangoFontMetrics *metrics; + (void)hb_version_string(); + const char *spec = (fonts && fontcount > 0 && fonts[0] && fonts[0][0]) + ? fonts[0] + : "Fira Code, DejaVuSansM Nerd Font 20px"; + + fnt->dpy = drw->dpy; + fnt->fontmap = pango_xft_get_font_map(drw->dpy, drw->screen); + fnt->context = pango_font_map_create_context(fnt->fontmap); + fnt->desc = pango_font_description_from_string(spec); + pango_context_set_font_description(fnt->context, fnt->desc); + + metrics = pango_context_get_metrics(fnt->context, fnt->desc, pango_language_get_default()); + fnt->h = (unsigned int)((pango_font_metrics_get_ascent(metrics) + + pango_font_metrics_get_descent(metrics)) / PANGO_SCALE); + if (fnt->h < 14) fnt->h = 20; + pango_font_metrics_unref(metrics); + + fnt->layout = pango_layout_new(fnt->context); + pango_layout_set_font_description(fnt->layout, fnt->desc); + drw->fonts = fnt; + return fnt; +} + +void drw_fontset_free(Fnt *set) { + if (!set) return; + if (set->layout) g_object_unref(set->layout); + if (set->context) g_object_unref(set->context); + if (set->desc) pango_font_description_free(set->desc); + free(set); +} + +void drw_clr_create(Drw *drw, Clr *dest, const char *clrname) { + if (!drw || !dest || !clrname) return; + if (!XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen), + DefaultColormap(drw->dpy, drw->screen), clrname, dest)) { + XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen), + DefaultColormap(drw->dpy, drw->screen), "#ffffff", dest); + } +} + +Clr *drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount) { + Clr *ret; + if (!drw || !clrnames || clrcount == 0) return NULL; + ret = ecalloc(clrcount, sizeof(XftColor)); + for (size_t i = 0; i < clrcount; i++) + drw_clr_create(drw, &ret[i], clrnames[i]); + return ret; +} + +void drw_setfontset(Drw *drw, Fnt *set) { + if (drw) drw->fonts = set; +} + +void drw_setscheme(Drw *drw, Clr *scm) { + if (drw) drw->scheme = scm; +} + +void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert) { + if (!drw || !drw->scheme) return; + XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel); + if (filled) + XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h); + else + XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1); +} + +int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, + unsigned int lpad, const char *text, int invert) { + char buf[1024]; + int ty, render = x || y || w || h; + unsigned int ew, eh; + XftDraw *d = NULL; + + if (!drw || (render && !drw->scheme) || !text || !drw->fonts) + return 0; + + if (!render) { + w = ~0; + } else { + XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel); + XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h); + d = XftDrawCreate(drw->dpy, drw->drawable, + DefaultVisual(drw->dpy, drw->screen), + DefaultColormap(drw->dpy, drw->screen)); + x += (int)lpad; + if (w > lpad) w -= lpad; + } + + size_t len = strlen(text); + if (len >= sizeof(buf)) len = sizeof(buf) - 1; + memcpy(buf, text, len); + buf[len] = '\0'; + + if (len > 0 && w > 0) { + drw_font_getexts(drw->fonts, buf, (unsigned int)len, &ew, &eh); + while (len > 3 && ew > w) { + len--; + while (len > 0 && (buf[len] & 0xc0) == 0x80) len--; + if (len >= 3) memcpy(buf + len - 3, "...", 3); + buf[len] = '\0'; + drw_font_getexts(drw->fonts, buf, (unsigned int)len, &ew, &eh); + } + if (render && d) { + pango_layout_set_text(drw->fonts->layout, buf, -1); + ty = y + (int)(h - eh) / 2; + if (ty < y) ty = y; + pango_xft_render_layout(d, &drw->scheme[invert ? ColBg : ColFg], + drw->fonts->layout, x * PANGO_SCALE, ty * PANGO_SCALE); + } + x += (int)ew; + } + + if (d) XftDrawDestroy(d); + return x + (render ? (int)w : 0); +} + +int drw_text_align(Drw *drw, int x, int y, unsigned int w, unsigned int h, + const char *text, int textlen, int align) { + char buf[1024]; + if (!drw || !drw->scheme || !drw->fonts || !text) return x; + int len = textlen < (int)sizeof(buf) - 1 ? textlen : (int)sizeof(buf) - 1; + if (len < 0) len = 0; + memcpy(buf, text, (size_t)len); + buf[len] = '\0'; + + unsigned int ew = 0, eh = 0; + drw_font_getexts(drw->fonts, buf, (unsigned int)len, &ew, &eh); + int dx = (align == AlignR && ew < w) ? x + (int)(w - ew) : x; + int ty = y + (int)(h - eh) / 2; + if (ty < y) ty = y; + + XftDraw *d = XftDrawCreate(drw->dpy, drw->drawable, + DefaultVisual(drw->dpy, drw->screen), + DefaultColormap(drw->dpy, drw->screen)); + pango_layout_set_text(drw->fonts->layout, buf, len); + pango_xft_render_layout(d, &drw->scheme[ColFg], + drw->fonts->layout, dx * PANGO_SCALE, ty * PANGO_SCALE); + XftDrawDestroy(d); + return dx + (int)ew; +} + +void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h) { + if (!drw) return; + XCopyArea(drw->dpy, drw->drawable, win, drw->gc, x, y, w, h, x, y); + XSync(drw->dpy, False); +} + +unsigned int drw_fontset_getwidth(Drw *drw, const char *text) { + unsigned int w = 0, h = 0; + if (!drw || !drw->fonts || !text || !text[0]) return 0; + drw_font_getexts(drw->fonts, text, (unsigned int)strlen(text), &w, &h); + return w; +} + +void drw_font_getexts(Fnt *font, const char *text, unsigned int len, + unsigned int *w, unsigned int *h) { + PangoRectangle r; + if (!font || !text) { + if (w) *w = 0; + if (h) *h = 0; + return; + } + pango_layout_set_text(font->layout, text, (int)len); + pango_layout_get_extents(font->layout, NULL, &r); + if (w) *w = (unsigned int)((r.width + PANGO_SCALE - 1) / PANGO_SCALE); + if (h) *h = (unsigned int)((r.height + PANGO_SCALE - 1) / PANGO_SCALE); + if (h && *h == 0) *h = font->h; +} + +Cur *drw_cur_create(Drw *drw, int shape) { + Cur *cur; + if (!drw) return NULL; + cur = ecalloc(1, sizeof(Cur)); + cur->cursor = XCreateFontCursor(drw->dpy, shape); + return cur; +} + +void drw_cur_free(Drw *drw, Cur *cursor) { + if (!cursor) return; + if (drw) XFreeCursor(drw->dpy, cursor->cursor); + free(cursor); +} diff --git a/src/dmenu/drw.h b/src/dmenu/drw.h new file mode 100644 index 0000000..f3a130c --- /dev/null +++ b/src/dmenu/drw.h @@ -0,0 +1,65 @@ +/* See LICENSE file for copyright and license details. */ +#ifndef DMENU_DRW_H +#define DMENU_DRW_H + +#include +#include +#include +#include + +typedef struct { + Cursor cursor; +} Cur; + +typedef struct Fnt { + Display *dpy; + unsigned int h; + PangoLayout *layout; + PangoFontMap *fontmap; + PangoContext *context; + PangoFontDescription *desc; +} Fnt; + +enum { ColFg, ColBg }; /* Clr scheme index */ +enum { AlignL, AlignR }; +typedef XftColor Clr; + +typedef struct { + unsigned int w, h; + Display *dpy; + int screen; + Window root; + Drawable drawable; + GC gc; + Clr *scheme; + Fnt *fonts; +} Drw; + +Drw *drw_create(Display *dpy, int screen, Window win, unsigned int w, unsigned int h); +void drw_resize(Drw *drw, unsigned int w, unsigned int h); +void drw_free(Drw *drw); + +Fnt *drw_fontset_create(Drw *drw, const char *fonts[], size_t fontcount); +void drw_fontset_free(Fnt *set); +unsigned int drw_fontset_getwidth(Drw *drw, const char *text); +void drw_font_getexts(Fnt *font, const char *text, unsigned int len, + unsigned int *w, unsigned int *h); + +void drw_clr_create(Drw *drw, Clr *dest, const char *clrname); +Clr *drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount); + +Cur *drw_cur_create(Drw *drw, int shape); +void drw_cur_free(Drw *drw, Cur *cursor); + +void drw_setfontset(Drw *drw, Fnt *set); +void drw_setscheme(Drw *drw, Clr *scm); + +void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert); +int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, + unsigned int lpad, const char *text, int invert); +int drw_text_align(Drw *drw, int x, int y, unsigned int w, unsigned int h, + const char *text, int textlen, int align); + +void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h); + +#endif diff --git a/src/dmenu/stest.1 b/src/dmenu/stest.1 new file mode 100644 index 0000000..2667d8a --- /dev/null +++ b/src/dmenu/stest.1 @@ -0,0 +1,90 @@ +.TH STEST 1 dmenu\-VERSION +.SH NAME +stest \- filter a list of files by properties +.SH SYNOPSIS +.B stest +.RB [ -abcdefghlpqrsuwx ] +.RB [ -n +.IR file ] +.RB [ -o +.IR file ] +.RI [ file ...] +.SH DESCRIPTION +.B stest +takes a list of files and filters by the files' properties, analogous to +.IR test (1). +Files which pass all tests are printed to stdout. If no files are given, stest +reads files from stdin. +.SH OPTIONS +.TP +.B \-a +Test hidden files. +.TP +.B \-b +Test that files are block specials. +.TP +.B \-c +Test that files are character specials. +.TP +.B \-d +Test that files are directories. +.TP +.B \-e +Test that files exist. +.TP +.B \-f +Test that files are regular files. +.TP +.B \-g +Test that files have their set-group-ID flag set. +.TP +.B \-h +Test that files are symbolic links. +.TP +.B \-l +Test the contents of a directory given as an argument. +.TP +.BI \-n " file" +Test that files are newer than +.IR file . +.TP +.BI \-o " file" +Test that files are older than +.IR file . +.TP +.B \-p +Test that files are named pipes. +.TP +.B \-q +No files are printed, only the exit status is returned. +.TP +.B \-r +Test that files are readable. +.TP +.B \-s +Test that files are not empty. +.TP +.B \-u +Test that files have their set-user-ID flag set. +.TP +.B \-v +Invert the sense of tests, only failing files pass. +.TP +.B \-w +Test that files are writable. +.TP +.B \-x +Test that files are executable. +.SH EXIT STATUS +.TP +.B 0 +At least one file passed all tests. +.TP +.B 1 +No files passed all tests. +.TP +.B 2 +An error occurred. +.SH SEE ALSO +.IR dmenu (1), +.IR test (1) diff --git a/src/dmenu/stest.c b/src/dmenu/stest.c new file mode 100644 index 0000000..7a7b0bc --- /dev/null +++ b/src/dmenu/stest.c @@ -0,0 +1,109 @@ +/* See LICENSE file for copyright and license details. */ +#include + +#include +#include +#include +#include +#include +#include + +#include "arg.h" +char *argv0; + +#define FLAG(x) (flag[(x)-'a']) + +static void test(const char *, const char *); +static void usage(void); + +static int match = 0; +static int flag[26]; +static struct stat old, new; + +static void +test(const char *path, const char *name) +{ + struct stat st, ln; + + if ((!stat(path, &st) && (FLAG('a') || name[0] != '.') /* hidden files */ + && (!FLAG('b') || S_ISBLK(st.st_mode)) /* block special */ + && (!FLAG('c') || S_ISCHR(st.st_mode)) /* character special */ + && (!FLAG('d') || S_ISDIR(st.st_mode)) /* directory */ + && (!FLAG('e') || access(path, F_OK) == 0) /* exists */ + && (!FLAG('f') || S_ISREG(st.st_mode)) /* regular file */ + && (!FLAG('g') || st.st_mode & S_ISGID) /* set-group-id flag */ + && (!FLAG('h') || (!lstat(path, &ln) && S_ISLNK(ln.st_mode))) /* symbolic link */ + && (!FLAG('n') || st.st_mtime > new.st_mtime) /* newer than file */ + && (!FLAG('o') || st.st_mtime < old.st_mtime) /* older than file */ + && (!FLAG('p') || S_ISFIFO(st.st_mode)) /* named pipe */ + && (!FLAG('r') || access(path, R_OK) == 0) /* readable */ + && (!FLAG('s') || st.st_size > 0) /* not empty */ + && (!FLAG('u') || st.st_mode & S_ISUID) /* set-user-id flag */ + && (!FLAG('w') || access(path, W_OK) == 0) /* writable */ + && (!FLAG('x') || access(path, X_OK) == 0)) != FLAG('v')) { /* executable */ + if (FLAG('q')) + exit(0); + match = 1; + puts(name); + } +} + +static void +usage(void) +{ + fprintf(stderr, "usage: %s [-abcdefghlpqrsuvwx] " + "[-n file] [-o file] [file...]\n", argv0); + exit(2); /* like test(1) return > 1 on error */ +} + +int +main(int argc, char *argv[]) +{ + struct dirent *d; + char path[PATH_MAX], *line = NULL, *file; + size_t linesiz = 0; + ssize_t n; + DIR *dir; + int r; + + ARGBEGIN { + case 'n': /* newer than file */ + case 'o': /* older than file */ + file = EARGF(usage()); + if (!(FLAG(ARGC()) = !stat(file, (ARGC() == 'n' ? &new : &old)))) + perror(file); + break; + default: + /* miscellaneous operators */ + if (strchr("abcdefghlpqrsuvwx", ARGC())) + FLAG(ARGC()) = 1; + else + usage(); /* unknown flag */ + } ARGEND; + + if (!argc) { + /* read list from stdin */ + while ((n = getline(&line, &linesiz, stdin)) > 0) { + if (n && line[n - 1] == '\n') + line[n - 1] = '\0'; + test(line, line); + } + free(line); + } else { + for (; argc; argc--, argv++) { + if (FLAG('l') && (dir = opendir(*argv))) { + /* test directory contents */ + while ((d = readdir(dir))) { + r = snprintf(path, sizeof path, "%s/%s", + *argv, d->d_name); + if (r >= 0 && (size_t)r < sizeof path) + test(path, d->d_name); + } + closedir(dir); + } else { + test(*argv, *argv); + } + } + } + return match ? 0 : 1; +} diff --git a/src/dmenu/util.c b/src/dmenu/util.c new file mode 100644 index 0000000..fe044fc --- /dev/null +++ b/src/dmenu/util.c @@ -0,0 +1,35 @@ +/* See LICENSE file for copyright and license details. */ +#include +#include +#include +#include + +#include "util.h" + +void * +ecalloc(size_t nmemb, size_t size) +{ + void *p; + + if (!(p = calloc(nmemb, size))) + die("calloc:"); + return p; +} + +void +die(const char *fmt, ...) { + va_list ap; + + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + + if (fmt[0] && fmt[strlen(fmt)-1] == ':') { + fputc(' ', stderr); + perror(NULL); + } else { + fputc('\n', stderr); + } + + exit(1); +} diff --git a/src/dmenu/util.h b/src/dmenu/util.h new file mode 100644 index 0000000..531ab25 --- /dev/null +++ b/src/dmenu/util.h @@ -0,0 +1,12 @@ +/* See LICENSE file for copyright and license details. */ + +#ifndef MAX +#define MAX(A, B) ((A) > (B) ? (A) : (B)) +#endif +#ifndef MIN +#define MIN(A, B) ((A) < (B) ? (A) : (B)) +#endif +#define BETWEEN(X, A, B) ((A) <= (X) && (X) <= (B)) + +void die(const char *fmt, ...); +void *ecalloc(size_t nmemb, size_t size); diff --git a/src/dwm/config.def.h b/src/dwm/config.def.h new file mode 100644 index 0000000..a384de1 --- /dev/null +++ b/src/dwm/config.def.h @@ -0,0 +1,196 @@ +/* See LICENSE file for copyright and license details. */ +/* ANODE DWM configuration (cross-Unix, fractional DPI, first-class systray, Fira Code) */ +#include + +/* logical base appearance values at 96 DPI (1.0x), scaled dynamically at runtime */ +static const unsigned int base_borderpx = 2; +static const unsigned int base_snap = 18; +static const unsigned int base_systrayspacing = 4; + +static unsigned int borderpx = 2; +static unsigned int snap = 18; +static const int showbar = 1; +static const int topbar = 1; +static const unsigned int systraypinning = 0; +static const unsigned int systrayonleft = 0; +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 *colors[][3] = { + /* fg bg border */ + [SchemeNorm] = { normfgcolor, normbgcolor, normbordercolor }, + [SchemeSel] = { selfgcolor, selbgcolor, selbordercolor }, +}; + +/* tagging */ +static const char *tags[] = { "1", "2", "3", "4", "5" }; + +static const Rule rules[] = { + /* class instance title tags mask isfloating monitor */ + { "anode-lock", NULL, NULL, ~0U, 1, -1 }, + { "anode-power", NULL, NULL, 0, 1, -1 }, + { "anode-net", NULL, NULL, 0, 1, -1 }, + { "anode-audio", NULL, NULL, 0, 1, -1 }, + { "anode-display", NULL, NULL, 0, 1, -1 }, + { "anode-datetime", NULL, NULL, 0, 1, -1 }, + { "anode-themes", NULL, NULL, 0, 1, -1 }, +}; + +/* layout(s) */ +static const float mfact = 0.55f; +static const int nmaster = 1; +static const int resizehints = 0; +static const int lockfullscreen = 1; + +static const Layout layouts[] = { + /* symbol arrange function */ + { "[]=", tile }, + { "[M]", monocle }, + { "><>", NULL }, + { "###", grid }, +}; + +/* key definitions */ +#define MODKEY Mod4Mask +#define TAGKEYS(KEY,TAG) \ + { MODKEY, KEY, view, {.ui = 1 << TAG} }, \ + { MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \ + { MODKEY|ShiftMask, KEY, tag, {.ui = 1 << TAG} }, \ + { MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} }, + +#define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } } + +/* commands */ +static const char *termcmd[] = { "st", NULL }; +static const char *launchercmd[] = { "anode-launcher", NULL }; +static const char *dmenucmd[] = { "dmenu_run", NULL }; +static const char *powercmd[] = { "anode-power", NULL }; +static const char *netcmd[] = { "anode-net", NULL }; +static const char *audiocmd[] = { "anode-audio", NULL }; +static const char *displaycmd[] = { "anode-display", NULL }; +static const char *datetimecmd[] = { "anode-datetime", NULL }; +static const char *themescmd[] = { "anode-themes", NULL }; +static const char *lockcmd[] = { "anode-lock", NULL }; +static const char *vkbdcmd[] = { "anode-media-key", "vkbd-toggle", NULL }; +static const char *shotcmd[] = { "anode-media-key", "screenshot", NULL }; +static const char *shotwincmd[] = { "anode-media-key", "screenshot-window", NULL }; +static const char *briupcmd[] = { "anode-media-key", "bri-up", NULL }; +static const char *bridowncmd[] = { "anode-media-key", "bri-down", NULL }; +static const char *volupcmd[] = { "anode-media-key", "vol-up", NULL }; +static const char *voldowncmd[] = { "anode-media-key", "vol-down", NULL }; +static const char *volmutecmd[] = { "anode-media-key", "vol-mute", NULL }; +static const char *micmutecmd[] = { "anode-media-key", "mic-mute", NULL }; +static const char *playpausecmd[] = { "anode-media-key", "play-pause", NULL }; +static const char *medprevcmd[] = { "anode-media-key", "prev", NULL }; +static const char *mednextcmd[] = { "anode-media-key", "next", NULL }; +static const char *medstopcmd[] = { "anode-media-key", "stop", NULL }; +static const char *airplanecmd[] = { "anode-media-key", "airplane", NULL }; +static const char *suspendcmd[] = { "anode-media-key", "suspend", NULL }; + +static const Key keys[] = { + /* modifier key function argument */ + { MODKEY, XK_Return, spawn, {.v = termcmd} }, + { MODKEY, XK_p, spawn, {.v = launchercmd} }, + { MODKEY|ShiftMask, XK_p, spawn, {.v = dmenucmd} }, + { 0, XK_Menu, spawn, {.v = launchercmd} }, + { 0, XF86XK_MenuKB, spawn, {.v = launchercmd} }, + { 0, XF86XK_Launch1, spawn, {.v = launchercmd} }, + { MODKEY, XK_c, spawn, {.v = powercmd} }, + { MODKEY, XK_n, spawn, {.v = netcmd} }, + { MODKEY, XK_a, spawn, {.v = audiocmd} }, + { MODKEY, XK_d, spawn, {.v = displaycmd} }, + { MODKEY, XK_w, spawn, {.v = datetimecmd} }, + { MODKEY, XK_t, spawn, {.v = themescmd} }, + { MODKEY, XK_v, spawn, {.v = vkbdcmd} }, +#ifdef XF86XK_Keyboard + { 0, XF86XK_Keyboard, spawn, {.v = vkbdcmd} }, +#endif + { MODKEY|ShiftMask, XK_l, spawn, {.v = lockcmd} }, + { 0, XF86XK_ScreenSaver, spawn, {.v = lockcmd} }, + { 0, XK_Print, spawn, {.v = shotcmd} }, + { ControlMask, XK_Print, spawn, {.v = shotwincmd} }, + { ShiftMask, XK_Print, spawn, {.v = shotwincmd} }, + { 0, XF86XK_MonBrightnessUp, spawn, {.v = briupcmd} }, + { 0, XF86XK_MonBrightnessDown, spawn, {.v = bridowncmd} }, + { 0, XF86XK_AudioRaiseVolume, spawn, {.v = volupcmd} }, + { 0, XF86XK_AudioLowerVolume, spawn, {.v = voldowncmd} }, + { 0, XF86XK_AudioMute, spawn, {.v = volmutecmd} }, + { 0, XF86XK_AudioRecord, spawn, {.v = micmutecmd} }, + { 0, XF86XK_AudioMicMute, spawn, {.v = micmutecmd} }, + { 0, XF86XK_AudioPlay, spawn, {.v = playpausecmd} }, + { 0, XF86XK_AudioPause, spawn, {.v = playpausecmd} }, + { 0, XF86XK_AudioPrev, spawn, {.v = medprevcmd} }, + { 0, XF86XK_AudioNext, spawn, {.v = mednextcmd} }, + { 0, XF86XK_AudioStop, spawn, {.v = medstopcmd} }, + { 0, XF86XK_Tools, spawn, {.v = powercmd} }, + { 0, XF86XK_Option, spawn, {.v = audiocmd} }, + { 0, XF86XK_TaskPane, spawn, {.v = launchercmd} }, + { 0, XF86XK_TopMenu, spawn, {.v = launchercmd} }, + { 0, XF86XK_UWB, spawn, {.v = airplanecmd} }, +#ifdef XF86XK_RFKill + { 0, XF86XK_RFKill, spawn, {.v = airplanecmd} }, +#endif + { 0, XF86XK_WLAN, spawn, {.v = netcmd} }, + { 0, XF86XK_Sleep, spawn, {.v = suspendcmd} }, + { 0, XF86XK_PowerDown, spawn, {.v = powercmd} }, + { MODKEY, XK_b, togglebar, {0} }, + { MODKEY, XK_j, focusstack, {.i = +1} }, + { MODKEY, XK_k, focusstack, {.i = -1} }, + { MODKEY, XK_Down, focusstack, {.i = +1} }, + { MODKEY, XK_Up, focusstack, {.i = -1} }, + { MODKEY, XK_i, incnmaster, {.i = +1} }, + { MODKEY, XK_o, incnmaster, {.i = -1} }, + { MODKEY, XK_h, setmfact, {.f = -0.05f} }, + { MODKEY, XK_l, setmfact, {.f = +0.05f} }, + { MODKEY, XK_space, spawn, {.v = launchercmd} }, + { MODKEY|ShiftMask, XK_Return, zoom, {0} }, + { MODKEY|ShiftMask, XK_space, togglefloating, {0} }, + { MODKEY, XK_Tab, view, {0} }, + { MODKEY|ShiftMask, XK_q, killclient, {0} }, + { MODKEY|ShiftMask, XK_c, killclient, {0} }, + { MODKEY, XK_F1, setlayout, {.v = &layouts[0]} }, + { MODKEY, XK_F2, setlayout, {.v = &layouts[1]} }, + { MODKEY, XK_F3, setlayout, {.v = &layouts[2]} }, + { MODKEY, XK_F4, setlayout, {.v = &layouts[3]} }, + { MODKEY, XK_m, setlayout, {.v = &layouts[1]} }, + { MODKEY, XK_f, setlayout, {.v = &layouts[2]} }, + { MODKEY, XK_g, setlayout, {.v = &layouts[3]} }, + { MODKEY, XK_0, view, {.ui = ~0U} }, + { MODKEY|ShiftMask, XK_0, tag, {.ui = ~0U} }, + { MODKEY, XK_comma, focusmon, {.i = -1} }, + { MODKEY, XK_period, focusmon, {.i = +1} }, + { MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1} }, + { MODKEY|ShiftMask, XK_period, tagmon, {.i = +1} }, + { MODKEY|ShiftMask, XK_r, reloadxres, {0} }, + TAGKEYS( XK_1, 0) + TAGKEYS( XK_2, 1) + TAGKEYS( XK_3, 2) + TAGKEYS( XK_4, 3) + TAGKEYS( XK_5, 4) + { MODKEY|ControlMask|ShiftMask, XK_q, quit, {0} }, +}; + +/* button definitions */ +static const Button buttons[] = { + /* click event mask button function argument */ + { ClkLauncher, 0, Button1, spawn, {.v = launchercmd} }, + { ClkLtSymbol, 0, Button1, setlayout, {0} }, + { ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[1]} }, + { ClkWinTitle, 0, Button2, zoom, {0} }, + { ClkCloseBtn, 0, Button1, killclient, {0} }, + { ClkStatusText, 0, Button1, spawn, {.v = powercmd} }, + { ClkStatusText, 0, Button3, spawn, {.v = audiocmd} }, + { ClkClientWin, MODKEY, Button1, movemouse, {0} }, + { ClkClientWin, MODKEY, Button3, resizemouse, {0} }, + { ClkTagBar, 0, Button1, view, {0} }, + { ClkTagBar, 0, Button3, toggleview, {0} }, + { ClkTagBar, MODKEY, Button1, tag, {0} }, + { ClkTagBar, MODKEY, Button3, toggletag, {0} }, +}; diff --git a/src/dwm/config.h b/src/dwm/config.h new file mode 100644 index 0000000..a384de1 --- /dev/null +++ b/src/dwm/config.h @@ -0,0 +1,196 @@ +/* See LICENSE file for copyright and license details. */ +/* ANODE DWM configuration (cross-Unix, fractional DPI, first-class systray, Fira Code) */ +#include + +/* logical base appearance values at 96 DPI (1.0x), scaled dynamically at runtime */ +static const unsigned int base_borderpx = 2; +static const unsigned int base_snap = 18; +static const unsigned int base_systrayspacing = 4; + +static unsigned int borderpx = 2; +static unsigned int snap = 18; +static const int showbar = 1; +static const int topbar = 1; +static const unsigned int systraypinning = 0; +static const unsigned int systrayonleft = 0; +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 *colors[][3] = { + /* fg bg border */ + [SchemeNorm] = { normfgcolor, normbgcolor, normbordercolor }, + [SchemeSel] = { selfgcolor, selbgcolor, selbordercolor }, +}; + +/* tagging */ +static const char *tags[] = { "1", "2", "3", "4", "5" }; + +static const Rule rules[] = { + /* class instance title tags mask isfloating monitor */ + { "anode-lock", NULL, NULL, ~0U, 1, -1 }, + { "anode-power", NULL, NULL, 0, 1, -1 }, + { "anode-net", NULL, NULL, 0, 1, -1 }, + { "anode-audio", NULL, NULL, 0, 1, -1 }, + { "anode-display", NULL, NULL, 0, 1, -1 }, + { "anode-datetime", NULL, NULL, 0, 1, -1 }, + { "anode-themes", NULL, NULL, 0, 1, -1 }, +}; + +/* layout(s) */ +static const float mfact = 0.55f; +static const int nmaster = 1; +static const int resizehints = 0; +static const int lockfullscreen = 1; + +static const Layout layouts[] = { + /* symbol arrange function */ + { "[]=", tile }, + { "[M]", monocle }, + { "><>", NULL }, + { "###", grid }, +}; + +/* key definitions */ +#define MODKEY Mod4Mask +#define TAGKEYS(KEY,TAG) \ + { MODKEY, KEY, view, {.ui = 1 << TAG} }, \ + { MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \ + { MODKEY|ShiftMask, KEY, tag, {.ui = 1 << TAG} }, \ + { MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} }, + +#define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } } + +/* commands */ +static const char *termcmd[] = { "st", NULL }; +static const char *launchercmd[] = { "anode-launcher", NULL }; +static const char *dmenucmd[] = { "dmenu_run", NULL }; +static const char *powercmd[] = { "anode-power", NULL }; +static const char *netcmd[] = { "anode-net", NULL }; +static const char *audiocmd[] = { "anode-audio", NULL }; +static const char *displaycmd[] = { "anode-display", NULL }; +static const char *datetimecmd[] = { "anode-datetime", NULL }; +static const char *themescmd[] = { "anode-themes", NULL }; +static const char *lockcmd[] = { "anode-lock", NULL }; +static const char *vkbdcmd[] = { "anode-media-key", "vkbd-toggle", NULL }; +static const char *shotcmd[] = { "anode-media-key", "screenshot", NULL }; +static const char *shotwincmd[] = { "anode-media-key", "screenshot-window", NULL }; +static const char *briupcmd[] = { "anode-media-key", "bri-up", NULL }; +static const char *bridowncmd[] = { "anode-media-key", "bri-down", NULL }; +static const char *volupcmd[] = { "anode-media-key", "vol-up", NULL }; +static const char *voldowncmd[] = { "anode-media-key", "vol-down", NULL }; +static const char *volmutecmd[] = { "anode-media-key", "vol-mute", NULL }; +static const char *micmutecmd[] = { "anode-media-key", "mic-mute", NULL }; +static const char *playpausecmd[] = { "anode-media-key", "play-pause", NULL }; +static const char *medprevcmd[] = { "anode-media-key", "prev", NULL }; +static const char *mednextcmd[] = { "anode-media-key", "next", NULL }; +static const char *medstopcmd[] = { "anode-media-key", "stop", NULL }; +static const char *airplanecmd[] = { "anode-media-key", "airplane", NULL }; +static const char *suspendcmd[] = { "anode-media-key", "suspend", NULL }; + +static const Key keys[] = { + /* modifier key function argument */ + { MODKEY, XK_Return, spawn, {.v = termcmd} }, + { MODKEY, XK_p, spawn, {.v = launchercmd} }, + { MODKEY|ShiftMask, XK_p, spawn, {.v = dmenucmd} }, + { 0, XK_Menu, spawn, {.v = launchercmd} }, + { 0, XF86XK_MenuKB, spawn, {.v = launchercmd} }, + { 0, XF86XK_Launch1, spawn, {.v = launchercmd} }, + { MODKEY, XK_c, spawn, {.v = powercmd} }, + { MODKEY, XK_n, spawn, {.v = netcmd} }, + { MODKEY, XK_a, spawn, {.v = audiocmd} }, + { MODKEY, XK_d, spawn, {.v = displaycmd} }, + { MODKEY, XK_w, spawn, {.v = datetimecmd} }, + { MODKEY, XK_t, spawn, {.v = themescmd} }, + { MODKEY, XK_v, spawn, {.v = vkbdcmd} }, +#ifdef XF86XK_Keyboard + { 0, XF86XK_Keyboard, spawn, {.v = vkbdcmd} }, +#endif + { MODKEY|ShiftMask, XK_l, spawn, {.v = lockcmd} }, + { 0, XF86XK_ScreenSaver, spawn, {.v = lockcmd} }, + { 0, XK_Print, spawn, {.v = shotcmd} }, + { ControlMask, XK_Print, spawn, {.v = shotwincmd} }, + { ShiftMask, XK_Print, spawn, {.v = shotwincmd} }, + { 0, XF86XK_MonBrightnessUp, spawn, {.v = briupcmd} }, + { 0, XF86XK_MonBrightnessDown, spawn, {.v = bridowncmd} }, + { 0, XF86XK_AudioRaiseVolume, spawn, {.v = volupcmd} }, + { 0, XF86XK_AudioLowerVolume, spawn, {.v = voldowncmd} }, + { 0, XF86XK_AudioMute, spawn, {.v = volmutecmd} }, + { 0, XF86XK_AudioRecord, spawn, {.v = micmutecmd} }, + { 0, XF86XK_AudioMicMute, spawn, {.v = micmutecmd} }, + { 0, XF86XK_AudioPlay, spawn, {.v = playpausecmd} }, + { 0, XF86XK_AudioPause, spawn, {.v = playpausecmd} }, + { 0, XF86XK_AudioPrev, spawn, {.v = medprevcmd} }, + { 0, XF86XK_AudioNext, spawn, {.v = mednextcmd} }, + { 0, XF86XK_AudioStop, spawn, {.v = medstopcmd} }, + { 0, XF86XK_Tools, spawn, {.v = powercmd} }, + { 0, XF86XK_Option, spawn, {.v = audiocmd} }, + { 0, XF86XK_TaskPane, spawn, {.v = launchercmd} }, + { 0, XF86XK_TopMenu, spawn, {.v = launchercmd} }, + { 0, XF86XK_UWB, spawn, {.v = airplanecmd} }, +#ifdef XF86XK_RFKill + { 0, XF86XK_RFKill, spawn, {.v = airplanecmd} }, +#endif + { 0, XF86XK_WLAN, spawn, {.v = netcmd} }, + { 0, XF86XK_Sleep, spawn, {.v = suspendcmd} }, + { 0, XF86XK_PowerDown, spawn, {.v = powercmd} }, + { MODKEY, XK_b, togglebar, {0} }, + { MODKEY, XK_j, focusstack, {.i = +1} }, + { MODKEY, XK_k, focusstack, {.i = -1} }, + { MODKEY, XK_Down, focusstack, {.i = +1} }, + { MODKEY, XK_Up, focusstack, {.i = -1} }, + { MODKEY, XK_i, incnmaster, {.i = +1} }, + { MODKEY, XK_o, incnmaster, {.i = -1} }, + { MODKEY, XK_h, setmfact, {.f = -0.05f} }, + { MODKEY, XK_l, setmfact, {.f = +0.05f} }, + { MODKEY, XK_space, spawn, {.v = launchercmd} }, + { MODKEY|ShiftMask, XK_Return, zoom, {0} }, + { MODKEY|ShiftMask, XK_space, togglefloating, {0} }, + { MODKEY, XK_Tab, view, {0} }, + { MODKEY|ShiftMask, XK_q, killclient, {0} }, + { MODKEY|ShiftMask, XK_c, killclient, {0} }, + { MODKEY, XK_F1, setlayout, {.v = &layouts[0]} }, + { MODKEY, XK_F2, setlayout, {.v = &layouts[1]} }, + { MODKEY, XK_F3, setlayout, {.v = &layouts[2]} }, + { MODKEY, XK_F4, setlayout, {.v = &layouts[3]} }, + { MODKEY, XK_m, setlayout, {.v = &layouts[1]} }, + { MODKEY, XK_f, setlayout, {.v = &layouts[2]} }, + { MODKEY, XK_g, setlayout, {.v = &layouts[3]} }, + { MODKEY, XK_0, view, {.ui = ~0U} }, + { MODKEY|ShiftMask, XK_0, tag, {.ui = ~0U} }, + { MODKEY, XK_comma, focusmon, {.i = -1} }, + { MODKEY, XK_period, focusmon, {.i = +1} }, + { MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1} }, + { MODKEY|ShiftMask, XK_period, tagmon, {.i = +1} }, + { MODKEY|ShiftMask, XK_r, reloadxres, {0} }, + TAGKEYS( XK_1, 0) + TAGKEYS( XK_2, 1) + TAGKEYS( XK_3, 2) + TAGKEYS( XK_4, 3) + TAGKEYS( XK_5, 4) + { MODKEY|ControlMask|ShiftMask, XK_q, quit, {0} }, +}; + +/* button definitions */ +static const Button buttons[] = { + /* click event mask button function argument */ + { ClkLauncher, 0, Button1, spawn, {.v = launchercmd} }, + { ClkLtSymbol, 0, Button1, setlayout, {0} }, + { ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[1]} }, + { ClkWinTitle, 0, Button2, zoom, {0} }, + { ClkCloseBtn, 0, Button1, killclient, {0} }, + { ClkStatusText, 0, Button1, spawn, {.v = powercmd} }, + { ClkStatusText, 0, Button3, spawn, {.v = audiocmd} }, + { ClkClientWin, MODKEY, Button1, movemouse, {0} }, + { ClkClientWin, MODKEY, Button3, resizemouse, {0} }, + { ClkTagBar, 0, Button1, view, {0} }, + { ClkTagBar, 0, Button3, toggleview, {0} }, + { ClkTagBar, MODKEY, Button1, tag, {0} }, + { ClkTagBar, MODKEY, Button3, toggletag, {0} }, +}; diff --git a/src/dwm/drw.c b/src/dwm/drw.c new file mode 100644 index 0000000..2b3cd21 --- /dev/null +++ b/src/dwm/drw.c @@ -0,0 +1,212 @@ +/* See LICENSE file for copyright and license details. */ +/* Pango + HarfBuzz + Xft drawing backend for Geminux DWM */ +#include +#include +#include +#include +#include +#include +#include + +#include "drw.h" +#include "util.h" + +Drw *drw_create(Display *dpy, int screen, Window root, unsigned int w, unsigned int h) { + Drw *drw = ecalloc(1, sizeof(Drw)); + drw->dpy = dpy; + drw->screen = screen; + drw->root = root; + drw->w = w; + drw->h = h; + drw->drawable = XCreatePixmap(dpy, root, w, h, DefaultDepth(dpy, screen)); + drw->gc = XCreateGC(dpy, root, 0, NULL); + XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter); + return drw; +} + +void drw_resize(Drw *drw, unsigned int w, unsigned int h) { + if (!drw) return; + drw->w = w; + drw->h = h; + if (drw->drawable) + XFreePixmap(drw->dpy, drw->drawable); + drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, DefaultDepth(drw->dpy, drw->screen)); +} + +void drw_free(Drw *drw) { + if (!drw) return; + if (drw->drawable) + XFreePixmap(drw->dpy, drw->drawable); + if (drw->gc) + XFreeGC(drw->dpy, drw->gc); + drw_font_free(drw->font); + free(drw); +} + +Fnt *drw_font_create(Drw *drw, const char font[]) { + Fnt *fnt = ecalloc(1, sizeof(Fnt)); + PangoFontMetrics *metrics; + + fnt->dpy = drw->dpy; + fnt->fontmap = pango_xft_get_font_map(drw->dpy, drw->screen); + fnt->context = pango_font_map_create_context(fnt->fontmap); + fnt->desc = pango_font_description_from_string(font && font[0] ? font : "Fira Code 18px"); + pango_context_set_font_description(fnt->context, fnt->desc); + + metrics = pango_context_get_metrics(fnt->context, fnt->desc, pango_language_get_default()); + fnt->h = (unsigned int)((pango_font_metrics_get_ascent(metrics) + + pango_font_metrics_get_descent(metrics)) / PANGO_SCALE); + if (fnt->h < 12) fnt->h = 18; + pango_font_metrics_unref(metrics); + + fnt->layout = pango_layout_new(fnt->context); + pango_layout_set_font_description(fnt->layout, fnt->desc); + return fnt; +} + +void drw_font_free(Fnt *font) { + if (!font) return; + if (font->layout) g_object_unref(font->layout); + if (font->context) g_object_unref(font->context); + if (font->desc) pango_font_description_free(font->desc); + free(font); +} + +void drw_clr_create(Drw *drw, Clr *dest, const char *clrname) { + if (!drw || !dest || !clrname) return; + if (!XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen), + DefaultColormap(drw->dpy, drw->screen), clrname, dest)) { + fprintf(stderr, "dwm: warning: cannot allocate color '%s', using #ffffff\n", clrname); + XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen), + DefaultColormap(drw->dpy, drw->screen), "#ffffff", dest); + } +} + +Clr *drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount) { + Clr *ret; + if (!drw || !clrnames || clrcount == 0) return NULL; + ret = ecalloc(clrcount, sizeof(XftColor)); + for (size_t i = 0; i < clrcount; i++) + drw_clr_create(drw, &ret[i], clrnames[i]); + return ret; +} + +void drw_setfont(Drw *drw, Fnt *font) { + if (drw) drw->font = font; +} + +void drw_setscheme(Drw *drw, Clr *scm) { + if (drw) drw->scheme = scm; +} + +void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert) { + if (!drw || !drw->scheme) return; + XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel); + if (filled) + XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h); + else + XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1); +} + +int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, + unsigned int lpad, const char *text, int invert, Bool markup) { + char buf[1024]; + int ty, render = x || y || w || h; + unsigned int ew, eh; + XftDraw *d = NULL; + + if (!drw || (render && !drw->scheme) || !text || !drw->font) + return 0; + + if (!render) { + w = ~0; + } else { + XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel); + XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h); + d = XftDrawCreate(drw->dpy, drw->drawable, + DefaultVisual(drw->dpy, drw->screen), + DefaultColormap(drw->dpy, drw->screen)); + x += (int)lpad; + if (w > lpad) w -= lpad; + } + + size_t len = strlen(text); + if (len >= sizeof(buf)) len = sizeof(buf) - 1; + memcpy(buf, text, len); + buf[len] = '\0'; + + if (len > 0 && w > 0) { + drw_font_getexts(drw->font, buf, (unsigned int)len, &ew, &eh, markup); + while (len > 3 && ew > w) { + len--; + while (len > 0 && (buf[len] & 0xc0) == 0x80) len--; + if (len >= 3) memcpy(buf + len - 3, "...", 3); + buf[len] = '\0'; + drw_font_getexts(drw->font, buf, (unsigned int)len, &ew, &eh, markup); + } + + if (render && d) { + if (markup) + pango_layout_set_markup(drw->font->layout, buf, -1); + else + pango_layout_set_text(drw->font->layout, buf, -1); + ty = y + (int)(h - eh) / 2; + if (ty < y) ty = y; + pango_xft_render_layout(d, &drw->scheme[invert ? ColBg : ColFg], + drw->font->layout, x * PANGO_SCALE, ty * PANGO_SCALE); + if (markup) + pango_layout_set_attributes(drw->font->layout, NULL); + } + x += (int)ew; + } + + if (d) XftDrawDestroy(d); + return x + (render ? (int)w : 0); +} + +void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h) { + if (!drw) return; + XCopyArea(drw->dpy, drw->drawable, win, drw->gc, x, y, w, h, x, y); + XSync(drw->dpy, False); +} + +unsigned int drw_font_getwidth(Drw *drw, const char *text, Bool markup) { + unsigned int w = 0, h = 0; + if (!drw || !drw->font || !text || !text[0]) return 0; + drw_font_getexts(drw->font, text, (unsigned int)strlen(text), &w, &h, markup); + return w; +} + +void drw_font_getexts(Fnt *font, const char *text, unsigned int len, + unsigned int *w, unsigned int *h, Bool markup) { + PangoRectangle r; + if (!font || !text) { + if (w) *w = 0; + if (h) *h = 0; + return; + } + if (markup) + pango_layout_set_markup(font->layout, text, (int)len); + else + pango_layout_set_text(font->layout, text, (int)len); + pango_layout_get_extents(font->layout, NULL, &r); + if (markup) + pango_layout_set_attributes(font->layout, NULL); + if (w) *w = (unsigned int)((r.width + PANGO_SCALE - 1) / PANGO_SCALE); + if (h) *h = (unsigned int)((r.height + PANGO_SCALE - 1) / PANGO_SCALE); + if (h && *h == 0) *h = font->h; +} + +Cur *drw_cur_create(Drw *drw, int shape) { + Cur *cur; + if (!drw) return NULL; + cur = ecalloc(1, sizeof(Cur)); + cur->cursor = XCreateFontCursor(drw->dpy, shape); + return cur; +} + +void drw_cur_free(Drw *drw, Cur *cursor) { + if (!cursor) return; + if (drw) XFreeCursor(drw->dpy, cursor->cursor); + free(cursor); +} diff --git a/src/dwm/drw.h b/src/dwm/drw.h new file mode 100644 index 0000000..e534a3d --- /dev/null +++ b/src/dwm/drw.h @@ -0,0 +1,62 @@ +/* See LICENSE file for copyright and license details. */ +#ifndef DWM_DRW_H +#define DWM_DRW_H + +#include +#include +#include +#include + +typedef struct { + Cursor cursor; +} Cur; + +typedef struct Fnt { + Display *dpy; + unsigned int h; + PangoLayout *layout; + PangoFontMap *fontmap; + PangoContext *context; + PangoFontDescription *desc; +} Fnt; + +enum { ColFg, ColBg, ColBorder }; /* Clr scheme index */ +typedef XftColor Clr; + +typedef struct { + unsigned int w, h; + Display *dpy; + int screen; + Window root; + Drawable drawable; + GC gc; + Clr *scheme; + Fnt *font; +} Drw; + +Drw *drw_create(Display *dpy, int screen, Window win, unsigned int w, unsigned int h); +void drw_resize(Drw *drw, unsigned int w, unsigned int h); +void drw_free(Drw *drw); + +Fnt *drw_font_create(Drw *drw, const char font[]); +void drw_font_free(Fnt *font); +unsigned int drw_font_getwidth(Drw *drw, const char *text, Bool markup); +void drw_font_getexts(Fnt *font, const char *text, unsigned int len, + unsigned int *w, unsigned int *h, Bool markup); + +void drw_clr_create(Drw *drw, Clr *dest, const char *clrname); +Clr *drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount); + +Cur *drw_cur_create(Drw *drw, int shape); +void drw_cur_free(Drw *drw, Cur *cursor); + +void drw_setscheme(Drw *drw, Clr *scm); +void drw_setfont(Drw *drw, Fnt *font); + +void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert); +int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, + unsigned int lpad, const char *text, int invert, Bool markup); + +void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h); + +#endif diff --git a/src/dwm/dwm.1 b/src/dwm/dwm.1 new file mode 100644 index 0000000..86f497b --- /dev/null +++ b/src/dwm/dwm.1 @@ -0,0 +1,226 @@ +.TH DWM 1 dwm\-VERSION +.SH NAME +dwm \- dynamic window manager +.SH SYNOPSIS +.B dwm +.RB [ \-v ] +.SH DESCRIPTION +dwm is a dynamic window manager for X. It manages windows in tiled, monocle +and floating layouts. Either layout can be applied dynamically, optimising the +environment for the application in use and the task performed. +.P +In tiled layouts windows are managed in a master and stacking area. The master +area on the left contains one window by default, and the stacking area on the +right contains all other windows. The number of master area windows can be +adjusted from zero to an arbitrary number. In monocle layout all windows are +maximised to the screen size. In floating layout windows can be resized and +moved freely. Dialog windows are always managed floating, regardless of the +layout applied. +.P +Windows are grouped by tags. Each window can be tagged with one or multiple +tags. Selecting certain tags displays all windows with these tags. +.P +Each screen contains a small status bar which displays all available tags, the +layout, the title of the focused window, and the text read from the root window +name property, if the screen is focused. A floating window is indicated with an +empty square and a maximised floating window is indicated with a filled square +before the windows title. The selected tags are indicated with a different +color. The tags of the focused window are indicated with a filled square in the +top left corner. The tags which are applied to one or more windows are +indicated with an empty square in the top left corner. +.P +The attach below patch makes newly spawned windows attach after the currently +selected window +.P +dwm draws a small border around windows to indicate the focus state. +.SH OPTIONS +.TP +.B \-v +prints version information to standard output, then exits. +.SH USAGE +.SS Status bar +.TP +.B X root window name +is read and displayed in the status text area. It can be set with the +.BR xsetroot (1) +command. +.TP +.B Button1 +click on a tag label to display all windows with that tag, click on the layout +label toggles between tiled and floating layout. +.TP +.B Button3 +click on a tag label adds/removes all windows with that tag to/from the view. +.TP +.B Mod4\-Button1 +click on a tag label applies that tag to the focused window. +.TP +.B Mod4\-Button3 +click on a tag label adds/removes that tag to/from the focused window. +.SS Keyboard commands +.TP +.B Mod4\-Shift\-Return +Start +.BR st(1). +.TP +.B Mod4\-p +Spawn +.BR dmenu(1) +for launching other programs. +.TP +.B Mod4\-, +Focus previous screen, if any. +.TP +.B Mod4\-. +Focus next screen, if any. +.TP +.B Mod4\-Shift\-, +Send focused window to previous screen, if any. +.TP +.B Mod4\-Shift\-. +Send focused window to next screen, if any. +.TP +.B Mod4\-b +Toggles bar on and off. +.TP +.B Mod4\-t +Sets tiled layout. +.TP +.B Mod4\-f +Sets floating layout. +.TP +.B Mod4\-m +Sets monocle layout. +.TP +.B Mod4\-space +Toggles between current and previous layout. +.TP +.B Mod4\-Control\-, +Cycles backwards in layout list. +.TP +.B Mod4\-Control\-. +Cycles forwards in layout list. +.TP +.B Mod4\-j +Focus next window. +.TP +.B Mod4\-k +Focus previous window. +.TP +.B Mod4\-i +Increase number of windows in master area. +.TP +.B Mod4\-d +Decrease number of windows in master area. +.TP +.B Mod4\-l +Increase master area size. +.TP +.B Mod4\-h +Decrease master area size. +.TP +.B Mod4\-Return +Zooms/cycles focused window to/from master area (tiled layouts only). +.TP +.B Mod4\-Shift\-c +Close focused window. +.TP +.B Mod4\-Shift\-space +Toggle focused window between tiled and floating state. +.TP +.B Mod4\-Tab +Toggles to the previously selected tags. +.TP +.B Mod4\-Shift\-[1..n] +Apply nth tag to focused window. +.TP +.B Mod4\-Shift\-0 +Apply all tags to focused window. +.TP +.B Mod4\-Control\-Shift\-[1..n] +Add/remove nth tag to/from focused window. +.TP +.B Mod4\-[1..n] +View all windows with nth tag. +.TP +.B Mod4\-0 +View all windows with any tag. +.TP +.B Mod4\-Control\-[1..n] +Add/remove all windows with nth tag to/from the view. +.TP +.B Mod4\-Shift\-q +Quit dwm. +.SS Mouse commands +.TP +.B Mod4\-Button1 +Move focused window while dragging. Tiled windows will be toggled to the floating state. +.TP +.B Mod4\-Button2 +Toggles focused window between floating and tiled state. +.TP +.B Mod4\-Button3 +Resize focused window while dragging. Tiled windows will be toggled to the floating state. +.SH CUSTOMIZATION +dwm is customized by creating a custom config.h and (re)compiling the source +code, or by setting X resources. +.P +The following X resource settings can be set: +.TP +.BI dwm.font +defines the font or font set used. +.TP +.BI dwm.background +defines the normal background color. +.IR #RGB , +.IR #RRGGBB , +and X color names are supported. +.TP +.BI dwm.border +defines the normal border color +.TP +.BI dwm.selbackground +defines the selected background color +.TP +.BI dwm.selforeground +defines the selected foreground color +.TP +.BI dwm.selborder +defines the selected border color +.TP +.BI dwm.tabactivebackground +defines the background color for active tabs +.TP +.BI dwm.tabactiveforeground +defines the foreground color for active tabs +.TP +.BI dwm.tabactiveborder +defines the border color for active tabs +.TP +.BI dwm.tabinactivebackground +defines the background color for inactive tabs +.TP +.BI dwm.tabinactiveforeground +defines the foreground color for inactive tabs +.TP +.BI dwm.tabinactiveborder +defines the border color for inactive tabs +.SH SEE ALSO +.BR dmenu (1), +.BR st (1) +.SH ISSUES +Java applications which use the XToolkit/XAWT backend may draw grey windows +only. The XToolkit/XAWT backend breaks ICCCM-compliance in recent JDK 1.5 and early +JDK 1.6 versions, because it assumes a reparenting window manager. Possible workarounds +are using JDK 1.4 (which doesn't contain the XToolkit/XAWT backend) or setting the +environment variable +.BR AWT_TOOLKIT=MToolkit +(to use the older Motif backend instead) or running +.B xprop -root -f _NET_WM_NAME 32a -set _NET_WM_NAME LG3D +or +.B wmname LG3D +(to pretend that a non-reparenting window manager is running that the +XToolkit/XAWT backend can recognize) or when using OpenJDK setting the environment variable +.BR _JAVA_AWT_WM_NONREPARENTING=1 . +.SH BUGS +Send all bug reports with a patch to hackers@suckless.org. diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c new file mode 100644 index 0000000..9cb1fe7 --- /dev/null +++ b/src/dwm/dwm.c @@ -0,0 +1,2760 @@ +/* See LICENSE file for copyright and license details. */ +/* ANODE DWM - Pango/HarfBuzz + First-class Systray + EWMH Struts + Fractional DPI */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef XINERAMA +#include +#endif +#include + +#include "drw.h" +#include "util.h" +#include "anode_scale.h" + +/* macros */ +#define BUTTONMASK (ButtonPressMask|ButtonReleaseMask) +#define CLEANMASK(mask) (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask)) +#define INTERSECT(x,y,w,h,m) (MAX(0, MIN((x)+(w),(m)->wx+(m)->ww) - MAX((x),(m)->wx)) \ + * MAX(0, MIN((y)+(h),(m)->wy+(m)->wh) - MAX((y),(m)->wy))) +#define ISVISIBLE(C) ((C->tags & C->mon->tagset[C->mon->seltags])) +#define LENGTH(X) (sizeof X / sizeof X[0]) +#define MOUSEMASK (BUTTONMASK|PointerMotionMask) +#define WIDTH(X) ((X)->w + 2 * (X)->bw) +#define HEIGHT(X) ((X)->h + 2 * (X)->bw) +#define TAGMASK ((1 << LENGTH(tags)) - 1) +#define TEXTW(X) (drw_font_getwidth(drw, (X), False) + lrpad) + +#define SYSTEM_TRAY_REQUEST_DOCK 0 +#define XEMBED_EMBEDDED_NOTIFY 0 +#define XEMBED_WINDOW_ACTIVATE 1 +#define XEMBED_WINDOW_DEACTIVATE 2 +#define XEMBED_FOCUS_IN 4 +#define XEMBED_MODALITY_ON 10 +#define XEMBED_MAPPED (1 << 0) +#define XEMBED_EMBEDDED_VERSION 0 +#define VERSION_MAJOR 0 +#define VERSION_MINOR 0 +#define XEMBED_EMBEDDED_VERSION_VAL ((VERSION_MAJOR << 16) | VERSION_MINOR) + +enum { CurNormal, CurResize, CurMove, CurLast }; +enum { SchemeNorm, SchemeSel }; +enum { NetSupported, NetWMName, NetWMState, NetWMCheck, + NetSystemTray, NetSystemTrayOP, NetSystemTrayOrientation, + NetSystemTrayOrientationHorz, NetSystemTrayVisual, + NetWMFullscreen, NetActiveWindow, NetWorkarea, + NetWMWindowType, NetWMWindowTypeDialog, NetWMWindowTypeDock, + NetWMStrutPartial, NetWMStrut, NetClientList, NetLast }; +enum { Manager, Xembed, XembedInfo, XLast }; +enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; +enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkLauncher, + ClkCloseBtn, ClkClientWin, ClkRootWin, ClkLast }; + +typedef union { + int i; + unsigned int ui; + float f; + const void *v; +} Arg; + +typedef struct { + unsigned int click; + unsigned int mask; + unsigned int button; + void (*func)(const Arg *arg); + const Arg arg; +} Button; + +typedef struct Monitor Monitor; +typedef struct Client Client; +struct Client { + char name[256]; + float mina, maxa; + int x, y, w, h; + int oldx, oldy, oldw, oldh; + int basew, baseh, incw, inch, maxw, maxh, minw, minh, hintsvalid; + int bw, oldbw; + unsigned int tags; + int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen; + Client *next; + Client *snext; + Monitor *mon; + Window win; +}; + +typedef struct { + unsigned int mod; + KeySym keysym; + void (*func)(const Arg *); + const Arg arg; +} Key; + +typedef struct { + const char *symbol; + void (*arrange)(Monitor *); +} Layout; + +struct Monitor { + char ltsymbol[16]; + float mfact; + int nmaster; + int num; + int by; + int mx, my, mw, mh; + int wx, wy, ww, wh; + unsigned int seltags; + unsigned int sellt; + unsigned int tagset[2]; + int showbar; + int topbar; + Client *clients; + Client *sel; + Client *stack; + Monitor *next; + Window barwin; + const Layout *lt[2]; +}; + +typedef struct { + const char *class; + const char *instance; + const char *title; + unsigned int tags; + int isfloating; + int monitor; +} Rule; + +typedef struct Systray Systray; +struct Systray { + Window win; + Client *icons; + Visual *visual; + int depth; + Colormap colormap; + int use_argb; +}; + +typedef struct DockWin DockWin; +struct DockWin { + Window win; + unsigned long strut[12]; + DockWin *next; +}; + +/* function declarations */ +static void applyrules(Client *c); +static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact); +static void arrange(Monitor *m); +static void arrangemon(Monitor *m); +static void attach(Client *c); +static void attachstack(Client *c); +static void buttonpress(XEvent *e); +static void checkotherwm(void); +static void cleanup(void); +static void cleanupmon(Monitor *mon); +static void clientmessage(XEvent *e); +static void configure(Client *c); +static void configurenotify(XEvent *e); +static void configurerequest(XEvent *e); +static Monitor *createmon(void); +static void destroynotify(XEvent *e); +static void detach(Client *c); +static void detachstack(Client *c); +static Monitor *dirtomon(int dir); +static void drawbar(Monitor *m); +static void drawbars(void); +static void enternotify(XEvent *e); +static void expose(XEvent *e); +static void focus(Client *c); +static void focusin(XEvent *e); +static void focusmon(const Arg *arg); +static void focusstack(const Arg *arg); +static Atom getatomprop(Client *c, Atom prop); +static int getrootptr(int *x, int *y); +static long getstate(Window w); +static unsigned int getsystraywidth(void); +static int gettextprop(Window w, Atom atom, char *text, unsigned int size); +static void grabbuttons(Client *c, int focused); +static void grabkeys(void); +static void grid(Monitor *m); +static void incnmaster(const Arg *arg); +static void keypress(XEvent *e); +static void keyrelease(XEvent *e); +static void killclient(const Arg *arg); +static void loadxres(void); +static void manage(Window w, XWindowAttributes *wa); +static void mappingnotify(XEvent *e); +static void maprequest(XEvent *e); +static void monocle(Monitor *m); +static void motionnotify(XEvent *e); +static void movemouse(const Arg *arg); +static Client *nexttiled(Client *c); +static unsigned long long now_ms(void); +static void pop(Client *c); +static void propertynotify(XEvent *e); +static void quit(const Arg *arg); +static Monitor *recttomon(int x, int y, int w, int h); +static void reloadxres(const Arg *arg); +static void removesystrayicon(Client *i); +static void resize(Client *c, int x, int y, int w, int h, int interact); +static void resizebarwin(Monitor *m); +static void resizeclient(Client *c, int x, int y, int w, int h); +static void resizemouse(const Arg *arg); +static void resizerequest(XEvent *e); +static void restack(Monitor *m); +static void run(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); +static void setclientstate(Client *c, long state); +static void setfocus(Client *c); +static void setfullscreen(Client *c, int fullscreen); +static void setlayout(const Arg *arg); +static void setmfact(const Arg *arg); +static void setup(void); +static void seturgent(Client *c, int urg); +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 spawn(const Arg *arg); +static Monitor *systraytomon(Monitor *m); +static void tag(const Arg *arg); +static void tagmon(const Arg *arg); +static void tile(Monitor *m); +static void togglebar(const Arg *arg); +static void togglefloating(const Arg *arg); +static void toggletag(const Arg *arg); +static void toggleview(const Arg *arg); +static void unfocus(Client *c, int setfocus); +static void unmanage(Client *c, int destroyed); +static void unmapnotify(XEvent *e); +static void mapnotify(XEvent *e); +static void reparentnotify(XEvent *e); +static void updatebarpos(Monitor *m); +static void updatebars(void); +static void updateclientlist(void); +static int updategeom(void); +static void updatenumlockmask(void); +static void updatesizehints(Client *c); +static void updatestatus(void); +static void updatesystray(int updatebar); +static void updatesystrayicongeom(Client *i, int w, int h); +static void updatesystrayiconstate(Client *i, XPropertyEvent *ev); +static unsigned long systray_bg_pixel(void); +static int getxembedflags(Window w, long *flags_out); +static int isdockwin(Window w); +static void dockadd(Window w); +static int dockremove(Window w); +static void dockupdate(Window w); +static void recalcworkareas(void); +static void updateworkarea(void); +static void updatetitle(Client *c); +static void updatewindowtype(Client *c); +static void updatewmhints(Client *c); +static void view(const Arg *arg); +static Client *wintoclient(Window w); +static Monitor *wintomon(Window w); +static Client *wintosystrayicon(Window w); +static int xerror(Display *dpy, XErrorEvent *ee); +static int xerrordummy(Display *dpy, XErrorEvent *ee); +static int xerrorstart(Display *dpy, XErrorEvent *ee); +static void zoom(const Arg *arg); + +/* variables */ +static Systray *systray = NULL; +static DockWin *docks = NULL; +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 screen; +static int sw, sh; +static int bh; +static int lrpad; +static int (*xerrorxlib)(Display *, XErrorEvent *); +static unsigned int numlockmask = 0; +static volatile sig_atomic_t reload_pending = 0; +static volatile sig_atomic_t restart_dwm = 0; +static int super_down = 0; +static int super_dirty = 0; +static unsigned long long super_down_ms = 0; +static int super_latched = 0; +static unsigned long long super_latch_until = 0; + +static void (*handler[LASTEvent])(XEvent *) = { + [ButtonPress] = buttonpress, + [ClientMessage] = clientmessage, + [ConfigureRequest] = configurerequest, + [ConfigureNotify] = configurenotify, + [DestroyNotify] = destroynotify, + [EnterNotify] = enternotify, + [Expose] = expose, + [FocusIn] = focusin, + [KeyPress] = keypress, + [KeyRelease] = keyrelease, + [MapNotify] = mapnotify, + [MappingNotify] = mappingnotify, + [MapRequest] = maprequest, + [MotionNotify] = motionnotify, + [PropertyNotify] = propertynotify, + [ReparentNotify] = reparentnotify, + [ResizeRequest] = resizerequest, + [UnmapNotify] = unmapnotify +}; +static Atom wmatom[WMLast], netatom[NetLast], xatom[XLast]; +static int running = 1; +static Cur *cursor[CurLast]; +static Clr **scheme; +static Display *dpy; +static Drw *drw; +static Fnt *dwmfont = NULL; +static Monitor *mons, *selmon; +static Window root, wmcheckwin; + +#include "config.h" + +struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; }; + +static unsigned long long now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (unsigned long long)ts.tv_sec * 1000ULL + (unsigned long long)ts.tv_nsec / 1000000ULL; +} + +static void applyrules(Client *c) { + const char *class, *instance; + unsigned int i; + const Rule *r; + Monitor *m; + XClassHint ch = { NULL, NULL }; + + c->isfloating = 0; + c->tags = 0; + XGetClassHint(dpy, c->win, &ch); + class = ch.res_class ? ch.res_class : broken; + instance = ch.res_name ? ch.res_name : broken; + + for (i = 0; i < LENGTH(rules); i++) { + r = &rules[i]; + if ((!r->title || strstr(c->name, r->title)) && + (!r->class || strstr(class, r->class)) && + (!r->instance || strstr(instance, r->instance))) { + c->isfloating = r->isfloating; + c->tags |= r->tags; + for (m = mons; m && m->num != r->monitor; m = m->next) ; + if (m) c->mon = m; + } + } + if (ch.res_class) XFree(ch.res_class); + if (ch.res_name) XFree(ch.res_name); + c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags]; +} + +static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact) { + int baseismin; + Monitor *m = c->mon; + + *w = MAX(1, *w); + *h = MAX(1, *h); + if (interact) { + if (*x > sw) *x = sw - WIDTH(c); + if (*y > sh) *y = sh - HEIGHT(c); + if (*x + *w + 2 * c->bw < 0) *x = 0; + if (*y + *h + 2 * c->bw < 0) *y = 0; + } else { + if (*x >= m->wx + m->ww) *x = m->wx + m->ww - WIDTH(c); + if (*y >= m->wy + m->wh) *y = m->wy + m->wh - HEIGHT(c); + if (*x + *w + 2 * c->bw <= m->wx) *x = m->wx; + if (*y + *h + 2 * c->bw <= m->wy) *y = m->wy; + } + if (*h < bh) *h = bh; + if (*w < bh) *w = bh; + if (resizehints || c->isfloating || !c->mon->lt[c->mon->sellt]->arrange) { + if (!c->hintsvalid) updatesizehints(c); + baseismin = c->basew == c->minw && c->baseh == c->minh; + if (!baseismin) { + *w -= c->basew; + *h -= c->baseh; + } + if (c->mina > 0 && c->maxa > 0) { + if (c->maxa < (float)*w / *h) *w = (int)(*h * c->maxa + 0.5); + else if (c->mina < (float)*h / *w) *h = (int)(*w * c->mina + 0.5); + } + if (baseismin) { + *w -= c->basew; + *h -= c->baseh; + } + if (c->incw) *w -= *w % c->incw; + if (c->inch) *h -= *h % c->inch; + *w = MAX(*w + c->basew, c->minw); + *h = MAX(*h + c->baseh, c->minh); + if (c->maxw) *w = MIN(*w, c->maxw); + if (c->maxh) *h = MIN(*h, c->maxh); + } + return *x != c->x || *y != c->y || *w != c->w || *h != c->h; +} + +static void arrange(Monitor *m) { + if (m) showhide(m->stack); + else for (m = mons; m; m = m->next) showhide(m->stack); + if (m) { + arrangemon(m); + restack(m); + } else { + for (m = mons; m; m = m->next) arrangemon(m); + } +} + +static void arrangemon(Monitor *m) { + snprintf(m->ltsymbol, sizeof m->ltsymbol, "%s", m->lt[m->sellt]->symbol); + if (m->lt[m->sellt]->arrange) + m->lt[m->sellt]->arrange(m); +} + +static void attach(Client *c) { + c->next = c->mon->clients; + c->mon->clients = c; +} + +static void attachstack(Client *c) { + c->snext = c->mon->stack; + c->mon->stack = c; +} + +static void buttonpress(XEvent *e) { + unsigned int i, x, click; + Arg arg = {0}; + Client *c; + Monitor *m; + XButtonPressedEvent *ev = &e->xbutton; + + click = ClkRootWin; + if ((m = wintomon(ev->window)) && m != selmon) { + unfocus(selmon->sel, 1); + selmon = m; + focus(NULL); + } + if (ev->window == selmon->barwin) { + int stw = (showsystray && selmon == systraytomon(selmon) && !systrayonleft) + ? (int)getsystraywidth() : 0; + int tw = (int)TEXTW(stext) - lrpad + 4; + if (ev->x < launcher_w) { + click = ClkLauncher; + } else { + i = 0; + x = (unsigned int)launcher_w; + do { + x += (int)TEXTW(tags[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)) { + click = ClkLtSymbol; + } else if (ev->x > selmon->ww - tw - stw) { + click = ClkStatusText; + } else if (selmon->sel && ev->x > selmon->ww - tw - stw - closebtn_w) { + click = ClkCloseBtn; + } else { + click = ClkWinTitle; + } + } + } else if ((c = wintoclient(ev->window))) { + focus(c); + restack(selmon); + XAllowEvents(dpy, ReplayPointer, CurrentTime); + click = ClkClientWin; + } + for (i = 0; i < LENGTH(buttons); i++) { + if (click == buttons[i].click && buttons[i].func && + buttons[i].button == ev->button && + CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state)) { + buttons[i].func((click == ClkTagBar && buttons[i].arg.i == 0) ? &arg : &buttons[i].arg); + } + } +} + +static void checkotherwm(void) { + xerrorxlib = XSetErrorHandler(xerrorstart); + XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask); + XSync(dpy, False); + XSetErrorHandler(xerror); + XSync(dpy, False); +} + +static void cleanup(void) { + Arg a = {.ui = ~0U}; + Layout foo = { "", NULL }; + Monitor *m; + size_t i; + + view(&a); + selmon->lt[selmon->sellt] = &foo; + for (m = mons; m; m = m->next) + while (m->stack) unmanage(m->stack, 0); + XUngrabKey(dpy, AnyKey, AnyModifier, root); + while (mons) cleanupmon(mons); + + if (showsystray && systray) { + while (systray->icons) { + Client *c = systray->icons; + systray->icons = c->next; + free(c); + } + XUnmapWindow(dpy, systray->win); + XDestroyWindow(dpy, systray->win); + if (systray->use_argb && systray->colormap) + XFreeColormap(dpy, systray->colormap); + free(systray); + } + while (docks) { + DockWin *d = docks; + docks = d->next; + free(d); + } + + for (i = 0; i < CurLast; i++) drw_cur_free(drw, cursor[i]); + free(scheme[SchemeNorm]); + free(scheme[SchemeSel]); + free(scheme); + XDestroyWindow(dpy, wmcheckwin); + drw_free(drw); + XSync(dpy, False); + XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime); + XDeleteProperty(dpy, root, netatom[NetActiveWindow]); +} + +static void cleanupmon(Monitor *mon) { + Monitor *m; + if (mon == mons) mons = mons->next; + else { + for (m = mons; m && m->next != mon; m = m->next) ; + m->next = mon->next; + } + XUnmapWindow(dpy, mon->barwin); + XDestroyWindow(dpy, mon->barwin); + free(mon); +} + +static void clientmessage(XEvent *e) { + XWindowAttributes wa; + XSetWindowAttributes swa; + XClientMessageEvent *cme = &e->xclient; + Client *c = wintoclient(cme->window); + + if (showsystray && systray && cme->window == systray->win && + cme->message_type == netatom[NetSystemTrayOP]) { + if (cme->data.l[1] == SYSTEM_TRAY_REQUEST_DOCK) { + Window iw = (Window)cme->data.l[2]; + if (!iw || wintosystrayicon(iw)) + return; + if (!(c = (Client *)calloc(1, sizeof(Client)))) + die("fatal: could not malloc() %zu bytes\n", sizeof(Client)); + c->win = iw; + c->mon = systraytomon(NULL); + c->next = systray->icons; + systray->icons = c; + if (!XGetWindowAttributes(dpy, c->win, &wa)) { + wa.width = bh; + wa.height = bh; + wa.border_width = 0; + wa.depth = DefaultDepth(dpy, screen); + } + c->x = c->oldx = c->y = c->oldy = 0; + c->w = c->oldw = wa.width; + c->h = c->oldh = wa.height; + c->oldbw = wa.border_width; + c->bw = 0; + c->isfloating = True; + long flags = 0; + c->tags = getxembedflags(c->win, &flags) ? ((flags & XEMBED_MAPPED) ? 1 : 0) : 1; + updatesizehints(c); + updatesystrayicongeom(c, wa.width, wa.height); + XAddToSaveSet(dpy, c->win); + XSelectInput(dpy, c->win, StructureNotifyMask | SubstructureNotifyMask | PropertyChangeMask | ResizeRedirectMask); + XReparentWindow(dpy, c->win, systray->win, 0, 0); + if (!systray->use_argb && wa.depth == DefaultDepth(dpy, screen)) { + swa.background_pixel = scheme[SchemeNorm][ColBg].pixel; + XChangeWindowAttributes(dpy, c->win, CWBackPixel, &swa); + } + sendevent(c->win, xatom[Xembed], StructureNotifyMask, CurrentTime, + XEMBED_EMBEDDED_NOTIFY, 0, (long)systray->win, XEMBED_EMBEDDED_VERSION_VAL); + if (c->tags) { + XMapRaised(dpy, c->win); + setclientstate(c, NormalState); + sendevent(c->win, xatom[Xembed], StructureNotifyMask, CurrentTime, + XEMBED_WINDOW_ACTIVATE, 0, (long)systray->win, XEMBED_EMBEDDED_VERSION_VAL); + } else { + setclientstate(c, WithdrawnState); + } + XSync(dpy, False); + updatesystray(1); + drawbars(); + } + return; + } + + if (!c) return; + if (cme->message_type == netatom[NetWMState]) { + if ((Atom)cme->data.l[1] == netatom[NetWMFullscreen] || + (Atom)cme->data.l[2] == netatom[NetWMFullscreen]) { + setfullscreen(c, (cme->data.l[0] == 1 || + (cme->data.l[0] == 2 && !c->isfullscreen))); + } + } else if (cme->message_type == netatom[NetActiveWindow]) { + if (c != selmon->sel && !c->isurgent) + seturgent(c, 1); + } +} + +static void configure(Client *c) { + XConfigureEvent ce; + ce.type = ConfigureNotify; + ce.display = dpy; + ce.event = c->win; + ce.window = c->win; + ce.x = c->x; + ce.y = c->y; + ce.width = c->w; + ce.height = c->h; + ce.border_width = c->bw; + ce.above = None; + ce.override_redirect = False; + XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce); +} + +static void configurenotify(XEvent *e) { + 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) resizeclient(c, m->mx, m->my, m->mw, m->mh); + resizebarwin(m); + } + updatesystray(1); + updateworkarea(); + focus(NULL); + arrange(NULL); + } + } +} + +static void configurerequest(XEvent *e) { + Client *c; + Monitor *m; + XConfigureRequestEvent *ev = &e->xconfigurerequest; + XWindowChanges wc; + + if ((c = wintoclient(ev->window))) { + if (ev->value_mask & CWBorderWidth) + c->bw = ev->border_width; + else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) { + 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 & 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 ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight))) + configure(c); + if (ISVISIBLE(c)) + XMoveResizeWindow(dpy, c->win, c->x, c->y, (unsigned int)c->w, (unsigned int)c->h); + } else { + configure(c); + } + } else { + wc.x = ev->x; + wc.y = ev->y; + wc.width = ev->width; + wc.height = ev->height; + wc.border_width = ev->border_width; + wc.sibling = ev->above; + wc.stack_mode = ev->detail; + XConfigureWindow(dpy, ev->window, (unsigned int)ev->value_mask, &wc); + } + XSync(dpy, False); +} + +static Monitor *createmon(void) { + Monitor *m = ecalloc(1, sizeof(Monitor)); + m->tagset[0] = m->tagset[1] = 1; + m->mfact = mfact; + m->nmaster = nmaster; + m->showbar = showbar; + m->topbar = topbar; + m->lt[0] = &layouts[0]; + m->lt[1] = &layouts[1 % LENGTH(layouts)]; + strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol); + return m; +} + +static void destroynotify(XEvent *e) { + Client *c; + XDestroyWindowEvent *ev = &e->xdestroywindow; + if ((c = wintoclient(ev->window))) + unmanage(c, 1); + else if ((c = wintosystrayicon(ev->window))) { + removesystrayicon(c); + updatesystray(1); + drawbars(); + } else if (dockremove(ev->window)) { + recalcworkareas(); + } +} + +static void detach(Client *c) { + Client **tc; + for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next) ; + *tc = c->next; +} + +static void detachstack(Client *c) { + Client **tc, *t; + for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext) ; + *tc = c->snext; + if (c == c->mon->sel) { + for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext) ; + c->mon->sel = t; + } +} + +static Monitor *dirtomon(int dir) { + Monitor *m = NULL; + if (dir > 0) { + if (!(m = selmon->next)) m = mons; + } else if (selmon == mons) { + for (m = mons; m->next; m = m->next) ; + } else { + for (m = mons; m->next != selmon; m = m->next) ; + } + return m; +} + +static void drawbar(Monitor *m) { + int x, w, tw = 0, stw = 0; + int boxs = (int)drw->font->h / 9; + int boxw = (int)drw->font->h / 6 + 2; + unsigned int i, occ = 0, urg = 0; + Client *c; + + if (!m->showbar) return; + + if (showsystray && m == systraytomon(m) && !systrayonleft) + stw = (int)getsystraywidth(); + + if (m == selmon) { + 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); + } + + for (c = m->clients; c; c = c->next) { + occ |= c->tags; + if (c->isurgent) urg |= c->tags; + } + + /* Launcher touch button */ + drw_setscheme(drw, scheme[SchemeSel]); + int lpad = (launcher_w - (int)drw_font_getwidth(drw, "\xef\x83\x89", False)) / 2; + drw_text(drw, 0, 0, (unsigned int)launcher_w, (unsigned int)bh, (unsigned int)MAX(lpad, 4), "\xef\x83\x89", 0, False); + x = launcher_w; + + for (i = 0; i < LENGTH(tags); i++) { + w = (int)TEXTW(tags[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); + 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))), + (urg & (1U << i)) != 0); + x += w; + } + + w = (int)TEXTW(m->ltsymbol); + drw_setscheme(drw, scheme[SchemeNorm]); + x = drw_text(drw, x, 0, (unsigned int)w, (unsigned int)bh, lrpad / 2, m->ltsymbol, 0, False); + + int avail = m->ww - tw - stw - x; + if (avail > bh) { + if (m->sel) { + int title_w = avail > closebtn_w + 24 ? avail - closebtn_w : avail; + 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) { + 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); + } + } else { + drw_setscheme(drw, scheme[SchemeNorm]); + drw_rect(drw, x, 0, (unsigned int)avail, (unsigned int)bh, 1, 1); + } + } + drw_map(drw, m->barwin, 0, 0, (unsigned int)(m->ww - stw), (unsigned int)bh); +} + +static void drawbars(void) { + Monitor *m; + for (m = mons; m; m = m->next) drawbar(m); +} + +static void enternotify(XEvent *e) { + Client *c; + Monitor *m; + XCrossingEvent *ev = &e->xcrossing; + if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root) + return; + c = wintoclient(ev->window); + m = c ? c->mon : wintomon(ev->window); + if (m != selmon) { + Monitor *oldm = selmon; + unfocus(selmon->sel, 1); + selmon = m; + if (showsystray && !systraypinning && oldm) { + resizebarwin(oldm); + resizebarwin(m); + updatesystray(1); + } + } else if (!c || c == selmon->sel) { + return; + } + focus(c); +} + +static void expose(XEvent *e) { + Monitor *m; + XExposeEvent *ev = &e->xexpose; + if (ev->count == 0 && (m = wintomon(ev->window))) { + drawbar(m); + if (m == selmon) updatesystray(0); + } +} + +static void focus(Client *c) { + if (!c || !ISVISIBLE(c)) + for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext) ; + if (selmon->sel && selmon->sel != c) + unfocus(selmon->sel, 0); + if (c) { + if (c->mon != selmon) selmon = c->mon; + if (c->isurgent) seturgent(c, 0); + detachstack(c); + attachstack(c); + grabbuttons(c, 1); + XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel); + setfocus(c); + } else { + XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime); + XDeleteProperty(dpy, root, netatom[NetActiveWindow]); + } + selmon->sel = c; + drawbars(); +} + +static void focusin(XEvent *e) { + XFocusChangeEvent *ev = &e->xfocus; + if (ev->mode == NotifyGrab || ev->mode == NotifyWhileGrabbed) + return; + if (selmon->sel && ev->window != selmon->sel->win) + setfocus(selmon->sel); +} + +static void focusmon(const Arg *arg) { + Monitor *m; + if (!mons->next) return; + if ((m = dirtomon(arg->i)) == selmon) return; + Monitor *oldm = selmon; + unfocus(selmon->sel, 0); + selmon = m; + if (showsystray && !systraypinning) { + resizebarwin(oldm); + resizebarwin(m); + updatesystray(1); + } + focus(NULL); +} + +static void focusstack(const Arg *arg) { + Client *c = NULL, *i; + if (!selmon->sel || (selmon->sel->isfullscreen && lockfullscreen)) + return; + if (arg->i > 0) { + for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next) ; + if (!c) + for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next) ; + } else { + for (i = selmon->clients; i != selmon->sel; i = i->next) + if (ISVISIBLE(i)) c = i; + if (!c) + for (; i; i = i->next) + if (ISVISIBLE(i)) c = i; + } + if (c) { + focus(c); + restack(selmon); + } +} + +static Atom getatomprop(Client *c, Atom prop) { + int di; + unsigned long dl; + unsigned char *p = NULL; + Atom da, atom = None; + if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM, + &da, &di, &dl, &dl, &p) == Success && p) { + atom = *(Atom *)p; + XFree(p); + } + return atom; +} + +static int getrootptr(int *x, int *y) { + int di; + unsigned int dui; + Window dummy; + return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui); +} + +static long getstate(Window w) { + int format; + long result = -1; + unsigned char *p = NULL; + unsigned long n, extra; + Atom real; + if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState], + &real, &format, &n, &extra, (unsigned char **)&p) != Success) + return -1; + if (n != 0) result = *p; + XFree(p); + return result; +} + +static unsigned int getsystraywidth(void) { + unsigned int w = 0; + Client *i; + if (showsystray && systray) { + for (i = systray->icons; i; i = i->next) + if (i->tags) w += (unsigned int)i->w + systrayspacing; + } + return w ? w + systrayspacing : 0; +} + +static int gettextprop(Window w, Atom atom, char *text, unsigned int size) { + char **list = NULL; + int n; + XTextProperty name; + + if (!text || size == 0) return 0; + text[0] = '\0'; + if (!XGetTextProperty(dpy, w, &name, atom) || !name.nitems) return 0; + if (name.encoding == XA_STRING) { + strncpy(text, (char *)name.value, size - 1); + } else if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) { + strncpy(text, *list, size - 1); + XFreeStringList(list); + } + text[size - 1] = '\0'; + XFree(name.value); + return 1; +} + +static void grabbuttons(Client *c, int focused) { + updatenumlockmask(); + unsigned int i, j; + unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask }; + XUngrabButton(dpy, AnyButton, AnyModifier, c->win); + if (!focused) + XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, + BUTTONMASK, GrabModeSync, GrabModeSync, None, None); + for (i = 0; i < LENGTH(buttons); i++) { + if (buttons[i].click == ClkClientWin) { + for (j = 0; j < LENGTH(modifiers); j++) { + XGrabButton(dpy, buttons[i].button, buttons[i].mask | modifiers[j], + c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None); + if (buttons[i].mask & Mod4Mask) { + XGrabButton(dpy, buttons[i].button, buttons[i].mask | Mod5Mask | modifiers[j], + c->win, False, BUTTONMASK, GrabModeAsync, GrabModeSync, None, None); + } + } + } + } +} + +static void grabkeys(void) { + updatenumlockmask(); + unsigned int i, j; + unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask }; + int active_latch = super_latched && (now_ms() <= super_latch_until); + + XUngrabKey(dpy, AnyKey, AnyModifier, root); + + /* Monitor Super_L (Fn+Alt) for comfortable one-shot tap-latch fallback */ + KeyCode super_kc = XKeysymToKeycode(dpy, XK_Super_L); + if (super_kc) { + for (j = 0; j < LENGTH(modifiers); j++) { + XGrabKey(dpy, super_kc, modifiers[j], root, True, GrabModeSync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod5Mask | modifiers[j], root, True, GrabModeSync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod1Mask | modifiers[j], root, True, GrabModeSync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod1Mask | Mod5Mask | modifiers[j], root, True, GrabModeSync, GrabModeAsync); + } + } + + int min_kc = 8, max_kc = 255; + XDisplayKeycodes(dpy, &min_kc, &max_kc); + + for (i = 0; i < LENGTH(keys); i++) { + int kc_i; + for (kc_i = min_kc; kc_i <= max_kc; kc_i++) { + KeyCode kc = (KeyCode)kc_i; + KeySym s0 = XkbKeycodeToKeysym(dpy, kc, 0, 0); + KeySym s2 = XkbKeycodeToKeysym(dpy, kc, 0, 2); + KeySym s3 = XkbKeycodeToKeysym(dpy, kc, 0, 3); + + if (s0 == keys[i].keysym) { + for (j = 0; j < LENGTH(modifiers); j++) { + XGrabKey(dpy, kc, keys[i].mod | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + if (keys[i].mod & Mod4Mask) { + /* Fn+Alt frequently preserves Mod1Mask and/or Mod5Mask alongside Mod4Mask under XKB */ + XGrabKey(dpy, kc, keys[i].mod | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, kc, keys[i].mod | Mod1Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, kc, keys[i].mod | Mod1Mask | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + if (active_latch) { + XGrabKey(dpy, kc, (keys[i].mod & ~Mod4Mask) | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + } + } + } + } else if (!(keys[i].mod & Mod4Mask) && s2 == keys[i].keysym && s0 != keys[i].keysym) { + /* Grab Fn (ISO_Level3_Shift / Mod5Mask) Layer-3 multimedia/system keys */ + for (j = 0; j < LENGTH(modifiers); j++) { + XGrabKey(dpy, kc, keys[i].mod | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + } + } else if (!(keys[i].mod & Mod4Mask) && s3 == keys[i].keysym && s2 != keys[i].keysym && s0 != keys[i].keysym) { + /* Grab Shift+Fn (ShiftMask | Mod5Mask) Layer-4 keysyms */ + for (j = 0; j < LENGTH(modifiers); j++) { + XGrabKey(dpy, kc, keys[i].mod | ShiftMask | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + } + } + } + } +} + +static void grid(Monitor *m) { + unsigned int i, n, cx, cy, cw, ch, aw, ah, cols, rows; + Client *c; + for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++) ; + if (n == 0) return; + + for (cols = 0; cols <= n / 2; cols++) + if (cols * cols >= n) break; + if (n == 5) cols = 2; + rows = (cols && (cols - 1) * cols >= n) ? cols - 1 : cols; + if (rows == 0) rows = 1; + ch = (unsigned int)m->wh / rows; + cw = (unsigned int)(m->ww / (cols ? cols : 1)); + for (i = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) { + cx = (unsigned int)m->wx + (i / rows) * cw; + cy = (unsigned int)m->wy + (i % rows) * ch; + ah = (i + 1) % rows == 0 ? (unsigned int)m->wh - (i % rows) * ch : ch; + aw = (i / rows + 1) >= cols ? (unsigned int)m->ww - (i / rows) * cw : cw; + resize(c, (int)cx, (int)cy, (int)aw - 2 * c->bw, (int)ah - 2 * c->bw, 0); + } +} + +static void incnmaster(const Arg *arg) { + selmon->nmaster = MAX(selmon->nmaster + arg->i, 0); + arrange(selmon); +} + +static void keypress(XEvent *e) { + unsigned int i; + XKeyEvent *ev = &e->xkey; + KeySym sym_ev = XLookupKeysym(ev, 0); + KeySym sym0 = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 0); + KeySym sym_lvl2 = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 2); + KeySym sym_lvl3 = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 3); + unsigned long long t = now_ms(); + int active_latch = super_latched && (t <= super_latch_until); + + if (sym0 == XK_Super_L || sym_ev == XK_Super_L) { + super_down = 1; + super_dirty = 0; + super_down_ms = t; + XAllowEvents(dpy, ReplayKeyboard, ev->time); + return; + } + + if (super_down && sym0 != XK_Alt_L && sym0 != XK_ISO_Level3_Shift && + sym0 != XK_Shift_L && sym0 != XK_Shift_R && + sym0 != XK_Control_L && sym0 != XK_Control_R) { + super_dirty = 1; + } + + for (i = 0; i < LENGTH(keys); i++) { + int matched = 0; + if (sym0 == keys[i].keysym || sym_ev == keys[i].keysym) { + if (CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)) { + matched = 1; + } else if ((keys[i].mod & Mod4Mask) && + CLEANMASK(keys[i].mod) == CLEANMASK(ev->state & ~(Mod1Mask | Mod5Mask))) { + matched = 1; + } else if (active_latch && (keys[i].mod & Mod4Mask) && + CLEANMASK(keys[i].mod & ~Mod4Mask) == CLEANMASK(ev->state & ~(Mod1Mask | Mod5Mask))) { + matched = 1; + super_latched = 0; + grabkeys(); + } + } + if (!matched && !(keys[i].mod & Mod4Mask) && + (ev->state & Mod5Mask) && !(ev->state & (Mod4Mask | Mod1Mask)) && + sym_lvl2 == keys[i].keysym && sym0 != keys[i].keysym) { + if (CLEANMASK(keys[i].mod) == CLEANMASK(ev->state & ~Mod5Mask)) + matched = 1; + } + if (!matched && !(keys[i].mod & Mod4Mask) && + (ev->state & (ShiftMask | Mod5Mask)) == (ShiftMask | Mod5Mask) && + !(ev->state & (Mod4Mask | Mod1Mask)) && + sym_lvl3 == keys[i].keysym && sym_lvl2 != keys[i].keysym && sym0 != keys[i].keysym) { + if (CLEANMASK(keys[i].mod) == CLEANMASK(ev->state & ~(ShiftMask | Mod5Mask))) + matched = 1; + } + if (matched && keys[i].func) { + keys[i].func(&(keys[i].arg)); + return; + } + } + + if (active_latch) { + super_latched = 0; + grabkeys(); + } +} + +static void keyrelease(XEvent *e) { + XKeyEvent *ev = &e->xkey; + KeySym sym0 = XkbKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0, 0); + unsigned long long t = now_ms(); + + if ((sym0 == XK_Super_L || XLookupKeysym(ev, 0) == XK_Super_L) && super_down) { + super_down = 0; + if (!super_dirty && (t - super_down_ms) < 550ULL) { + super_latched = !super_latched; + super_latch_until = t + 1500ULL; + grabkeys(); + } + } +} + +static void killclient(const Arg *arg) { + (void)arg; + if (!selmon->sel) return; + if (!sendevent(selmon->sel->win, wmatom[WMDelete], NoEventMask, + (long)wmatom[WMDelete], CurrentTime, 0, 0, 0)) { + XGrabServer(dpy); + XSetErrorHandler(xerrordummy); + XSetCloseDownMode(dpy, DestroyAll); + XKillClient(dpy, selmon->sel->win); + XSync(dpy, False); + XSetErrorHandler(xerror); + XUngrabServer(dpy); + } +} + +static const char *xrm_lookup(XrmDatabase db, const char *k1, const char *k2, const char *k3) { + char *type = NULL; + XrmValue val; + if (k1 && XrmGetResource(db, k1, "*", &type, &val) && val.addr && val.addr[0]) + return val.addr; + if (k2 && XrmGetResource(db, k2, "*", &type, &val) && val.addr && val.addr[0]) + return val.addr; + if (k3 && XrmGetResource(db, k3, "*", &type, &val) && val.addr && val.addr[0]) + return val.addr; + return NULL; +} + +static void loadxres(void) { + XrmInitialize(); + XrmDatabase db = anode_open_xres_db(dpy); + double dpi = 96.0; + anode_read_xres_scale_from_db(db, dpy, &dpi, &ui_scale, NULL); + + 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); + + const char *v; + if (db && (v = xrm_lookup(db, "dwm.font", NULL, NULL))) { + snprintf(xres_font, sizeof(xres_font), "%s", v); + font = xres_font; + } else { + const char *ff = db ? xrm_lookup(db, "theme.fontFace", NULL, NULL) : NULL; + const char *ic = db ? xrm_lookup(db, "theme.iconFontFace", NULL, NULL) : NULL; + const char *bs = db ? xrm_lookup(db, "theme.baseFontSize", NULL, NULL) : NULL; + int px = bs ? atoi(bs) : anode_scale_px(15, ui_scale); + if (px < 8 || px > 96) px = anode_scale_px(15, ui_scale); + snprintf(xres_font, sizeof(xres_font), "%s, %s %dpx", + ff ? ff : "Fira Code", + ic ? ic : "DejaVuSansM Nerd Font", px); + font = xres_font; + } + + if (db) { + if ((v = xrm_lookup(db, "dwm.normbgcolor", "dwm.background", "theme.bgBar"))) + snprintf(normbgcolor, sizeof(normbgcolor), "%s", v); + if ((v = xrm_lookup(db, "dwm.normfgcolor", "dwm.foreground", "theme.fgMain"))) + snprintf(normfgcolor, sizeof(normfgcolor), "%s", v); + if ((v = xrm_lookup(db, "dwm.normbordercolor", "dwm.border", "theme.border"))) + snprintf(normbordercolor, sizeof(normbordercolor), "%s", v); + if ((v = xrm_lookup(db, "dwm.selbgcolor", "dwm.selbackground", "theme.selBg"))) + snprintf(selbgcolor, sizeof(selbgcolor), "%s", v); + if ((v = xrm_lookup(db, "dwm.selfgcolor", "dwm.selforeground", "theme.selFg"))) + snprintf(selfgcolor, sizeof(selfgcolor), "%s", v); + if ((v = xrm_lookup(db, "dwm.selbordercolor", "dwm.selborder", "theme.accent"))) + snprintf(selbordercolor, sizeof(selbordercolor), "%s", v); + if ((v = xrm_lookup(db, "dwm.borderpx", NULL, NULL))) { + int b = atoi(v); + if (b >= 1 && b <= 12) borderpx = (unsigned int)b; + } + XrmDestroyDatabase(db); + } +} + +static void reloadxres(const Arg *arg) { + (void)arg; + Monitor *m; + Client *c; + loadxres(); + if (dwmfont) { + drw_font_free(dwmfont); + dwmfont = NULL; + } + dwmfont = drw_font_create(drw, font); + drw_setfont(drw, dwmfont); + lrpad = (int)dwmfont->h + anode_scale_px(4, ui_scale); + bh = MAX((int)dwmfont->h + anode_scale_px(12, ui_scale), anode_scale_px(30, ui_scale)); + drw_resize(drw, (unsigned int)sw, (unsigned int)bh); + + free(scheme[SchemeNorm]); + free(scheme[SchemeSel]); + scheme[SchemeNorm] = drw_scm_create(drw, (const char **)colors[SchemeNorm], 3); + scheme[SchemeSel] = drw_scm_create(drw, (const char **)colors[SchemeSel], 3); + + updatebars(); + for (m = mons; m; m = m->next) { + updatebarpos(m); + resizebarwin(m); + for (c = m->clients; c; c = c->next) { + c->bw = (int)borderpx; + XSetWindowBorder(dpy, c->win, + scheme[c == selmon->sel ? SchemeSel : SchemeNorm][ColBorder].pixel); + } + } + if (showsystray && systray) { + for (c = systray->icons; c; c = c->next) + updatesystrayicongeom(c, c->w, c->h); + } + updatesystray(1); + updateworkarea(); + arrange(NULL); + drawbars(); + XSync(dpy, False); +} + +static void manage(Window w, XWindowAttributes *wa) { + Client *c, *t = NULL; + Window trans = None; + XWindowChanges wc; + + c = ecalloc(1, sizeof(Client)); + c->win = w; + c->x = c->oldx = wa->x; + c->y = c->oldy = wa->y; + c->w = c->oldw = wa->width; + c->h = c->oldh = wa->height; + c->oldbw = wa->border_width; + + updatetitle(c); + if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) { + c->mon = t->mon; + c->tags = t->tags; + } else { + c->mon = selmon; + applyrules(c); + } + + 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; + + wc.border_width = c->bw; + XConfigureWindow(dpy, w, CWBorderWidth, &wc); + XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel); + configure(c); + updatewindowtype(c); + updatesizehints(c); + updatewmhints(c); + XSelectInput(dpy, w, EnterWindowMask | FocusChangeMask | PropertyChangeMask | StructureNotifyMask); + grabbuttons(c, 0); + if (!c->isfloating) + c->isfloating = c->oldstate = (trans != None || c->isfixed); + if (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) + 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); + } + if (c->isfloating) + 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); +} + +static void mappingnotify(XEvent *e) { + XMappingEvent *ev = &e->xmapping; + XRefreshKeyboardMapping(ev); + if (ev->request == MappingKeyboard) grabkeys(); +} + +static void mapnotify(XEvent *e) { + XMapEvent *ev = &e->xmap; + if (ev->window == root || (systray && ev->window == systray->win)) + return; + if (!wintoclient(ev->window) && !wintosystrayicon(ev->window) && isdockwin(ev->window)) { + XSelectInput(dpy, ev->window, PropertyChangeMask); + dockadd(ev->window); + } +} + +static void reparentnotify(XEvent *e) { + XReparentEvent *ev = &e->xreparent; + Client *i; + if ((i = wintosystrayicon(ev->window)) && systray && ev->parent != systray->win) { + removesystrayicon(i); + updatesystray(1); + drawbars(); + } +} + +static void maprequest(XEvent *e) { + static XWindowAttributes wa; + XMapRequestEvent *ev = &e->xmaprequest; + Client *i; + if ((i = wintosystrayicon(ev->window))) { + long flags = 0; + int mapped = getxembedflags(i->win, &flags) ? ((flags & XEMBED_MAPPED) ? 1 : 0) : 1; + i->tags = mapped ? 1 : 0; + if (mapped) { + XMapRaised(dpy, i->win); + setclientstate(i, NormalState); + sendevent(i->win, xatom[Xembed], StructureNotifyMask, CurrentTime, + XEMBED_WINDOW_ACTIVATE, 0, (long)systray->win, XEMBED_EMBEDDED_VERSION_VAL); + } + updatesystray(1); + drawbars(); + return; + } + if (isdockwin(ev->window)) { + XSelectInput(dpy, ev->window, StructureNotifyMask | PropertyChangeMask); + dockadd(ev->window); + XMapWindow(dpy, ev->window); + return; + } + if (!XGetWindowAttributes(dpy, ev->window, &wa) || wa.override_redirect) + return; + if (!wintoclient(ev->window)) + manage(ev->window, &wa); +} + +static void monocle(Monitor *m) { + unsigned int n = 0; + Client *c; + for (c = m->clients; c; c = c->next) + if (ISVISIBLE(c)) n++; + if (n > 0) + snprintf(m->ltsymbol, sizeof m->ltsymbol, "[%u]", n); + for (c = nexttiled(m->clients); c; c = nexttiled(c->next)) + resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0); +} + +static void motionnotify(XEvent *e) { + static Monitor *mon = NULL; + Monitor *m; + XMotionEvent *ev = &e->xmotion; + if (ev->window != root) return; + if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) { + Monitor *oldm = selmon; + unfocus(selmon->sel, 1); + selmon = m; + if (showsystray && !systraypinning && oldm && oldm != m) { + resizebarwin(oldm); + resizebarwin(m); + updatesystray(1); + } + focus(NULL); + } + mon = m; +} + +static void movemouse(const Arg *arg) { + (void)arg; + int x, y, ocx, ocy, nx, ny; + Client *c; + Monitor *m; + XEvent ev; + Time lasttime = 0; + + if (!(c = selmon->sel) || c->isfullscreen) return; + restack(selmon); + ocx = c->x; + ocy = c->y; + if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync, + None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess) + return; + if (!getrootptr(&x, &y)) return; + do { + XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev); + switch (ev.type) { + case ConfigureRequest: + case Expose: + case MapRequest: + handler[ev.type](&ev); + break; + case MotionNotify: + if ((ev.xmotion.time - lasttime) <= (1000 / 60)) continue; + lasttime = ev.xmotion.time; + nx = ocx + (ev.xmotion.x - x); + ny = ocy + (ev.xmotion.y - y); + if (abs(selmon->wx - nx) < (int)snap) nx = selmon->wx; + else if (abs((selmon->wx + selmon->ww) - (nx + WIDTH(c))) < (int)snap) + nx = selmon->wx + selmon->ww - WIDTH(c); + if (abs(selmon->wy - ny) < (int)snap) ny = selmon->wy; + else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < (int)snap) + ny = selmon->wy + selmon->wh - HEIGHT(c); + if (!c->isfloating && selmon->lt[selmon->sellt]->arrange && + (abs(nx - c->x) > (int)snap || abs(ny - c->y) > (int)snap)) + togglefloating(NULL); + if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) + resize(c, nx, ny, c->w, c->h, 1); + break; + } + } while (ev.type != ButtonRelease); + XUngrabPointer(dpy, CurrentTime); + if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) { + sendmon(c, m); + selmon = m; + focus(NULL); + } +} + +static Client *nexttiled(Client *c) { + for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next) ; + return c; +} + +static void pop(Client *c) { + detach(c); + attach(c); + focus(c); + arrange(c->mon); +} + +static void propertynotify(XEvent *e) { + Client *c; + Window trans; + XPropertyEvent *ev = &e->xproperty; + + if ((c = wintosystrayicon(ev->window))) { + if (ev->atom == XA_WM_NORMAL_HINTS) { + updatesizehints(c); + updatesystrayicongeom(c, c->w, c->h); + } else { + updatesystrayiconstate(c, ev); + } + updatesystray(1); + drawbars(); + return; + } + + if ((ev->window == root) && (ev->atom == XA_RESOURCE_MANAGER) && + ev->state != PropertyDelete) { + reloadxres(NULL); + return; + } + + if (ev->state != PropertyDelete && + (ev->atom == netatom[NetWMStrutPartial] || ev->atom == netatom[NetWMStrut])) { + dockupdate(ev->window); + } else if (ev->state != PropertyDelete && ev->atom == netatom[NetWMWindowType] && + isdockwin(ev->window) && !wintoclient(ev->window)) { + XSelectInput(dpy, ev->window, StructureNotifyMask | PropertyChangeMask); + dockadd(ev->window); + } + + if ((ev->window == root) && (ev->atom == XA_WM_NAME)) { + updatestatus(); + } else if (ev->state == PropertyDelete) { + return; + } else if ((c = wintoclient(ev->window))) { + switch (ev->atom) { + case XA_WM_TRANSIENT_FOR: + if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) && + (c->isfloating = (wintoclient(trans) != NULL))) + arrange(c->mon); + break; + case XA_WM_NORMAL_HINTS: + c->hintsvalid = 0; + break; + case XA_WM_HINTS: + updatewmhints(c); + drawbars(); + break; + } + if (ev->atom == XA_WM_NAME || ev->atom == netatom[NetWMName]) { + updatetitle(c); + if (c == c->mon->sel) drawbar(c->mon); + } + if (ev->atom == netatom[NetWMWindowType]) + updatewindowtype(c); + } +} + +static void quit(const Arg *arg) { + (void)arg; + running = 0; +} + +static Monitor *recttomon(int x, int y, int w, int h) { + Monitor *m, *r = selmon; + int a, area = 0; + for (m = mons; m; m = m->next) { + if ((a = INTERSECT(x, y, w, h, m)) > area) { + area = a; + r = m; + } + } + return r; +} + +static void removesystrayicon(Client *i) { + Client **ii; + if (!showsystray || !i || !systray) return; + for (ii = &systray->icons; *ii && *ii != i; ii = &(*ii)->next) ; + if (*ii) *ii = i->next; + free(i); +} + +static void resize(Client *c, int x, int y, int w, int h, int interact) { + if (applysizehints(c, &x, &y, &w, &h, interact)) + resizeclient(c, x, y, w, h); +} + +static void resizebarwin(Monitor *m) { + unsigned int w = (unsigned int)m->ww; + if (showsystray && m == systraytomon(m) && !systrayonleft) + w -= getsystraywidth(); + XMoveResizeWindow(dpy, m->barwin, m->wx, m->by, w, (unsigned int)bh); +} + +static void resizeclient(Client *c, int x, int y, int w, int h) { + XWindowChanges wc; + c->oldx = c->x; c->x = wc.x = x; + c->oldy = c->y; c->y = wc.y = y; + c->oldw = c->w; c->w = wc.width = w; + c->oldh = c->h; c->h = wc.height = h; + wc.border_width = c->bw; + XConfigureWindow(dpy, c->win, CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc); + configure(c); + XSync(dpy, False); +} + +static void resizemouse(const Arg *arg) { + (void)arg; + int ocx, ocy, nw, nh; + Client *c; + Monitor *m; + XEvent ev; + Time lasttime = 0; + + if (!(c = selmon->sel) || c->isfullscreen) return; + restack(selmon); + ocx = c->x; + ocy = c->y; + if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync, + None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess) + return; + XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1); + do { + XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, &ev); + switch (ev.type) { + case ConfigureRequest: + case Expose: + case MapRequest: + handler[ev.type](&ev); + break; + case MotionNotify: + if ((ev.xmotion.time - lasttime) <= (1000 / 60)) continue; + lasttime = ev.xmotion.time; + nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1); + nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1); + if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww && + c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh) { + if (!c->isfloating && selmon->lt[selmon->sellt]->arrange && + (abs(nw - c->w) > (int)snap || abs(nh - c->h) > (int)snap)) + togglefloating(NULL); + } + if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) + resize(c, c->x, c->y, nw, nh, 1); + break; + } + } while (ev.type != ButtonRelease); + XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1); + XUngrabPointer(dpy, CurrentTime); + while (XCheckMaskEvent(dpy, EnterWindowMask, &ev)) ; + if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) { + sendmon(c, m); + selmon = m; + focus(NULL); + } +} + +static void resizerequest(XEvent *e) { + XResizeRequestEvent *ev = &e->xresizerequest; + Client *i; + if ((i = wintosystrayicon(ev->window))) { + updatesystrayicongeom(i, ev->width, ev->height); + resizebarwin(selmon); + updatesystray(0); + } +} + +static void restack(Monitor *m) { + Client *c; + XEvent ev; + XWindowChanges wc; + drawbar(m); + if (!m->sel) return; + if (m->sel->isfloating || !m->lt[m->sellt]->arrange) + XRaiseWindow(dpy, m->sel->win); + if (m->lt[m->sellt]->arrange) { + wc.stack_mode = Below; + wc.sibling = m->barwin; + for (c = m->stack; c; c = c->snext) { + if (!c->isfloating && ISVISIBLE(c)) { + XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc); + wc.sibling = c->win; + } + } + } + XSync(dpy, False); + while (XCheckMaskEvent(dpy, EnterWindowMask, &ev)) ; +} + +static void run(void) { + XEvent ev; + struct pollfd pfd = { .fd = ConnectionNumber(dpy), .events = POLLIN }; + XSync(dpy, False); + while (running) { + if (reload_pending) { + reload_pending = 0; + reloadxres(NULL); + } + if (super_latched && now_ms() > super_latch_until) { + super_latched = 0; + grabkeys(); + } + while (XPending(dpy) > 0) { + XNextEvent(dpy, &ev); + if (handler[ev.type]) + handler[ev.type](&ev); + } + if (!running) break; + int timeout_ms = super_latched ? 250 : -1; + int pr = poll(&pfd, 1, timeout_ms); + if (pr < 0 && errno != EINTR) break; + } +} + +static void scan(void) { + unsigned int i, num; + Window d1, d2, *wins = NULL; + XWindowAttributes wa; + if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) { + for (i = 0; i < num; i++) { + if (!XGetWindowAttributes(dpy, wins[i], &wa)) + continue; + if (wa.map_state == IsViewable && isdockwin(wins[i])) { + XSelectInput(dpy, wins[i], StructureNotifyMask | PropertyChangeMask); + dockadd(wins[i]); + continue; + } + if (wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1)) + continue; + if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState) + manage(wins[i], &wa); + } + for (i = 0; i < num; i++) { + if (!XGetWindowAttributes(dpy, wins[i], &wa)) continue; + if (!wa.override_redirect && XGetTransientForHint(dpy, wins[i], &d1) && + (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)) + manage(wins[i], &wa); + } + if (wins) XFree(wins); + } +} + +static void sendmon(Client *c, Monitor *m) { + if (c->mon == m) return; + unfocus(c, 1); + detach(c); + detachstack(c); + c->mon = m; + c->tags = m->tagset[m->seltags]; + attach(c); + attachstack(c); + focus(NULL); + arrange(NULL); +} + +static void setclientstate(Client *c, long state) { + long data[] = { state, None }; + XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32, + PropModeReplace, (unsigned char *)data, 2); +} + +static int sendevent(Window w, Atom proto, int mask, long d0, long d1, long d2, long d3, long d4) { + int n; + Atom *protocols, mt; + int exists = 0; + XEvent ev; + + if (proto == wmatom[WMTakeFocus] || proto == wmatom[WMDelete]) { + mt = wmatom[WMProtocols]; + if (XGetWMProtocols(dpy, w, &protocols, &n)) { + while (!exists && n--) exists = (protocols[n] == proto); + XFree(protocols); + } + } else { + exists = True; + mt = proto; + } + if (exists) { + ev.type = ClientMessage; + ev.xclient.window = w; + ev.xclient.message_type = mt; + ev.xclient.format = 32; + ev.xclient.data.l[0] = d0; + ev.xclient.data.l[1] = d1; + ev.xclient.data.l[2] = d2; + ev.xclient.data.l[3] = d3; + ev.xclient.data.l[4] = d4; + XSendEvent(dpy, w, False, mask, &ev); + } + return exists; +} + +static void setfocus(Client *c) { + if (!c->neverfocus) { + XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime); + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&(c->win), 1); + } + sendevent(c->win, wmatom[WMTakeFocus], NoEventMask, (long)wmatom[WMTakeFocus], CurrentTime, 0, 0, 0); +} + +static void setfullscreen(Client *c, int fullscreen) { + if (fullscreen && !c->isfullscreen) { + XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, + PropModeReplace, (unsigned char *)&netatom[NetWMFullscreen], 1); + c->isfullscreen = 1; + c->oldstate = c->isfloating; + c->oldbw = c->bw; + c->bw = 0; + c->isfloating = 1; + resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh); + XRaiseWindow(dpy, c->win); + } else if (!fullscreen && c->isfullscreen) { + XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, + PropModeReplace, (unsigned char *)0, 0); + c->isfullscreen = 0; + c->isfloating = c->oldstate; + c->bw = c->oldbw; + c->x = c->oldx; c->y = c->oldy; + c->w = c->oldw; c->h = c->oldh; + resizeclient(c, c->x, c->y, c->w, c->h); + arrange(c->mon); + } +} + +static void setlayout(const Arg *arg) { + if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt]) + selmon->sellt ^= 1; + if (arg && arg->v) + selmon->lt[selmon->sellt] = (const Layout *)arg->v; + snprintf(selmon->ltsymbol, sizeof selmon->ltsymbol, "%s", selmon->lt[selmon->sellt]->symbol); + if (selmon->sel) arrange(selmon); + else drawbar(selmon); +} + +static void setmfact(const Arg *arg) { + float f; + if (!arg || !selmon->lt[selmon->sellt]->arrange) return; + f = arg->f < 1.0 ? arg->f + selmon->mfact : arg->f - 1.0; + if (f < 0.05 || f > 0.95) return; + selmon->mfact = f; + arrange(selmon); +} + +static void setup(void) { + XSetWindowAttributes wa; + Atom utf8string; + struct sigaction sa; + + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_NOCLDSTOP | SA_NOCLDWAIT | SA_RESTART; + sa.sa_handler = sigchld_handler; + sigaction(SIGCHLD, &sa, NULL); + while (waitpid(-1, NULL, WNOHANG) > 0) ; + + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = sigusr1_handler; + sigaction(SIGUSR1, &sa, NULL); + + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = sighup_handler; + sigaction(SIGHUP, &sa, NULL); + + loadxres(); + + screen = DefaultScreen(dpy); + sw = DisplayWidth(dpy, screen); + sh = DisplayHeight(dpy, screen); + root = RootWindow(dpy, screen); + drw = drw_create(dpy, screen, root, (unsigned int)sw, (unsigned int)sh); + dwmfont = drw_font_create(drw, font); + drw_setfont(drw, dwmfont); + lrpad = (int)dwmfont->h + anode_scale_px(4, ui_scale); + bh = MAX((int)dwmfont->h + anode_scale_px(12, ui_scale), anode_scale_px(30, ui_scale)); + updategeom(); + + { + char trayatom[64]; + snprintf(trayatom, sizeof(trayatom), "_NET_SYSTEM_TRAY_S%d", screen); + netatom[NetSystemTray] = XInternAtom(dpy, trayatom, False); + } + utf8string = XInternAtom(dpy, "UTF8_STRING", False); + wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False); + wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False); + wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False); + wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False); + netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False); + netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False); + netatom[NetSystemTrayOP] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_OPCODE", False); + netatom[NetSystemTrayOrientation] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_ORIENTATION", False); + netatom[NetSystemTrayOrientationHorz] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_ORIENTATION_HORZ", False); + netatom[NetSystemTrayVisual] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_VISUAL", False); + netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False); + netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False); + netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False); + netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); + netatom[NetWorkarea] = XInternAtom(dpy, "_NET_WORKAREA", 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); + netatom[NetWMStrutPartial] = XInternAtom(dpy, "_NET_WM_STRUT_PARTIAL", False); + netatom[NetWMStrut] = XInternAtom(dpy, "_NET_WM_STRUT", False); + netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False); + xatom[Manager] = XInternAtom(dpy, "MANAGER", False); + xatom[Xembed] = XInternAtom(dpy, "_XEMBED", False); + xatom[XembedInfo] = XInternAtom(dpy, "_XEMBED_INFO", False); + + cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr); + cursor[CurResize] = drw_cur_create(drw, XC_sizing); + cursor[CurMove] = drw_cur_create(drw, XC_fleur); + + scheme = ecalloc(2, sizeof(Clr *)); + scheme[SchemeNorm] = drw_scm_create(drw, (const char **)colors[SchemeNorm], 3); + scheme[SchemeSel] = drw_scm_create(drw, (const char **)colors[SchemeSel], 3); + + updatesystray(0); + updatebars(); + updateworkarea(); + updatestatus(); + + wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0); + XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&wmcheckwin, 1); + XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8, + PropModeReplace, (unsigned char *)"dwm", 3); + XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&wmcheckwin, 1); + XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32, + PropModeReplace, (unsigned char *)netatom, NetLast); + XDeleteProperty(dpy, root, netatom[NetClientList]); + + wa.cursor = cursor[CurNormal]->cursor; + wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask | + ButtonPressMask | PointerMotionMask | EnterWindowMask | + LeaveWindowMask | StructureNotifyMask | PropertyChangeMask | + FocusChangeMask; + XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa); + XSelectInput(dpy, root, wa.event_mask); + grabkeys(); + focus(NULL); +} + +static void seturgent(Client *c, int urg) { + XWMHints *wmh; + c->isurgent = urg; + if (!(wmh = XGetWMHints(dpy, c->win))) return; + wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint); + XSetWMHints(dpy, c->win, wmh); + XFree(wmh); +} + +static void showhide(Client *c) { + if (!c) return; + if (ISVISIBLE(c)) { + XMoveWindow(dpy, c->win, c->x, c->y); + if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen) + resize(c, c->x, c->y, c->w, c->h, 0); + showhide(c->snext); + } else { + showhide(c->snext); + XMoveWindow(dpy, c->win, WIDTH(c) * -2, c->y); + } +} + +static void sigchld_handler(int sig) { + (void)sig; + while (waitpid(-1, NULL, WNOHANG) > 0) ; +} + +static void sigusr1_handler(int sig) { + (void)sig; + reload_pending = 1; +} + +static void sighup_handler(int sig) { + (void)sig; + restart_dwm = 1; + running = 0; +} + +static void spawn(const Arg *arg) { + struct sigaction sa; + if (fork() == 0) { + if (dpy) close(ConnectionNumber(dpy)); + setsid(); + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = SIG_DFL; + sigaction(SIGCHLD, &sa, NULL); + execvp(((char **)arg->v)[0], (char **)arg->v); + die("dwm: execvp '%s' failed:", ((char **)arg->v)[0]); + } +} + +static Monitor *systraytomon(Monitor *m) { + Monitor *t; + unsigned int i, n; + if (!systraypinning) { + if (!m) return selmon; + return m == selmon ? m : NULL; + } + for (n = 1, t = mons; t && t->next; n++, t = t->next) ; + for (i = 1, t = mons; t && t->next && i < systraypinning; i++, t = t->next) ; + if (systraypinningfailfirst && n < systraypinning) return mons; + return t; +} + +static void tag(const Arg *arg) { + if (selmon->sel && (arg->ui & TAGMASK)) { + selmon->sel->tags = arg->ui & TAGMASK; + focus(NULL); + arrange(selmon); + } +} + +static void tagmon(const Arg *arg) { + if (!selmon->sel || !mons->next) return; + sendmon(selmon->sel, dirtomon(arg->i)); +} + +static void tile(Monitor *m) { + unsigned int i, n, h, mw, my, ty; + Client *c; + for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++) ; + if (n == 0) return; + + if (n > (unsigned int)m->nmaster) + mw = m->nmaster ? (unsigned int)(m->ww * m->mfact) : 0; + else + mw = (unsigned int)m->ww; + for (i = 0, my = ty = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) { + if (i < (unsigned int)m->nmaster) { + h = ((unsigned int)m->wh - my) / (MIN(n, (unsigned int)m->nmaster) - i); + resize(c, m->wx, m->wy + (int)my, (int)mw - 2 * c->bw, (int)h - 2 * c->bw, 0); + if (my + (unsigned int)HEIGHT(c) < (unsigned int)m->wh) + my += (unsigned int)HEIGHT(c); + } else { + h = ((unsigned int)m->wh - ty) / (n - i); + resize(c, m->wx + (int)mw, m->wy + (int)ty, m->ww - (int)mw - 2 * c->bw, (int)h - 2 * c->bw, 0); + if (ty + (unsigned int)HEIGHT(c) < (unsigned int)m->wh) + ty += (unsigned int)HEIGHT(c); + } + } +} + +static void togglebar(const Arg *arg) { + (void)arg; + selmon->showbar = !selmon->showbar; + updatebarpos(selmon); + resizebarwin(selmon); + if (showsystray && systray) { + XWindowChanges wc; + if (!selmon->showbar) wc.y = -bh; + else if (selmon->showbar) { + wc.y = 0; + if (!selmon->topbar) wc.y = selmon->mh - bh; + } + XConfigureWindow(dpy, systray->win, CWY, &wc); + } + arrange(selmon); +} + +static void togglefloating(const Arg *arg) { + (void)arg; + if (!selmon->sel || selmon->sel->isfullscreen) return; + 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); + arrange(selmon); +} + +static void toggletag(const Arg *arg) { + unsigned int newtags; + if (!selmon->sel) return; + newtags = selmon->sel->tags ^ (arg->ui & TAGMASK); + if (newtags) { + selmon->sel->tags = newtags; + focus(NULL); + arrange(selmon); + } +} + +static void toggleview(const Arg *arg) { + unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK); + if (newtagset) { + selmon->tagset[selmon->seltags] = newtagset; + focus(NULL); + arrange(selmon); + } +} + +static void unfocus(Client *c, int setfocus) { + if (!c) return; + grabbuttons(c, 0); + XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel); + if (setfocus) { + XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime); + XDeleteProperty(dpy, root, netatom[NetActiveWindow]); + } +} + +static void unmanage(Client *c, int destroyed) { + Monitor *m = c->mon; + XWindowChanges wc; + detach(c); + detachstack(c); + if (!destroyed) { + wc.border_width = c->oldbw; + XGrabServer(dpy); + XSetErrorHandler(xerrordummy); + XSelectInput(dpy, c->win, NoEventMask); + XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); + XUngrabButton(dpy, AnyButton, AnyModifier, c->win); + setclientstate(c, WithdrawnState); + XSync(dpy, False); + XSetErrorHandler(xerror); + XUngrabServer(dpy); + } + free(c); + focus(NULL); + updateclientlist(); + arrange(m); +} + +static void unmapnotify(XEvent *e) { + Client *c; + XUnmapEvent *ev = &e->xunmap; + if ((c = wintoclient(ev->window))) { + if (ev->send_event) setclientstate(c, WithdrawnState); + else unmanage(c, 0); + } else if ((c = wintosystrayicon(ev->window))) { + if (c->tags) { + c->tags = 0; + setclientstate(c, WithdrawnState); + updatesystray(1); + drawbars(); + } + } else if (dockremove(ev->window)) { + recalcworkareas(); + } +} + +static void updatebars(void) { + unsigned int w; + Monitor *m; + XSetWindowAttributes wa = { + .override_redirect = True, + .background_pixmap = ParentRelative, + .event_mask = ButtonPressMask | ExposureMask + }; + XClassHint ch = {"dwm", "dwm"}; + for (m = mons; m; m = m->next) { + if (m->barwin) continue; + w = (unsigned int)m->ww; + if (showsystray && m == systraytomon(m) && !systrayonleft) w -= getsystraywidth(); + m->barwin = XCreateWindow(dpy, root, m->wx, m->by, w, (unsigned int)bh, 0, + DefaultDepth(dpy, screen), CopyFromParent, + DefaultVisual(dpy, screen), + CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa); + XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor); + if (showsystray && m == systraytomon(m) && systray && getsystraywidth() > 0) + XMapRaised(dpy, systray->win); + XMapRaised(dpy, m->barwin); + XSetClassHint(dpy, m->barwin, &ch); + } +} + +static void updatebarpos(Monitor *m) { + m->wx = m->mx; + m->wy = m->my; + m->ww = m->mw; + m->wh = m->mh; + if (m->showbar) { + m->wh -= bh; + m->by = m->topbar ? m->wy : m->wy + m->wh; + m->wy = m->topbar ? m->wy + bh : m->wy; + } else { + m->by = -bh; + } + for (DockWin *d = docks; d; d = d->next) { + unsigned long left = d->strut[0], right = d->strut[1]; + unsigned long top = d->strut[2], bottom = d->strut[3]; + unsigned long lsy = d->strut[4], ley = d->strut[5]; + unsigned long rsy = d->strut[6], rey = d->strut[7]; + unsigned long tsx = d->strut[8], tex = d->strut[9]; + unsigned long bsx = d->strut[10], bex = d->strut[11]; + int m_x2 = m->mx + m->mw, m_y2 = m->my + m->mh; + + if (left > 0 && ((ley == 0 && lsy == 0) || ((long)lsy < m_y2 && (long)ley >= m->my))) { + int nx = MAX(m->wx, (int)left); + if (nx > m->wx && nx < m->wx + m->ww) { + m->ww -= (nx - m->wx); + m->wx = nx; + } + } + if (right > 0 && ((rey == 0 && rsy == 0) || ((long)rsy < m_y2 && (long)rey >= m->my))) { + int rx = sw - (int)right; + if (rx < m->wx + m->ww && rx > m->wx) + m->ww = rx - m->wx; + } + if (top > 0 && ((tex == 0 && tsx == 0) || ((long)tsx < m_x2 && (long)tex >= m->mx))) { + int ny = MAX(m->wy, (int)top); + if (ny > m->wy && ny < m->wy + m->wh) { + m->wh -= (ny - m->wy); + m->wy = ny; + } + } + if (bottom > 0 && ((bex == 0 && bsx == 0) || ((long)bsx < m_x2 && (long)bex >= m->mx))) { + int by_lim = sh - (int)bottom; + if (by_lim < m->wy + m->wh && by_lim > m->wy) + m->wh = by_lim - m->wy; + } + } + if (m->ww < 64) m->ww = 64; + if (m->wh < 64) m->wh = 64; +} + +static void updateclientlist(void) { + Client *c; + Monitor *m; + XDeleteProperty(dpy, root, netatom[NetClientList]); + for (m = mons; m; m = m->next) + for (c = m->clients; c; c = c->next) + XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, + PropModeAppend, (unsigned char *)&(c->win), 1); +} + +static int updategeom(void) { + int dirty = 0; +#ifdef XINERAMA + if (XineramaIsActive(dpy)) { + int i, j, n, nn; + Client *c; + Monitor *m; + XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn); + XineramaScreenInfo *unique = ecalloc((size_t)nn, sizeof(XineramaScreenInfo)); + + for (n = 0, m = mons; m; m = m->next, n++) ; + for (i = 0, j = 0; i < nn; i++) { + int dup = 0; + for (int k = 0; k < j; k++) { + if (unique[k].x_org == info[i].x_org && unique[k].y_org == info[i].y_org && + unique[k].width == info[i].width && unique[k].height == info[i].height) { + dup = 1; + break; + } + } + if (!dup) memcpy(&unique[j++], &info[i], sizeof(XineramaScreenInfo)); + } + XFree(info); + nn = j; + 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 { + for (i = nn; i < n; i++) { + for (m = mons; m && m->next; m = m->next) ; + while ((c = m->clients)) { + dirty = 1; + m->clients = c->next; + detachstack(c); + c->mon = mons; + attach(c); + attachstack(c); + } + if (m == selmon) selmon = mons; + cleanupmon(m); + } + } + free(unique); + } else +#endif + { + if (!mons) mons = createmon(); + if (mons->mw != sw || mons->mh != sh) { + dirty = 1; + mons->mw = mons->ww = sw; + mons->mh = mons->wh = sh; + updatebarpos(mons); + } + } + if (dirty) { + selmon = mons; + selmon = wintomon(root); + } + return dirty; +} + +static void updatenumlockmask(void) { + unsigned int i; + int j; + XModifierKeymap *modmap = XGetModifierMapping(dpy); + numlockmask = 0; + for (i = 0; i < 8; i++) + for (j = 0; j < modmap->max_keypermod; j++) + if (modmap->modifiermap[i * modmap->max_keypermod + j] == + XKeysymToKeycode(dpy, XK_Num_Lock)) + numlockmask = (1U << i); + XFreeModifiermap(modmap); +} + +static void updatesizehints(Client *c) { + long msize; + XSizeHints size; + if (!XGetWMNormalHints(dpy, c->win, &size, &msize)) + size.flags = PSize; + if (size.flags & PBaseSize) { c->basew = size.base_width; c->baseh = size.base_height; } + else if (size.flags & PMinSize) { c->basew = size.min_width; c->baseh = size.min_height; } + else c->basew = c->baseh = 0; + + if (size.flags & PResizeInc) { c->incw = size.width_inc; c->inch = size.height_inc; } + else c->incw = c->inch = 0; + + if (size.flags & PMaxSize) { c->maxw = size.max_width; c->maxh = size.max_height; } + else c->maxw = c->maxh = 0; + + if (size.flags & PMinSize) { c->minw = size.min_width; c->minh = size.min_height; } + else if (size.flags & PBaseSize) { c->minw = size.base_width; c->minh = size.base_height; } + else c->minw = c->minh = 0; + + if (size.flags & PAspect) { + c->mina = (float)size.min_aspect.y / size.min_aspect.x; + c->maxa = (float)size.max_aspect.x / size.max_aspect.y; + } else { + c->maxa = c->mina = 0.0; + } + c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh); + c->hintsvalid = 1; +} + +static void updatestatus(void) { + if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext))) + strcpy(stext, "ANODE"); + drawbar(selmon); + updatesystray(1); +} + +static unsigned long systray_bg_pixel(void) { + if (systray && systray->use_argb) { + XRenderColor rc = scheme[SchemeNorm][ColBg].color; + unsigned long r = (unsigned long)(rc.red >> 8) & 0xff; + unsigned long g = (unsigned long)(rc.green >> 8) & 0xff; + unsigned long b = (unsigned long)(rc.blue >> 8) & 0xff; + return 0xff000000UL | (r << 16) | (g << 8) | b; + } + return scheme[SchemeNorm][ColBg].pixel; +} + +static int getxembedflags(Window w, long *flags_out) { + int di; + unsigned long dl, n = 0; + unsigned char *p = NULL; + Atom da = None; + if (XGetWindowProperty(dpy, w, xatom[XembedInfo], 0L, 2L, False, AnyPropertyType, + &da, &di, &n, &dl, &p) == Success && p) { + int ok = (di == 32 && n >= 2); + if (ok && flags_out) + *flags_out = (long)((unsigned long *)p)[1]; + XFree(p); + return ok; + } + return 0; +} + +static int isdockwin(Window w) { + int di; + unsigned long dl, n = 0; + unsigned char *p = NULL; + Atom da = None; + if (XGetWindowProperty(dpy, w, netatom[NetWMWindowType], 0L, 16L, False, XA_ATOM, + &da, &di, &n, &dl, &p) == Success && p) { + int is_dock = 0; + if (di == 32 && da == XA_ATOM) { + Atom *atoms = (Atom *)p; + for (unsigned long i = 0; i < n; i++) { + if (atoms[i] == netatom[NetWMWindowTypeDock]) { + is_dock = 1; + break; + } + } + } + XFree(p); + return is_dock; + } + return 0; +} + +static void readdocks_strut(Window w, unsigned long strut[12]) { + int di; + unsigned long dl, n = 0; + unsigned char *p = NULL; + Atom da = None; + memset(strut, 0, sizeof(unsigned long) * 12); + if (XGetWindowProperty(dpy, w, netatom[NetWMStrutPartial], 0L, 12L, False, XA_CARDINAL, + &da, &di, &n, &dl, &p) == Success && p) { + if (di == 32 && n >= 4) { + unsigned long *vals = (unsigned long *)p; + unsigned long lim = MIN(n, 12UL); + for (unsigned long i = 0; i < lim; i++) strut[i] = vals[i]; + } + XFree(p); + return; + } + if (XGetWindowProperty(dpy, w, netatom[NetWMStrut], 0L, 4L, False, XA_CARDINAL, + &da, &di, &n, &dl, &p) == Success && p) { + if (di == 32 && n >= 4) { + unsigned long *vals = (unsigned long *)p; + for (int i = 0; i < 4; i++) strut[i] = vals[i]; + } + XFree(p); + } +} + +static void updateworkarea(void) { + Monitor *m = selmon ? selmon : mons; + if (!m) return; + unsigned long data[LENGTH(tags) * 4]; + for (size_t i = 0; i < LENGTH(tags); i++) { + data[i * 4 + 0] = (unsigned long)MAX(0, m->wx); + data[i * 4 + 1] = (unsigned long)MAX(0, m->wy); + data[i * 4 + 2] = (unsigned long)MAX(1, m->ww); + data[i * 4 + 3] = (unsigned long)MAX(1, m->wh); + } + XChangeProperty(dpy, root, netatom[NetWorkarea], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)data, (int)(LENGTH(tags) * 4)); +} + +static void recalcworkareas(void) { + for (Monitor *m = mons; m; m = m->next) + updatebarpos(m); + updateworkarea(); + arrange(NULL); + drawbars(); +} + +static void dockadd(Window w) { + for (DockWin *d = docks; d; d = d->next) { + if (d->win == w) { + readdocks_strut(w, d->strut); + recalcworkareas(); + return; + } + } + DockWin *d = ecalloc(1, sizeof(DockWin)); + d->win = w; + readdocks_strut(w, d->strut); + d->next = docks; + docks = d; + recalcworkareas(); +} + +static int dockremove(Window w) { + DockWin **pp = &docks; + while (*pp) { + if ((*pp)->win == w) { + DockWin *victim = *pp; + *pp = victim->next; + free(victim); + return 1; + } + pp = &(*pp)->next; + } + return 0; +} + +static void dockupdate(Window w) { + for (DockWin *d = docks; d; d = d->next) { + if (d->win == w) { + readdocks_strut(w, d->strut); + recalcworkareas(); + return; + } + } +} + +static void updatesystray(int updatebar) { + XSetWindowAttributes wa; + XWindowChanges wc; + Client *i; + Monitor *m = systraytomon(NULL); + unsigned int x = (unsigned int)(m->mx + m->mw); + unsigned int sw_tray = TEXTW(stext) - (unsigned int)lrpad + systrayspacing; + unsigned int w = 0; + + if (!showsystray) return; + if (!systrayonleft) x -= sw_tray; + if (!systray) { + XVisualInfo vinfo; + unsigned long orient = 0; + VisualID vid; + if (!(systray = (Systray *)calloc(1, sizeof(Systray)))) + die("fatal: could not malloc() %zu bytes\n", sizeof(Systray)); + if (XMatchVisualInfo(dpy, screen, 32, TrueColor, &vinfo)) { + systray->visual = vinfo.visual; + systray->depth = 32; + systray->colormap = XCreateColormap(dpy, root, vinfo.visual, AllocNone); + systray->use_argb = 1; + } else { + systray->visual = DefaultVisual(dpy, screen); + systray->depth = DefaultDepth(dpy, screen); + systray->colormap = DefaultColormap(dpy, screen); + systray->use_argb = 0; + } + memset(&wa, 0, sizeof(wa)); + wa.event_mask = SubstructureNotifyMask | ButtonPressMask | ExposureMask; + wa.override_redirect = True; + wa.border_pixel = 0; + wa.colormap = systray->colormap; + wa.background_pixel = systray_bg_pixel(); + systray->win = XCreateWindow(dpy, root, (int)x, m->by, 1, (unsigned int)bh, 0, + systray->depth, InputOutput, systray->visual, + CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWColormap | CWEventMask, + &wa); + XChangeProperty(dpy, systray->win, netatom[NetSystemTrayOrientation], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&orient, 1); + vid = XVisualIDFromVisual(systray->visual); + XChangeProperty(dpy, systray->win, netatom[NetSystemTrayVisual], XA_VISUALID, 32, + PropModeReplace, (unsigned char *)&vid, 1); + XSetSelectionOwner(dpy, netatom[NetSystemTray], systray->win, CurrentTime); + if (XGetSelectionOwner(dpy, netatom[NetSystemTray]) == systray->win) { + sendevent(root, xatom[Manager], StructureNotifyMask, CurrentTime, + (long)netatom[NetSystemTray], (long)systray->win, 0, 0); + XSync(dpy, False); + } else { + fprintf(stderr, "dwm: unable to obtain system tray.\n"); + XDestroyWindow(dpy, systray->win); + if (systray->use_argb && systray->colormap) + XFreeColormap(dpy, systray->colormap); + free(systray); + systray = NULL; + return; + } + } + + for (w = 0, i = systray->icons; i; i = i->next) { + if (!i->tags) continue; + int iy = MAX(0, (bh - i->h) / 2); + w += systrayspacing; + i->x = (int)w; + i->y = iy; + XMoveResizeWindow(dpy, i->win, i->x, i->y, (unsigned int)i->w, (unsigned int)i->h); + XMapRaised(dpy, i->win); + w += (unsigned int)i->w; + if (i->mon != m) i->mon = m; + } + + if (w == 0) { + XUnmapWindow(dpy, systray->win); + if (updatebar) resizebarwin(m); + XSync(dpy, False); + return; + } + + w += systrayspacing; + x = (unsigned int)(m->wx + m->ww) - w; + XMoveResizeWindow(dpy, systray->win, (int)x, m->by, w, (unsigned int)bh); + wc.x = (int)x; wc.y = m->by; wc.width = (int)w; wc.height = bh; + wc.stack_mode = Above; wc.sibling = m->barwin; + XConfigureWindow(dpy, systray->win, CWX | CWY | CWWidth | CWHeight | CWSibling | CWStackMode, &wc); + XSetWindowBackground(dpy, systray->win, systray_bg_pixel()); + XClearWindow(dpy, systray->win); + XMapRaised(dpy, systray->win); + if (updatebar) resizebarwin(m); + XSync(dpy, False); +} + +static void updatesystrayicongeom(Client *i, int w, int h) { + if (i) { + int pad = anode_scale_px(2, ui_scale); + int target_h = MAX(8, bh - pad * 2); + if (w < 1) w = target_h; + if (h < 1) h = target_h; + i->h = target_h; + if (w == h) i->w = target_h; + else i->w = MAX(8, (int)((float)target_h * ((float)w / (float)h))); + applysizehints(i, &i->x, &i->y, &i->w, &i->h, False); + if (i->h > target_h || i->h < 8) { + i->w = (i->w == i->h) ? target_h : MAX(8, (int)((float)target_h * ((float)i->w / (float)(i->h ? i->h : 1)))); + i->h = target_h; + } + } +} + +static void updatesystrayiconstate(Client *i, XPropertyEvent *ev) { + long flags = 0; + int code = 0; + if (!showsystray || !i || ev->atom != xatom[XembedInfo]) + return; + if (!getxembedflags(i->win, &flags)) + return; + if ((flags & XEMBED_MAPPED) && !i->tags) { + i->tags = 1; + code = XEMBED_WINDOW_ACTIVATE; + XMapRaised(dpy, i->win); + setclientstate(i, NormalState); + } else if (!(flags & XEMBED_MAPPED) && i->tags) { + i->tags = 0; + code = XEMBED_WINDOW_DEACTIVATE; + XUnmapWindow(dpy, i->win); + setclientstate(i, WithdrawnState); + } else { + return; + } + sendevent(i->win, xatom[Xembed], StructureNotifyMask, CurrentTime, code, 0, (long)systray->win, XEMBED_EMBEDDED_VERSION_VAL); +} + +static void updatetitle(Client *c) { + if (!gettextprop(c->win, netatom[NetWMName], c->name, sizeof c->name)) + gettextprop(c->win, XA_WM_NAME, c->name, sizeof c->name); + if (c->name[0] == '\0') strcpy(c->name, broken); +} + +static void updatewindowtype(Client *c) { + Atom state = getatomprop(c, netatom[NetWMState]); + Atom wtype = getatomprop(c, netatom[NetWMWindowType]); + if (state == netatom[NetWMFullscreen]) setfullscreen(c, 1); + if (wtype == netatom[NetWMWindowTypeDialog]) c->isfloating = 1; +} + +static void updatewmhints(Client *c) { + XWMHints *wmh; + if ((wmh = XGetWMHints(dpy, c->win))) { + if (c == selmon->sel && (wmh->flags & XUrgencyHint)) { + wmh->flags &= ~XUrgencyHint; + XSetWMHints(dpy, c->win, wmh); + } else { + c->isurgent = (wmh->flags & XUrgencyHint) ? 1 : 0; + } + if (wmh->flags & InputHint) c->neverfocus = !wmh->input; + else c->neverfocus = 0; + XFree(wmh); + } +} + +static void view(const Arg *arg) { + if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags]) + return; + selmon->seltags ^= 1; + if (arg->ui & TAGMASK) + selmon->tagset[selmon->seltags] = arg->ui & TAGMASK; + focus(NULL); + arrange(selmon); +} + +static Client *wintoclient(Window w) { + Client *c; + Monitor *m; + for (m = mons; m; m = m->next) + for (c = m->clients; c; c = c->next) + if (c->win == w) return c; + return NULL; +} + +static Client *wintosystrayicon(Window w) { + Client *i = NULL; + if (!showsystray || !w || !systray) return i; + for (i = systray->icons; i && i->win != w; i = i->next) ; + return i; +} + +static Monitor *wintomon(Window w) { + int x, y; + Client *c; + Monitor *m; + if (w == root && getrootptr(&x, &y)) return recttomon(x, y, 1, 1); + for (m = mons; m; m = m->next) + if (w == m->barwin) return m; + if ((c = wintoclient(w))) return c->mon; + return selmon; +} + +static int xerror(Display *dpy, XErrorEvent *ee) { + if (ee->error_code == BadWindow || + (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch) || + (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable) || + (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable) || + (ee->request_code == X_PolySegment && ee->error_code == BadDrawable) || + (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch) || + (ee->request_code == X_GrabButton && ee->error_code == BadAccess) || + (ee->request_code == X_GrabKey && ee->error_code == BadAccess) || + (ee->request_code == X_CopyArea && ee->error_code == BadDrawable)) + return 0; + fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n", + ee->request_code, ee->error_code); + return xerrorxlib(dpy, ee); +} + +static int xerrordummy(Display *dpy, XErrorEvent *ee) { + (void)dpy; (void)ee; + return 0; +} + +static int xerrorstart(Display *dpy, XErrorEvent *ee) { + (void)dpy; (void)ee; + die("dwm: another window manager is already running"); + return -1; +} + +static void zoom(const Arg *arg) { + (void)arg; + Client *c = selmon->sel; + if (!selmon->lt[selmon->sellt]->arrange || !c || c->isfloating) return; + if (c == nexttiled(selmon->clients) && !(c = nexttiled(c->next))) return; + pop(c); +} + +int main(int argc, char *argv[]) { + if (argc == 2 && !strcmp("-v", argv[1])) { + die("dwm-" VERSION); + } else if (argc != 1) { + die("usage: dwm [-v]"); + } + if (!setlocale(LC_CTYPE, "") || !XSupportsLocale()) + fputs("warning: no locale support\n", stderr); + if (!(dpy = XOpenDisplay(NULL))) + die("dwm: cannot open display"); + checkotherwm(); + setup(); + scan(); + run(); + cleanup(); + XCloseDisplay(dpy); + if (restart_dwm) { + execvp(argv[0], argv); + } + return EXIT_SUCCESS; +} diff --git a/src/dwm/transient.c b/src/dwm/transient.c new file mode 100644 index 0000000..040adb5 --- /dev/null +++ b/src/dwm/transient.c @@ -0,0 +1,42 @@ +/* cc transient.c -o transient -lX11 */ + +#include +#include +#include +#include + +int main(void) { + Display *d; + Window r, f, t = None; + XSizeHints h; + XEvent e; + + d = XOpenDisplay(NULL); + if (!d) + exit(1); + r = DefaultRootWindow(d); + + f = XCreateSimpleWindow(d, r, 100, 100, 400, 400, 0, 0, 0); + h.min_width = h.max_width = h.min_height = h.max_height = 400; + h.flags = PMinSize | PMaxSize; + XSetWMNormalHints(d, f, &h); + XStoreName(d, f, "floating"); + XMapWindow(d, f); + + XSelectInput(d, f, ExposureMask); + while (1) { + XNextEvent(d, &e); + + if (t == None) { + sleep(5); + t = XCreateSimpleWindow(d, r, 50, 50, 100, 100, 0, 0, 0); + XSetTransientForHint(d, t, f); + XStoreName(d, t, "transient"); + XMapWindow(d, t); + XSelectInput(d, t, ExposureMask); + } + } + + XCloseDisplay(d); + exit(0); +} diff --git a/src/dwm/util.c b/src/dwm/util.c new file mode 100644 index 0000000..fe044fc --- /dev/null +++ b/src/dwm/util.c @@ -0,0 +1,35 @@ +/* See LICENSE file for copyright and license details. */ +#include +#include +#include +#include + +#include "util.h" + +void * +ecalloc(size_t nmemb, size_t size) +{ + void *p; + + if (!(p = calloc(nmemb, size))) + die("calloc:"); + return p; +} + +void +die(const char *fmt, ...) { + va_list ap; + + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + + if (fmt[0] && fmt[strlen(fmt)-1] == ':') { + fputc(' ', stderr); + perror(NULL); + } else { + fputc('\n', stderr); + } + + exit(1); +} diff --git a/src/dwm/util.h b/src/dwm/util.h new file mode 100644 index 0000000..531ab25 --- /dev/null +++ b/src/dwm/util.h @@ -0,0 +1,12 @@ +/* See LICENSE file for copyright and license details. */ + +#ifndef MAX +#define MAX(A, B) ((A) > (B) ? (A) : (B)) +#endif +#ifndef MIN +#define MIN(A, B) ((A) < (B) ? (A) : (B)) +#endif +#define BETWEEN(X, A, B) ((A) <= (X) && (X) <= (B)) + +void die(const char *fmt, ...); +void *ecalloc(size_t nmemb, size_t size); diff --git a/src/gtkTtk/generic/gtkTtk_Arrows.cpp b/src/gtkTtk/generic/gtkTtk_Arrows.cpp new file mode 100644 index 0000000..59c77f0 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Arrows.cpp @@ -0,0 +1,142 @@ +/* + * gtkTtk_Arrows.cpp + * ------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable arrow_statemap[] = +{ + { QStyle::Style_Default, TTK_STATE_DISABLED, 0 }, + { QStyle::Style_Enabled | QStyle::Style_Down, TTK_STATE_PRESSED, 0 }, + { QStyle::Style_Enabled | QStyle::Style_MouseOver, TTK_STATE_ACTIVE, 0 }, + { QStyle::Style_Enabled | QStyle::Style_Active, TTK_STATE_ALTERNATE, 0 }, + { QStyle::Style_Enabled, 0, 0 } +}; + +static int ArrowElements[] = { ARROW_UP, ARROW_DOWN, ARROW_LEFT, ARROW_RIGHT }; +typedef struct +{ + Tcl_Obj *sizeObj; + Tcl_Obj *borderObj; + Tcl_Obj *borderWidthObj; + Tcl_Obj *reliefObj; +} ArrowElement; + +static Ttk_ElementOptionSpec ArrowElementOptions[] = +{ + { "-arrowsize", TK_OPTION_PIXELS, Tk_Offset(ArrowElement,sizeObj), + DEFAULT_ARROW_SIZE }, + { "-background", TK_OPTION_BORDER, Tk_Offset(ArrowElement,borderObj), + DEFAULT_BACKGROUND }, + { "-borderwidth", TK_OPTION_PIXELS, Tk_Offset(ArrowElement,borderWidthObj), + DEFAULT_BORDERWIDTH }, + { "-relief", TK_OPTION_RELIEF, Tk_Offset(ArrowElement,reliefObj),"raised" }, + { NULL } +}; + +static void +ArrowElementGeometry( + void *clientData, void *elementRecord, + Tk_Window tkwin, int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + ArrowElement *arrow = (ArrowElement *) elementRecord; + int size = 12; + + Tk_GetPixelsFromObj(NULL, tkwin, arrow->sizeObj, &size); + *widthPtr = *heightPtr = size; +} + +static void +ArrowElementDraw(void *clientData, void *elementRecord, + Tk_Window tkwin, Drawable d, Ttk_Box b, unsigned int state) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + //ArrowElement *arrow = (ArrowElement *) elementRecord; + int direction = *(int *)clientData; + QStyle::SFlags sflags = GtkTtk_StateTableLookup(arrow_statemap ,state); + QStyle::PrimitiveElement element = QStyle::PE_ArrowUp; + //if (state == GTK_STATE_INSENSITIVE) + // sflags |= QStyle::Style_Off; + //else if (state == GTK_STATE_PRELIGHT) + // sflags |= QStyle::Style_On; + + switch(direction) + { + case ARROW_UP: element = QStyle::PE_ArrowUp; break; + case ARROW_DOWN: element = QStyle::PE_ArrowDown; break; + case ARROW_LEFT: element = QStyle::PE_ArrowLeft; break; + case ARROW_RIGHT: element = QStyle::PE_ArrowRight; break; + } + Tcl_MutexLock(>kTtkMutex); + QPixmap pixmap(b.width, b.height); + QPainter painter(&pixmap); + if ((GtkTtk_QPixmap_BackgroundTile) && + (!GtkTtk_QPixmap_BackgroundTile->isNull())) { + painter.fillRect(0, 0, b.width, b.height, QBrush(QColor(255,255,255), + *GtkTtk_QPixmap_BackgroundTile)); + } else { + painter.fillRect(0, 0, b.width, b.height, + qApp->palette().active().brush(QColorGroup::Background)); + } + qApp->style().drawPrimitive(element, &painter, + QRect(0, 0, b.width, b.height), qApp->palette().active(), sflags); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + Tcl_MutexUnlock(>kTtkMutex); +} + +static Ttk_ElementSpec ArrowElementSpec = +{ + TK_STYLE_VERSION_2, + sizeof(ArrowElement), + ArrowElementOptions, + ArrowElementGeometry, + ArrowElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + + +int GtkTtk_Init_Arrows(Tcl_Interp *interp, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "uparrow", + &ArrowElementSpec, &ArrowElements[0]); + Ttk_RegisterElement(interp, themePtr, "downarrow", + &ArrowElementSpec, &ArrowElements[1]); + Ttk_RegisterElement(interp, themePtr, "leftarrow", + &ArrowElementSpec, &ArrowElements[2]); + Ttk_RegisterElement(interp, themePtr, "rightarrow", + &ArrowElementSpec, &ArrowElements[3]); + Ttk_RegisterElement(interp, themePtr, "arrow", + &ArrowElementSpec, &ArrowElements[0]); + + /* + * Register layouts: + */ + + return TCL_OK; +}; +#endif diff --git a/src/gtkTtk/generic/gtkTtk_Background.cpp b/src/gtkTtk/generic/gtkTtk_Background.cpp new file mode 100644 index 0000000..0a9e136 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Background.cpp @@ -0,0 +1,175 @@ +/* + * gtkTtk_Background.cpp + * ----------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +#if 0 +static Ttk_StateTable background_statemap[] = +{ +}; +#endif + +typedef struct { +} BackgroundElement; + +static Ttk_ElementOptionSpec BackgroundElementOptions[] = { + {NULL} +}; + +static void BackgroundElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + // *paddingPtr = Ttk_UniformPadding(0); +} + +static void BackgroundElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_SETUP_GTK_DRAWABLE; + //GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + // GTKTTK_SECTION_ALL); + GTKTTK_DEFAULT_BACKGROUND; + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec GtkTtk_BackgroundElementSpec = { + TK_STYLE_VERSION_2, + sizeof(BackgroundElement), + BackgroundElementOptions, + BackgroundElementGeometry, + BackgroundElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Border element. + */ +#if 0 +typedef struct { + Tcl_Obj *borderWidthObj; + Tcl_Obj *reliefObj; +} BorderElement; + +static Ttk_ElementOptionSpec BorderElementOptions[] = { + { "-borderwidth", TK_OPTION_PIXELS, + Tk_Offset(BorderElement,borderWidthObj), BorderBorderWidth }, + { "-relief", TK_OPTION_RELIEF, + Tk_Offset(BorderElement,reliefObj), "flat" }, + {NULL} +}; + +static void BorderElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + //Tcl_MutexLock(>kTtkMutex); + BorderElement *border = (BorderElement*) elementRecord; + int borderWidth = 0; + Tcl_GetIntFromObj(NULL, border->borderWidthObj, &borderWidth); + *paddingPtr = Ttk_UniformPadding((short)borderWidth+2); + //Tcl_MutexUnlock(>kTtkMutex); +} + +static void BorderElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + NULL_PROXY_WIDGET(GtkTtk_QWidget_WidgetParent); + Tcl_MutexLock(>kTtkMutex); + BorderElement *border = (BorderElement*) elementRecord; + int relief = TK_RELIEF_FLAT; + int borderWidth = 0; + + Tcl_GetIntFromObj(NULL, border->borderWidthObj, &borderWidth); + Tk_GetReliefFromObj(NULL, border->reliefObj, &relief); + QStyle::SFlags sflags; + + switch (relief) { + case TK_RELIEF_GROOVE : + case TK_RELIEF_RIDGE : + case TK_RELIEF_RAISED : + sflags |= QStyle::Style_Raised; + break; + case TK_RELIEF_SUNKEN : + sflags |= QStyle::Style_Sunken; + break; + case TK_RELIEF_FLAT : + break; + case TK_RELIEF_SOLID : + break; + } + + QPixmap pixmap(b.width, b.height); + QPainter painter(&pixmap); + if (wc->GtkTtk_QPixmap_BackgroundTile && + !(wc->GtkTtk_QPixmap_BackgroundTile->isNull())) { + painter.fillRect(0, 0, b.width, b.height, + QBrush(QColor(255,255,255), + *(wc->GtkTtk_QPixmap_BackgroundTile))); + } else { + painter.fillRect(0, 0, b.width, b.height, + qApp->palette().active().background()); + } + if (borderWidth) { + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_GroupBoxFrame, &painter, + QRect(0, 0, b.width, b.height), qApp->palette().active(), sflags, + QStyleOption(borderWidth, 0)); + } + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + Tcl_MutexUnlock(>kTtkMutex); +} + +static Ttk_ElementSpec BorderElementSpec = { + TK_STYLE_VERSION_2, + sizeof(BorderElement), + BorderElementOptions, + BorderElementGeometry, + BorderElementDraw +}; +#endif + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +int GtkTtk_Init_Background(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "background", + &GtkTtk_BackgroundElementSpec, (void *) wc[0]); + //Ttk_RegisterElement(interp, themePtr, "border", + // &BorderElementSpec, NULL); + /* + * Register layouts: + */ + + return TCL_OK; +}; /* GtkTtk_Init_Background */ diff --git a/src/gtkTtk/generic/gtkTtk_Button.cpp b/src/gtkTtk/generic/gtkTtk_Button.cpp new file mode 100644 index 0000000..96cf955 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Button.cpp @@ -0,0 +1,208 @@ +/* + * gtkTtk_Button.cpp + * ------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +typedef struct { + Tcl_Obj *defaultStateObj; +} ButtonElement; + +static Ttk_ElementOptionSpec ButtonElementOptions[] = { + { (char *) "-default", TK_OPTION_ANY, + Tk_Offset(ButtonElement, defaultStateObj), (char *) "normal" }, + {NULL} +}; + +static void ButtonElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint focus_width; + gint focus_pad; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + *paddingPtr = Ttk_UniformPadding(GtkTtk_ScalePx(tkwin, PushButtonUniformPadding) + + focus_width + focus_pad); +} + +static void ButtonElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned int state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + gint width, height; + gint x, y; + gint border_width; + GtkBorder default_border = { 1, 1, 1, 1 }; + GtkBorder default_outside_border = { 0, 0, 0, 0 }; + GtkBorder *tmp_border, *tmp_outside_border; + gboolean interior_focus; + gint focus_width; + gint focus_pad; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetButton(wc); + ButtonElement *bd = (ButtonElement *) elementRecord; + GtkButton *button = (GtkButton *) widget; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_DEFAULT_BACKGROUND; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + GTKTTK_WIDGET_SET_DEFAULT(widget, bd->defaultStateObj); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + // GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, gtkShadow, NULL, + // widget, has_default ? "buttondefault" : "button", + // 0, 0, b.width, b.height); + // GtkTtk_gtk_paint_focus(style, gdkDrawable, gtkState, + // NULL, widget, "button", 0, 0, b.width, b.height); + + /* + * The following was taken from GTK+ button drawing code. + */ + border_width = ((GtkContainer*) widget)->border_width; + GtkTtk_gtk_widget_style_get(widget, + "default-border", &tmp_border, + "default-outside-border", &tmp_outside_border, + "interior-focus", &interior_focus, NULL); + if (tmp_border) { + default_border = *tmp_border; + GtkTtk_gtk_border_free(tmp_border); + } + if (tmp_outside_border) { + default_outside_border = *tmp_outside_border; + GtkTtk_gtk_border_free(tmp_outside_border); + } + + GtkTtk_gtk_widget_style_get(widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + + x = b.x + border_width; + y = b.y + border_width; + width = b.width - border_width * 2; + height = b.height - border_width * 2; + + if (has_default && button->relief == GTK_RELIEF_NORMAL) { + GtkTtk_gtk_paint_box(style, gdkDrawable, GTK_STATE_NORMAL, GTK_SHADOW_IN, + NULL, widget, "buttondefault", x, y, width, height); + x += default_border.left; + y += default_border.top; + width -= default_border.left + default_border.right; + height -= default_border.top + default_border.bottom; + } else { + x += default_outside_border.left; + y += default_outside_border.top; + width -= default_outside_border.left + default_outside_border.right; + height -= default_outside_border.top + default_outside_border.bottom; + } + + if (!interior_focus && (state & TTK_STATE_FOCUS)) { + x += focus_width + focus_pad; + y += focus_width + focus_pad; + width -= 2 * (focus_width + focus_pad); + height -= 2 * (focus_width + focus_pad); + } + + if (button->relief != GTK_RELIEF_NONE || (state & TTK_STATE_PRESSED) || + (state & TTK_STATE_ACTIVE) ) { + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "button", x, y, width, height); + } + + if (state & TTK_STATE_FOCUS) { + gint child_displacement_x; + gint child_displacement_y; + gboolean displace_focus; + + GtkTtk_gtk_widget_style_get(widget, + "child-displacement-y", &child_displacement_y, + "child-displacement-x", &child_displacement_x, + "displace-focus", &displace_focus, NULL); + + if (interior_focus) { + x += widget->style->xthickness + focus_pad; + y += widget->style->ythickness + focus_pad; + width -= 2 * (widget->style->xthickness + focus_pad); + height -= 2 * (widget->style->ythickness + focus_pad); + } else { + x -= focus_width + focus_pad; + y -= focus_width + focus_pad; + width += 2 * (focus_width + focus_pad); + height += 2 * (focus_width + focus_pad); + } + + if ((state & TTK_STATE_PRESSED) && displace_focus) { + x += child_displacement_x; + y += child_displacement_y; + } + + GtkTtk_gtk_paint_focus(style, gdkDrawable, gtkState, NULL, widget, + "button", x, y, width, height); + } + + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ButtonElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ButtonElement), + ButtonElementOptions, + ButtonElementGeometry, + ButtonElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +/* + * TTK_BEGIN_LAYOUT(ButtonLayout) + * TTK_GROUP("Button.border", TTK_FILL_BOTH, + * TTK_GROUP("Button.focus", TTK_FILL_BOTH, + * TTK_NODE("Button.label", TTK_FILL_BOTH)))) + * TTK_END_LAYOUT + */ +TTK_BEGIN_LAYOUT(ButtonLayout) + TTK_GROUP("Button.border", TTK_FILL_BOTH, + TTK_GROUP("Button.padding", TTK_FILL_BOTH, + TTK_NODE("Button.label", TTK_FILL_BOTH))) +TTK_END_LAYOUT + +int GtkTtk_Init_Button(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Button.border", + &ButtonElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "TButton", ButtonLayout); + return TCL_OK; +}; /* GtkTtk_Init_Button */ diff --git a/src/gtkTtk/generic/gtkTtk_CheckButton.cpp b/src/gtkTtk/generic/gtkTtk_CheckButton.cpp new file mode 100644 index 0000000..02679b7 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_CheckButton.cpp @@ -0,0 +1,190 @@ +/* + * gtkTtk_CheckButton.cpp + * ------------------------ + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +typedef struct { +} CheckButtonIndicatorElement; + + +static Ttk_ElementOptionSpec CheckButtonIndicatorElementOptions[] = { + {NULL} +}; + +static void CheckButtonIndicatorElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint size, spacing = CheckButtonHorizontalPadding; + gint focus_width, focus_pad; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetCheckButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, + "indicator-size", &size, + "indicator-spacing", &spacing, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + size = std::max(size, GtkTtk_ScalePx(tkwin, 14)); + spacing = std::max(spacing, GtkTtk_ScalePx(tkwin, 3)); + *widthPtr = *heightPtr = spacing*2+size+focus_width+focus_pad; + size = focus_width; + *paddingPtr = Ttk_MakePadding(*widthPtr, + size, + *widthPtr, + size); +} + +static void CheckButtonIndicatorElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + gint indicator_size, x, y; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetCheckButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + style = GtkTtk_GetGtkWindowStyle(wc->gtkWindow); + GTKTTK_DEFAULT_BACKGROUND; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_widget_style_get(widget, + "indicator-size", &indicator_size, NULL); + indicator_size = std::max(indicator_size, GtkTtk_ScalePx(tkwin, 14)); + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + x = (b.width - indicator_size) / 2; + y = (b.height - indicator_size) / 2; + GtkTtk_gtk_paint_check(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "checkbutton", x, y, indicator_size, indicator_size); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec CheckButtonIndicatorElementSpec = { + TK_STYLE_VERSION_2, + sizeof(CheckButtonIndicatorElement), + CheckButtonIndicatorElementOptions, + CheckButtonIndicatorElementGeometry, + CheckButtonIndicatorElementDraw +}; + +typedef struct { +} CheckButtonBorderElement; + + +static Ttk_ElementOptionSpec CheckButtonBorderElementOptions[] = { + {NULL} +}; + +static void CheckButtonBorderElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint focus_width; + gint focus_pad; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetCheckButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + *paddingPtr = Ttk_UniformPadding(focus_width + focus_pad); +} + +static void CheckButtonBorderElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetCheckButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_STYLE_BACKGROUND_DEFAULT; + GTKTTK_DEFAULT_BACKGROUND; + if (state & TTK_STATE_FOCUS) { + gint border_width = ((GtkContainer*) widget)->border_width; + gint focus_width; + gint focus_pad; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + GtkTtk_gtk_widget_style_get(widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + GtkTtk_gtk_paint_focus(style, gdkDrawable, gtkState, NULL, widget, + "checkbutton", b.x + border_width, b.y + border_width, + b.width - 2 * border_width, b.height - 2 * border_width); + } + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec CheckButtonBorderElementSpec = { + TK_STYLE_VERSION_2, + sizeof(CheckButtonBorderElement), + CheckButtonBorderElementOptions, + CheckButtonBorderElementGeometry, + CheckButtonBorderElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +/* + * TTK_BEGIN_LAYOUT(CheckbuttonLayout) + * TTK_GROUP("Checkbutton.border", TTK_FILL_BOTH, + * TTK_GROUP("Checkbutton.padding", TTK_FILL_BOTH, + * TTK_NODE("Checkbutton.indicator", TTK_PACK_LEFT) + * TTK_GROUP("Checkbutton.focus", TTK_PACK_LEFT | TTK_STICK_W, + * TTK_NODE("Checkbutton.label", TTK_FILL_BOTH)))) + * TTK_END_LAYOUT + */ +TTK_BEGIN_LAYOUT(CheckbuttonLayout) + TTK_GROUP("Checkbutton.border", TTK_FILL_BOTH, + TTK_GROUP("Checkbutton.padding", TTK_FILL_BOTH, + TTK_NODE("Checkbutton.indicator", TTK_PACK_LEFT) + TTK_NODE("Checkbutton.label", TTK_PACK_LEFT|TTK_STICK_W|TTK_FILL_BOTH))) +TTK_END_LAYOUT + +int GtkTtk_Init_CheckButton(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Checkbutton.border", + &CheckButtonBorderElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Checkbutton.indicator", + &CheckButtonIndicatorElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "TCheckbutton", CheckbuttonLayout); + + return TCL_OK; +}; /* GtkTtk_Init_CheckButton */ diff --git a/src/gtkTtk/generic/gtkTtk_Combobox.cpp b/src/gtkTtk/generic/gtkTtk_Combobox.cpp new file mode 100644 index 0000000..e9923fa --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Combobox.cpp @@ -0,0 +1,194 @@ +/* + * gtkTtk_Combobox.cpp + * --------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +typedef struct { +} ComboboxFieldElement; + + +static Ttk_ElementOptionSpec ComboboxFieldElementOptions[] = { + {NULL} +}; + +static void ComboboxFieldElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetComboboxEntry(wc); + GTKTTK_ENSURE_WIDGET_OK; + int xt = widget->style->xthickness; + int yt = widget->style->ythickness; + *paddingPtr = Ttk_MakePadding(xt + EntryUniformPadding, + yt + EntryUniformPadding, + xt + EntryUniformPadding, + yt + EntryUniformPadding); +} + +static void ComboboxFieldElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = NULL; + if (state & (TTK_STATE_DISABLED|TTK_STATE_READONLY)) { + widget = GtkTtk_GetCombobox(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_STYLE_BACKGROUND_DEFAULT; + GTKTTK_DEFAULT_BACKGROUND; + GTKTTK_STYLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "button", 0, 0, b.width, b.height); + } else { + widget = GtkTtk_GetComboboxEntry(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_STYLE_BACKGROUND_DEFAULT; + GTKTTK_DEFAULT_BACKGROUND; + GTKTTK_STYLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_ENTRY|GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_shadow(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "combobox", 0, 0, b.width, b.height); + } + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ComboboxFieldElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ComboboxFieldElement), + ComboboxFieldElementOptions, + ComboboxFieldElementGeometry, + ComboboxFieldElementDraw +}; + +typedef struct { +} ComboboxArrowElement; + + +static Ttk_ElementOptionSpec ComboboxArrowElementOptions[] = { + {NULL} +}; + +static void ComboboxArrowElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint size = 15; + GtkWidget *widget = GtkTtk_GetComboboxEntry(wc); + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, "arrow-size", &size, NULL); + + size = std::max(size, GtkTtk_ScalePx(tkwin, 14)); + *widthPtr = *heightPtr = size; + *paddingPtr = Ttk_UniformPadding(GtkTtk_ScalePx(tkwin, 4)); +} + +static void ComboboxArrowElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + GtkWidget *widget = NULL; + GtkWidget *arrow_widget = GtkTtk_GetArrow(wc); + gfloat arrow_scaling; + gint arrow_x; + gint arrow_y; + gint arrow_width; + gint arrow_height; + if (state & (TTK_STATE_DISABLED|TTK_STATE_READONLY)) { + widget = GtkTtk_GetCombobox(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_paint_flat_box(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "button", 0, 0, b.width, b.height); + } else { + widget = GtkTtk_GetComboboxEntry(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_ENTRY|GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_flat_box(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "combobox", 0, 0, b.width, b.height); + } + /* Draw the arrow, according to the desired scaling! */ + GtkTtk_gtk_widget_style_get(arrow_widget, "arrow-scaling", + &arrow_scaling, NULL); + if (arrow_scaling == 0.0) arrow_scaling = 1.0; + arrow_width = b.width * arrow_scaling; + arrow_height = b.height * arrow_scaling; + arrow_x = (b.width - arrow_width) / 2; + arrow_y = (b.height - arrow_height) / 2; + GtkTtk_gtk_paint_arrow(style, gdkDrawable, gtkState, GTK_SHADOW_NONE, NULL, + arrow_widget, "combo", GTK_ARROW_DOWN, TRUE, + arrow_x, arrow_y, arrow_width, arrow_height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ComboboxArrowElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ComboboxArrowElement), + ComboboxArrowElementOptions, + ComboboxArrowElementGeometry, + ComboboxArrowElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +int GtkTtk_Init_Combobox(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Combobox.field", + &ComboboxFieldElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Combobox.downarrow", + &ComboboxArrowElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + + return TCL_OK; +}; /* GtkTtk_Init_Combobox */ diff --git a/src/gtkTtk/generic/gtkTtk_Elements.h b/src/gtkTtk/generic/gtkTtk_Elements.h new file mode 100644 index 0000000..14ecdc1 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Elements.h @@ -0,0 +1,52 @@ +/* + * gtkTtk_Elements.h + * ------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ +#include "gtkTtk_TkHeaders.h" + +extern int GtkTtk_Init_Background(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Button(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_CheckButton(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_RadioButton(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Menubutton(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_ToolButton(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Entry(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Combobox(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Labelframe(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Scrollbar(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Notebook(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_TreeView(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Progress(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Scale(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Paned(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_SizeGrip(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Separator(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); +extern int GtkTtk_Init_Arrows(Tcl_Interp *interp, + GtkTtk_WidgetCache **, Ttk_Theme themePtr); diff --git a/src/gtkTtk/generic/gtkTtk_Entry.cpp b/src/gtkTtk/generic/gtkTtk_Entry.cpp new file mode 100644 index 0000000..383f9eb --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Entry.cpp @@ -0,0 +1,111 @@ +/* + * gtkTtk_Entry.cpp + * ------------------ + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable entry_statemap[] = +{ +}; +#endif + +typedef struct { +} EntryFieldElement; + + +static Ttk_ElementOptionSpec EntryFieldElementOptions[] = { + {NULL} +}; + +static void EntryFieldElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + // GtkBorder border = {0, 0, 0, 0}; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetEntry(wc); + GTKTTK_ENSURE_WIDGET_OK; + int xt = widget->style->xthickness; + int yt = widget->style->ythickness; + *paddingPtr = Ttk_MakePadding(xt + EntryUniformPadding, + yt + EntryUniformPadding, + xt + EntryUniformPadding, + yt + EntryUniformPadding); + // GtkTtk_gtk_widget_style_get(widget, "inner-border", &border, NULL); + // GtkTtk_g_object_get(widget, "inner-border", &border, NULL); + // *paddingPtr = GTKTTK_GTKBORDER_TO_PADDING(border); +} + +static void EntryFieldElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + gboolean hasFrame = TRUE; + GtkWidget *widget = GtkTtk_GetEntry(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + style = GtkTtk_GetGtkWindowStyle(wc->gtkWindow); + GTKTTK_DEFAULT_BACKGROUND; + if (hasFrame) { + GTKTTK_STYLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_ENTRY|GTKTTK_SECTION_ALL); + GtkTtk_gtk_paint_flat_box(style, gdkDrawable, gtkState, gtkShadow, NULL, widget, + "entry_bg", 0, 0, b.width, b.height); + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_paint_shadow(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "entry", 0, 0, b.width, b.height); + } + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec EntryFieldElementSpec = { + TK_STYLE_VERSION_2, + sizeof(EntryFieldElement), + EntryFieldElementOptions, + EntryFieldElementGeometry, + EntryFieldElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +int GtkTtk_Init_Entry(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Entry.field", + &EntryFieldElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + + return TCL_OK; +}; /* GtkTtk_Init_Entry */ diff --git a/src/gtkTtk/generic/gtkTtk_GtkApp.cpp b/src/gtkTtk/generic/gtkTtk_GtkApp.cpp new file mode 100644 index 0000000..75991b7 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_GtkApp.cpp @@ -0,0 +1,282 @@ +/* + * gtkTtk_GtkApp.c + * --------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#ifdef GTKTTK_ENABLE_GNOME +#include +GnomeProgram *my_app = NULL; +#endif /* GTKTTK_ENABLE_GNOME */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include +gboolean GtkTtk_GtkInitialisedFlag = FALSE; +GtkWidget *GtkTtk_GtkWindow = NULL; +static Atom GtkTtk_ResourceMgrAtom = None; +static int GtkTtk_ReloadScheduled = 0; + +static void GtkTtk_ReloadIdleProc(ClientData clientData) { + Tcl_Interp *interp = (Tcl_Interp *) clientData; + GtkTtk_ReloadScheduled = 0; + if (interp && !Tcl_InterpDeleted(interp)) { + if (Tcl_EvalEx(interp, "::ttk::theme::gtkTtk::reloadCurrentGtkTheme", + -1, TCL_EVAL_GLOBAL) != TCL_OK) { + Tcl_BackgroundError(interp); + } + } +} + +static int GtkTtk_RootEventProc(ClientData clientData, XEvent *eventPtr) { + GtkTtk_WidgetCache *wc = (GtkTtk_WidgetCache *) clientData; + if (!wc || !wc->GtkTtk_MainDisplay || !wc->GtkTtk_MainInterp) return 0; + if (eventPtr->type == PropertyNotify && + eventPtr->xproperty.window == DefaultRootWindow(wc->GtkTtk_MainDisplay)) { + if (GtkTtk_ResourceMgrAtom == None) { + GtkTtk_ResourceMgrAtom = + XInternAtom(wc->GtkTtk_MainDisplay, "RESOURCE_MANAGER", False); + } + if (eventPtr->xproperty.atom == GtkTtk_ResourceMgrAtom && + !GtkTtk_ReloadScheduled) { + GtkTtk_ReloadScheduled = 1; + Tcl_DoWhenIdle(GtkTtk_ReloadIdleProc, (ClientData) wc->GtkTtk_MainInterp); + } + } + return 0; +} + + + +/* In the following variable we store the XErrorHandler, before we install our + * own, which filters out some XErrors... */ +static int (*GtkTtk_TkXErrorHandler)(Display *displayPtr, + XErrorEvent *errorPtr); +static int (*GtkTtk_GtkXErrorHandler)(Display *displayPtr, + XErrorEvent *errorPtr); +static int GtkTtk_XErrorHandler(Display *displayPtr, XErrorEvent *errorPtr); + +static int GtkTtk_XEventHandler(ClientData clientdata, XEvent *eventPtr); + +/* + * GtkTtk_InterpDeleteProc: + * This function will be called when the interpreter gets deleted. It must free + * all allocated interp-specific memory segments. + */ +static void GtkTtk_InterpDeleteProc(ClientData clientData, Tcl_Interp *interp) { + GtkTtk_WidgetCache **wc_array = (GtkTtk_WidgetCache **) clientData; + GtkTtk_WidgetCache *wc = wc_array[0]; + Tcl_CancelIdleCall(GtkTtk_ReloadIdleProc, (ClientData) interp); + Tk_DeleteGenericHandler(&GtkTtk_RootEventProc, (ClientData) wc); + if (wc && wc->gtkWindow) { + /*This will destroy also ALL children!*/ + GtkTtk_gtk_widget_destroy(wc->gtkWindow); + } + // printf("Tk_DeleteGenericHandler: %p\n", interp); fflush(NULL); + Tk_DeleteGenericHandler(&GtkTtk_XEventHandler, (ClientData) interp); + Tcl_Free((char *) wc_array[0]); + Tcl_Free((char *) wc_array[1]); + Tcl_Free((char *) wc_array); +}; /* GtkTtk_InterpDeleteProc */ + +GtkTtk_WidgetCache **GtkTtk_CreateGtkApp(Tcl_Interp *interp) { + /* + * The first step is to initialise the gtk library. This must be done once + * in the application lifetime. + */ + Tcl_MutexLock(>kTtkMutex); + if (!GtkTtk_GtkInitialisedFlag) { +#ifdef GTKTTK_ENABLE_GNOME + gchar **remaining_args = NULL; + GOptionEntry option_entries[] = { + {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &remaining_args, + "Special option that collects any remaining arguments for us"}, + { NULL } + }; + GOptionContext *option_context; +#endif /* GTKTTK_ENABLE_GNOME */ + int argc = 1; + char **argv = GtkTtk_g_new0(char*, 2); + argv[0] = (char *) Tcl_GetNameOfExecutable(); + +#ifdef GTKTTK_INSTALL_XERROR_HANDLER + GtkTtk_TkXErrorHandler = XSetErrorHandler(GtkTtk_XErrorHandler); +#endif /* GTKTTK_INSTALL_XERROR_HANDLER */ + +#ifdef GTKTTK_ENABLE_GNOME + option_context = GtkTtk_g_option_context_new("tile-gtk"); + GtkTtk_g_option_context_add_main_entries(option_context, + option_entries, NULL); + /* We assume PACKAGE and VERSION are set to the program name and version + * number respectively. Also, assume that 'option_entries' is a global + * array of GOptionEntry structures. + */ + my_app = gnome_program_init(PACKAGE_NAME, PACKAGE_VERSION, + LIBGNOMEUI_MODULE, argc, argv, + GNOME_PARAM_GOPTION_CONTEXT, option_context, + GNOME_PARAM_NONE); + if (my_app) GtkTtk_GtkInitialisedFlag = TRUE; + if (remaining_args != NULL) { + GtkTtk_g_strfreev(remaining_args); + remaining_args = NULL; + } +#else /* GTKTTK_ENABLE_GNOME */ + GtkTtk_gtk_disable_setlocale(); + GtkTtk_GtkInitialisedFlag = GtkTtk_gtk_init_check(&argc, &argv); +#endif /* GTKTTK_ENABLE_GNOME */ + GtkTtk_g_free(argv); + if (!GtkTtk_GtkInitialisedFlag) { + Tcl_MutexUnlock(>kTtkMutex); + return NULL; + } + /* Initialise GtkTtk_GtkWindow... */ + GtkTtk_GtkWindow = GtkTtk_gtk_window_new(GTK_WINDOW_POPUP); + GtkTtk_gtk_widget_realize(GtkTtk_GtkWindow); +#ifdef GTKTTK_INSTALL_XERROR_HANDLER + /* + * GTK+ xerror handler will terminate the application. + * Just get rid of that... + */ + GtkTtk_GtkXErrorHandler = XSetErrorHandler(GtkTtk_XErrorHandler); +#endif /* GTKTTK_INSTALL_XERROR_HANDLER */ + +#ifdef GTKTTK_SYNCHRONIZE + XSynchronize(Tk_Display(Tk_MainWindow(interp)), true); +#endif /* GTKTTK_SYNCHRONIZE */ + } + Tcl_MutexUnlock(>kTtkMutex); + + /* + * Allocate the widget cache. We keep a widget cache per interpreter. + * Each cache is an array of two elements, one for each orientation. + */ + + GtkTtk_WidgetCache **wc_array = (GtkTtk_WidgetCache **) + Tcl_Alloc(sizeof(GtkTtk_WidgetCache*)*2); + wc_array[0] = (GtkTtk_WidgetCache *) + Tcl_Alloc(sizeof(GtkTtk_WidgetCache)); + wc_array[1] = (GtkTtk_WidgetCache *) + Tcl_Alloc(sizeof(GtkTtk_WidgetCache)); + Tcl_SetAssocData(interp, "gtkTtkTtk_gtk_widget_cache", + &GtkTtk_InterpDeleteProc, (ClientData) wc_array); + GtkTtk_WidgetCache *wc = wc_array[0]; + memset(wc, 0, sizeof(GtkTtk_WidgetCache)); + /* + * Initialise the widget cache. + */ + wc->GtkTtk_MainInterp = interp; + wc->GtkTtk_tkwin = Tk_MainWindow(interp); + if (wc->GtkTtk_tkwin != NULL && wc->GtkTtk_MainDisplay == None) { + Tk_MakeWindowExist(wc->GtkTtk_tkwin); + wc->GtkTtk_MainDisplay = Tk_Display(wc->GtkTtk_tkwin); + } + if (wc->GtkTtk_MainDisplay == None) { + Tcl_MutexUnlock(>kTtkMutex); + Tcl_Free((char *) wc_array[0]); + Tcl_Free((char *) wc_array[1]); + Tcl_Free((char *) wc_array); + return NULL; + } +#ifndef __WIN32__ + wc->gdkDisplay = GtkTtk_gdk_x11_lookup_xdisplay(wc->GtkTtk_MainDisplay); +#endif + if (!wc->gdkDisplay) { + wc->gdkDisplay = GtkTtk_gdk_display_get_default(); + } + wc->gtkWindow = GtkTtk_gtk_window_new(GTK_WINDOW_POPUP); + if (wc->gtkWindow) GtkTtk_gtk_widget_realize(wc->gtkWindow); + wc->protoLayout = GtkTtk_gtk_fixed_new(); + GtkTtk_gtk_container_add((GtkContainer*)(wc->gtkWindow), wc->protoLayout); + memcpy(wc_array[1], wc_array[0], sizeof(GtkTtk_WidgetCache)); + wc_array[0]->orientation = TTK_ORIENT_HORIZONTAL; + wc_array[1]->orientation = TTK_ORIENT_VERTICAL; + wc_array[0]->gtkOrientation = GTK_ORIENTATION_HORIZONTAL; + wc_array[1]->gtkOrientation = GTK_ORIENTATION_VERTICAL; + +#ifndef __WIN32__ + { + XWindowAttributes wa; + Window root = DefaultRootWindow(wc->GtkTtk_MainDisplay); + if (XGetWindowAttributes(wc->GtkTtk_MainDisplay, root, &wa)) { + XSelectInput(wc->GtkTtk_MainDisplay, root, wa.your_event_mask | PropertyChangeMask); + } + Tk_CreateGenericHandler(&GtkTtk_RootEventProc, (ClientData) wc); + } +#endif + return wc_array; +}; /* GtkTtk_CreateGtkApp */ + +void GtkTtk_DestroyGtkApp(void) { + Tcl_MutexLock(>kTtkMutex); + if (GtkTtk_GtkInitialisedFlag) { + // XSetErrorHandler(GtkTtk_TkXErrorHandler); + GtkTtk_GtkInitialisedFlag = FALSE; + } + Tcl_MutexUnlock(>kTtkMutex); +}; /* GtkTtk_DestroyGtkApp */ + +/* + * GtkTtk_XErrorHandler: + * This XError handler just prints some debug information and then calls + * Tk's XError handler... + */ +static int GtkTtk_XErrorHandler(Display *displayPtr, XErrorEvent *errorPtr) { +#ifdef GTKTTK_VERBOSE_XERROR_HANDLER + char buf[64]; + XGetErrorText (displayPtr, errorPtr->error_code, buf, 63); + printf("===============================================================\n"); + printf(" GtkTtk_XErrorHandler:\n"); + printf(" error_code = %s (%d)\n", buf, errorPtr->error_code); + printf(" request_code = %d\n", errorPtr->request_code); + printf(" minor_code = %d\n", errorPtr->minor_code); + printf("===============================================================\n"); +#endif /* GTKTTK_VERBOSE_XERROR_HANDLER */ + return GtkTtk_TkXErrorHandler(displayPtr, errorPtr); +}; /* GtkTtk_XErrorHandler */ + +static int GtkTtk_XEventHandler(ClientData clientData, XEvent *eventPtr) { + const char *tcl_callback; + int status; + if (eventPtr->type != ClientMessage) return 0; + // Atom GtkTtk_KIPC_COMM_ATOM = XInternAtom(eventPtr->xclient.display, + // "KIPC_COMM_ATOM" , false); + Atom GtkTtk_KIPC_COMM_ATOM = None; + if (eventPtr->xclient.message_type != GtkTtk_KIPC_COMM_ATOM) return 0; + /* The following data variable contains the type of the KIPC message, + * As defined in gnomelibs/gnomecore/kipc.h: + * PaletteChanged = 0 + * StyleChanged = 2 + * ToolbarStyleChanged = 6 + */ + switch (eventPtr->xclient.data.l[0]) { + case 0: /* PaletteChanged */ + tcl_callback = "tile::theme::gtkTtk::gnomePaletteChangeNotification"; + break; + case 2: /* StyleChanged */ + case 6: { /* ToolbarStyleChanged */ + tcl_callback = "tile::theme::gtkTtk::gnomeStyleChangeNotification"; + break; + } + default: { + return 0; + } + } + Tcl_Interp *interp = (Tcl_Interp *) clientData; + if (interp == NULL) return 0; + // printf("GtkTtk_XEventHandler: %p\n", interp); fflush(NULL); + /* Notify the tile engine about the change... */ + status = Tcl_Eval(interp, tcl_callback); + if (status != TCL_OK) Tcl_BackgroundError(interp); + /* Do not remove True: As many interpreters may have registered this event + * handler, allow Tk to call all of them! */ + return True; +} /* GtkTtk_XEventHandler */ diff --git a/src/gtkTtk/generic/gtkTtk_GtkHeaders.h b/src/gtkTtk/generic/gtkTtk_GtkHeaders.h new file mode 100644 index 0000000..3558dfc --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_GtkHeaders.h @@ -0,0 +1,77 @@ +/* + * gtkTtk_GtkHeaders.h + * -------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ +#ifndef _GTKTTK_GTKHEADERS +#define _GTKTTK_GTKHEADERS + +#include +#include "gtkTtk_Symbols.h" + +/* Convenience memory allocators + */ +#define GtkTtk_g_new0(struct_type, n_structs) \ + ((struct_type *) GtkTtk_g_malloc0 (((gsize) sizeof (struct_type)) * ((gsize) (n_structs)))) + +typedef struct GtkTtk_WidgetCache { + Tk_Window GtkTtk_tkwin; + Display* GtkTtk_MainDisplay; + Tcl_Interp* GtkTtk_MainInterp; + int orientation; + GtkOrientation gtkOrientation; + GdkDisplay* gdkDisplay; + GtkWidget* gtkArrow; + GtkWidget* gtkNotebook; + GtkWidget* gtkEntry; + GtkWidget* gtkHScale; + GtkWidget* gtkVScale; + GtkWidget* gtkHProgressBar; + GtkWidget* gtkVProgressBar; + GtkWidget* gtkCombobox; + GtkWidget* gtkComboboxEntry; + GtkWidget* gtkHScrollBar; + GtkWidget* gtkVScrollBar; + GtkWidget* gtkButton; + GtkWidget* gtkCheckButton; + GtkWidget* gtkSpinButton; + GtkWidget* gtkToolBar; + GtkWidget* gtkToolButton; + GtkWidget* gtkTreeView; + GtkWidget* gtkTreeHeader; + GtkWidget* gtkFrame; + GtkWidget* gtkStatusBar; + GtkWidget* gtkHPaned; + GtkWidget* gtkVPaned; + GtkWidget* gtkWindow; + GtkWidget* protoLayout; +} GtkTtk_WidgetCache; + +typedef struct { + GtkStateType state; /* State value to return if this entry matches */ + GtkShadowType shadow; /* Shadow value to return if this entry matches */ + unsigned int value; /* Value to return if this entry matches */ + unsigned int onBits; /* Bits which must be set */ + unsigned int offBits; /* Bits which must be cleared */ + unsigned int section; /* Table section to match */ +} GtkTtk_StateTable; + +#define GTKTTK_SECTION_ALL (1<<0) +#define GTKTTK_SECTION_BUTTONS (1<<1) +#define GTKTTK_SECTION_ENTRY (1<<2) +#define GTKTTK_SECTION_SCROLLBAR (1<<3) +#define GTKTTK_SECTION_STEPPERS (1<<4) +#define GTKTTK_SECTION_TROUGH (1<<5) +#define GTKTTK_SECTION_SASH (1<<6) +#define GTKTTK_SECTION_TABS (1<<7) + +#endif diff --git a/src/gtkTtk/generic/gtkTtk_Init.cpp b/src/gtkTtk/generic/gtkTtk_Init.cpp new file mode 100644 index 0000000..3ad1e74 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Init.cpp @@ -0,0 +1,909 @@ +/* + * $Id: gtkTtk_Init.cpp,v 1.15 2012/07/22 19:26:14 petasis Exp $ + * + * Copyright (C) 2004-2008 Georgios Petasis + * + * The gtkTtk theme is a Tk/Tile theme that uses Gtk/GNOME for drawing. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include + +static int GtkTtk_GtkAppCreated = 0; + +extern GtkTtk_WidgetCache **GtkTtk_CreateGtkApp(Tcl_Interp *interp); +extern void GtkTtk_DestroyGtkApp(void); + +static char initScript[] = + "namespace eval gtkTtk { };" + "namespace eval ttk::theme::gtkTtk { variable version " + PACKAGE_VERSION " };" + "tcl_findLibrary gtkTtk $ttk::theme::gtkTtk::version " + "$ttk::theme::gtkTtk::version gtkTtk.tcl GTKTTK_LIBRARY gtkTtk::library;"; +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY +static char libsInitScript[] = + "ttk::theme::gtkTtk::loadLibraries"; +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + +/* + * Exit Handler. + */ +static void GtkTtk_ExitProc(ClientData data) { + //Tcl_MutexLock(>kTtkMutex); + //GtkTtk_DestroyGtkApp(); + //Tcl_MutexUnlock(>kTtkMutex); + Tcl_MutexLock(>kTtkMutex); + // printf("GtkTtk_ExitProc: %d\n", GtkTtk_GtkAppCreated); fflush(NULL); + if (GtkTtk_GtkAppCreated < 0) { + Tcl_MutexUnlock(>kTtkMutex); + return; + } + --GtkTtk_GtkAppCreated; + if (GtkTtk_GtkAppCreated == 0) { + // printf("GtkTtk_ExitProc: %d <- GtkTtk_DestroyGtkApp();\n", + // GtkTtk_GtkAppCreated); fflush(NULL); + GtkTtk_DestroyGtkApp(); + } + Tcl_MutexUnlock(>kTtkMutex); + return; +}; /* GtkTtk_ExitProc */ + +/* + * Helper Functions + */ +int Gtkttk_ThemeName(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + // GtkTtk_WidgetCache **wc_array = (GtkTtk_WidgetCache **) clientData; + // GtkTtk_WidgetCache *wc; + // if (!wc_array || !wc_array[0]) { + // Tcl_SetResult(interp, (char *) "empty wc_array!", TCL_STATIC); + // return TCL_ERROR; + // } + // wc = wc_array[0]; + // if (!wc->gtkStyle) { + // Tcl_SetResult(interp, (char *) "empty wc->gtkStyle!", TCL_STATIC); + // return TCL_ERROR; + // } + GtkSettings *settings = NULL; + gchar *strval = NULL; + if (objc != 1) {Tcl_WrongNumArgs(interp, 1, objv, ""); return TCL_ERROR;} + + Tcl_MutexLock(>kTtkMutex); + settings = GtkTtk_gtk_settings_get_default(); + if (settings) { + GtkTtk_g_object_get(settings, "gtk-theme-name", &strval, NULL); + if (strval) { + Tcl_SetResult(interp, (char *) strval, TCL_VOLATILE); + GtkTtk_g_free(strval); + } + } + Tcl_MutexUnlock(>kTtkMutex); + return TCL_OK; +}; /* Gtkttk_ThemeName */ + +int Gtkttk_SetSettingsString(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + GtkSettings *settings = NULL; + (void) clientData; + if (objc != 3) { + Tcl_WrongNumArgs(interp, 1, objv, "property value"); + return TCL_ERROR; + } + Tcl_MutexLock(>kTtkMutex); + while (g_main_context_pending(NULL)) { + g_main_context_iteration(NULL, FALSE); + } + settings = GtkTtk_gtk_settings_get_default(); + if (settings) { + g_object_set(settings, Tcl_GetString(objv[1]), Tcl_GetString(objv[2]), NULL); + } + Tcl_MutexUnlock(>kTtkMutex); + return TCL_OK; +}; /* Gtkttk_SetSettingsString */ + +int Gtkttk_SettingsProperty(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + static const char *Methods[] = { + "integer", "boolean", "string", (char *) NULL + }; + enum methods { + INTEGER, BOOLEAN, STRING + }; + int type = STRING; + GtkSettings *settings = NULL; + gchar *s_val = NULL; + gboolean b_val = FALSE; + gint i_val = 0; + if (objc != 2 && objc != 3) { + Tcl_WrongNumArgs(interp, 1, objv, "property ?integer|boolean|string?"); + return TCL_ERROR; + } + if (objc == 3) { + if (Tcl_GetIndexFromObj(interp, objv[2], (const char **) Methods, + "method", 0, &type) != TCL_OK) { + return TCL_ERROR; + } + } + + Tcl_MutexLock(>kTtkMutex); + settings = GtkTtk_gtk_settings_get_default(); + if (settings) { + switch ((enum methods) type) { + case INTEGER: + GtkTtk_g_object_get(settings, Tcl_GetString(objv[1]), &i_val, NULL); + Tcl_SetObjResult(interp, Tcl_NewIntObj(i_val)); + break; + case BOOLEAN: + GtkTtk_g_object_get(settings, Tcl_GetString(objv[1]), &b_val, NULL); + if (b_val) Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1)); + else Tcl_SetObjResult(interp, Tcl_NewBooleanObj(0)); + break; + case STRING: + GtkTtk_g_object_get(settings, Tcl_GetString(objv[1]), &s_val, NULL); + if (s_val) { + Tcl_SetResult(interp, (char *) s_val, TCL_VOLATILE); + GtkTtk_g_free (s_val); + } + break; + } + } + Tcl_MutexUnlock(>kTtkMutex); + return TCL_OK; +}; /* Gtkttk_SettingsProperty */ + +#define GETPROPERTY_GTK_WIDGET_GET 0 +#define GETPROPERTY_GTK_WIDGET_STYLE_GET 1 +int Gtkttk_GetProperty(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[], int gtkMethod) { + static const char *Methods[] = { + "integer", "boolean", "string", (char *) NULL + }; + enum methods { + INTEGER, BOOLEAN, STRING + }; + static const char *Widgets[] = { + "GtkHScrollbar" , "GtkVScrollbar", "GtkNotebook", "GtkButton", + (char *) NULL + }; + enum widgets { + W_HSCROLLBAR, W_VSCROLLBAR, W_NOTEBOOK, W_BUTTON + }; + int type = STRING; + gchar *s_val = NULL; + gboolean b_val = FALSE; + gint i_val = 0; + GtkWidget *widget = NULL; + GtkTtk_WidgetCache **wc_array = (GtkTtk_WidgetCache **) clientData; + GtkTtk_WidgetCache *wc; + if (!wc_array || !wc_array[0]) { + Tcl_SetResult(interp, (char *) "empty wc_array!", TCL_STATIC); + return TCL_ERROR; + } + wc = wc_array[0]; + if (objc != 3 && objc != 4) { + Tcl_WrongNumArgs(interp, 1, objv, + "widget property ?integer|boolean|string?"); + return TCL_ERROR; + } + /* Get widget... */ + if (Tcl_GetIndexFromObj(interp, objv[1], (const char **) Widgets, + "widget", 0, &type) != TCL_OK) { + return TCL_ERROR; + } + switch ((enum widgets) type) { + case W_HSCROLLBAR: {widget = GtkTtk_GetHScrollBar(wc); break;} + case W_VSCROLLBAR: {widget = GtkTtk_GetVScrollBar(wc); break;} + case W_NOTEBOOK: {widget = GtkTtk_GetNotebook(wc); break;} + case W_BUTTON: {widget = GtkTtk_GetButton(wc); break;} + } + /* Get property type, which defaults to "string"... */ + if (objc == 4) { + if (Tcl_GetIndexFromObj(interp, objv[3], (const char **) Methods, + "method", 0, &type) != TCL_OK) { + return TCL_ERROR; + } + } + + Tcl_MutexLock(>kTtkMutex); + if (widget) { + switch ((enum methods) type) { + case INTEGER: + switch (gtkMethod) { + case GETPROPERTY_GTK_WIDGET_GET: + GtkTtk_gtk_object_get((GtkObject *) widget, + Tcl_GetString(objv[2]), &i_val, NULL); + break; + case GETPROPERTY_GTK_WIDGET_STYLE_GET: + GtkTtk_gtk_widget_style_get(widget, Tcl_GetString(objv[2]), + &i_val, NULL); + break; + } + Tcl_SetObjResult(interp, Tcl_NewIntObj(i_val)); + break; + case BOOLEAN: + switch (gtkMethod) { + case GETPROPERTY_GTK_WIDGET_GET: + GtkTtk_gtk_object_get((GtkObject *) widget, + Tcl_GetString(objv[2]), &b_val, NULL); + break; + case GETPROPERTY_GTK_WIDGET_STYLE_GET: + GtkTtk_gtk_widget_style_get(widget, Tcl_GetString(objv[2]), + &b_val, NULL); + break; + } + if (b_val) Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1)); + else Tcl_SetObjResult(interp, Tcl_NewBooleanObj(0)); + break; + case STRING: + switch (gtkMethod) { + case GETPROPERTY_GTK_WIDGET_GET: + GtkTtk_gtk_object_get((GtkObject *) widget, + Tcl_GetString(objv[2]), &s_val, NULL); + break; + case GETPROPERTY_GTK_WIDGET_STYLE_GET: + GtkTtk_gtk_widget_style_get(widget, Tcl_GetString(objv[2]), + &s_val, NULL); + break; + } + if (s_val) { + Tcl_SetResult(interp, (char *) s_val, TCL_VOLATILE); + GtkTtk_g_free (s_val); + } + break; + } + } + Tcl_MutexUnlock(>kTtkMutex); + return TCL_OK; +}; /* Gtkttk_GetProperty */ + +int Gtkttk_WidgetProperty(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + return Gtkttk_GetProperty(clientData, interp, objc, objv, + GETPROPERTY_GTK_WIDGET_GET); +}; /* Gtkttk_WidgetProperty */ + +int Gtkttk_WidgetStyleProperty(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + return Gtkttk_GetProperty(clientData, interp, objc, objv, + GETPROPERTY_GTK_WIDGET_STYLE_GET); +}; /* Gtkttk_WidgetStyleProperty */ + +int Gtkttk_GtkEnum(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + static const char *Methods[] = { + "GtkPositionType", (char *) NULL + }; + enum methods { + GTKPOSITIONTYPE, + }; + int index, v; + const char *n = NULL; + if (objc != 3) { + Tcl_WrongNumArgs(interp, 1, objv, "gtk_enum_type value"); + return TCL_ERROR; + } + /* Get widget... */ + if (Tcl_GetIndexFromObj(interp, objv[1], (const char **) Methods, + "gtk_enum_type", 0, &index) != TCL_OK) { + return TCL_ERROR; + } + if (Tcl_GetIntFromObj(interp, objv[2], &v) != TCL_OK) { + return TCL_ERROR; + } + switch ((enum methods) index) { + case GTKPOSITIONTYPE: { + if (v == GTK_POS_LEFT) n = "GTK_POS_LEFT"; + else if (v == GTK_POS_RIGHT) n = "GTK_POS_RIGHT"; + else if (v == GTK_POS_TOP) n = "GTK_POS_TOP"; + else if (v == GTK_POS_BOTTOM) n = "GTK_POS_BOTTOM"; + break; + } + } + if (!n) { + Tcl_SetResult(interp, (char *) "value out of range", TCL_STATIC); + return TCL_ERROR; + } + Tcl_SetResult(interp, (char *) n, TCL_STATIC); + return TCL_OK; +}; /* Gtkttk_GtkEnum */ + +int Gtkttk_GtkDirectory(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + static const char *Methods[] = { + "theme", "default_files", (char *) NULL + }; + enum methods { + THEME, DEFAULT_FILES + }; + int type; + gchar *dir = NULL, **dirs = NULL; + + if (objc != 2 && objc != 3) { + Tcl_WrongNumArgs(interp, 1, objv, "category ?value?"); + return TCL_ERROR; + } + if (Tcl_GetIndexFromObj(interp, objv[1], (const char **) Methods, + "method", 0, &type) != TCL_OK) { + return TCL_ERROR; + } + + Tcl_MutexLock(>kTtkMutex); + switch ((enum methods) type) { + case THEME: + dir = GtkTtk_gtk_rc_get_theme_dir(); + break; + case DEFAULT_FILES: + if (objc == 3) { + int mobjc; Tcl_Obj **mobjv; + if (Tcl_ListObjGetElements(interp, objv[2], &mobjc, &mobjv) != TCL_OK) { + return TCL_ERROR; + } + dirs = GtkTtk_g_new0(gchar *, mobjc+1); + for (int i = 0; i < mobjc; ++i) { + Tcl_IncrRefCount(mobjv[i]); + dirs[i] = Tcl_GetString(mobjv[i]); + } + GtkTtk_gtk_rc_set_default_files(dirs); + for (int i = 0; i < mobjc; ++i) { + Tcl_DecrRefCount(mobjv[i]); + } + GtkTtk_g_free(dirs); dirs = NULL; + } else { + dirs = GtkTtk_gtk_rc_get_default_files(); + } + break; + } + if (dir) { + Tcl_SetResult(interp, (char *) dir, TCL_VOLATILE); + GtkTtk_g_free(dir); + } + if (dirs) { + Tcl_Obj *list = Tcl_NewListObj(0, NULL); + while (*dirs) { + Tcl_ListObjAppendElement(NULL, list, Tcl_NewStringObj(*dirs, -1)); + ++dirs; + } + Tcl_SetObjResult(interp, list); + } + Tcl_MutexUnlock(>kTtkMutex); + return TCL_OK; +}; /* Gtkttk_GtkDirectory */ + +int Gtkttk_gtk_method(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + static const char *Methods[] = { + "gtk_rc_reparse_all_for_settings", "gtk_rc_reset_styles", (char *) NULL + }; + enum methods { + GTK_RC_REPARSE_ALL_FOR_SETTINGS, GTK_RC_RESET_STYLES + }; + int type; + + if (objc != 2) { + Tcl_WrongNumArgs(interp, 1, objv, "method"); return TCL_ERROR; + } + if (Tcl_GetIndexFromObj(interp, objv[1], (const char **) Methods, + "method", 0, &type) != TCL_OK) { + return TCL_ERROR; + } + + Tcl_MutexLock(>kTtkMutex); + switch ((enum methods) type) { + case GTK_RC_REPARSE_ALL_FOR_SETTINGS: + GtkTtk_gtk_rc_reparse_all_for_settings( + GtkTtk_gtk_settings_get_default(), TRUE); + break; + case GTK_RC_RESET_STYLES: + GtkTtk_gtk_rc_reset_styles(GtkTtk_gtk_settings_get_default()); + break; + } + Tcl_MutexUnlock(>kTtkMutex); + return TCL_OK; +}; /* Gtkttk_gtk_method */ + +int Gtkttk_ThemeColour(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + static const char *Methods[] = { + "fg(NORMAL)", "fg(PRELIGHT)", "fg(ACTIVE)", + "fg(SELECTED)", "fg(INSENSITIVE)", + "bg(NORMAL)", "bg(PRELIGHT)", "bg(ACTIVE)", + "bg(SELECTED)", "bg(INSENSITIVE)", + "base(NORMAL)", "base(PRELIGHT)", "base(ACTIVE)", + "base(SELECTED)", "base(INSENSITIVE)", + "text(NORMAL)", "text(PRELIGHT)", "text(ACTIVE)", + "text(SELECTED)", "text(INSENSITIVE)", + "light(NORMAL)", "light(PRELIGHT)", "light(ACTIVE)", + "light(SELECTED)", "light(INSENSITIVE)", + "mid(NORMAL)", "mid(PRELIGHT)", "mid(ACTIVE)", + "mid(SELECTED)", "mid(INSENSITIVE)", + "dark(NORMAL)", "dark(PRELIGHT)", "dark(ACTIVE)", + "dark(SELECTED)", "dark(INSENSITIVE)", + "text_aa(NORMAL)", "text_aa(PRELIGHT)", "text_aa(ACTIVE)", + "text_aa(SELECTED)", "text_aa(INSENSITIVE)", + (char *) NULL + }; + enum methods { + FG_NORMAL, FG_PRELIGHT, FG_ACTIVE, + FG_SELECTED, FG_INSENSITIVE, + BG_NORMAL , BG_PRELIGHT, BG_ACTIVE, + BG_SELECTED, BG_INSENSITIVE, + BASE_NORMAL, BASE_PRELIGHT, BASE_ACTIVE, + BASE_SELECTED, BASE_INSENSITIVE, + TEXT_NORMAL, TEXT_PRELIGHT, TEXT_ACTIVE, + TEXT_SELECTED, TEXT_INSENSITIVE, + LIGHT_NORMAL, LIGHT_PRELIGHT, LIGHT_ACTIVE, + LIGHT_SELECTED, LIGHT_INSENSITIVE, + MID_NORMAL, MID_PRELIGHT, MID_ACTIVE, + MID_SELECTED, MID_INSENSITIVE, + DARK_NORMAL, DARK_PRELIGHT, DARK_ACTIVE, + DARK_SELECTED, DARK_INSENSITIVE, + TAA_NORMAL, TAA_PRELIGHT, TAA_ACTIVE, + TAA_SELECTED, TAA_INSENSITIVE + }; + GtkTtk_WidgetCache **wc = (GtkTtk_WidgetCache **) clientData; + GdkColor colour; + gchar* colour_str = NULL; + GtkStyle *style; + int index; + if (!wc) { + Tcl_SetResult(interp, (char *) "empty wc!", TCL_STATIC); + return TCL_ERROR; + } + style = GtkTtk_GetGtkWindowStyle(wc[0]->gtkWindow); + if (!style) { + Tcl_SetResult(interp, (char *) "empty style!", TCL_STATIC); + return TCL_ERROR; + } + if (objc != 2) { + Tcl_WrongNumArgs(interp, 1, objv, "colour"); + return TCL_ERROR; + } + + if (Tcl_GetIndexFromObj(interp, objv[1], (const char **) Methods, + "method", 0, &index) == TCL_OK) { + switch ((enum methods) index) { + case FG_NORMAL: colour = style->fg[GTK_STATE_NORMAL]; break; + case FG_PRELIGHT: colour = style->fg[GTK_STATE_PRELIGHT]; break; + case FG_ACTIVE: colour = style->fg[GTK_STATE_ACTIVE]; break; + case FG_SELECTED: colour = style->fg[GTK_STATE_SELECTED]; break; + case FG_INSENSITIVE: colour = style->fg[GTK_STATE_INSENSITIVE]; break; + case BG_NORMAL: colour = style->bg[GTK_STATE_NORMAL]; break; + case BG_PRELIGHT: colour = style->bg[GTK_STATE_PRELIGHT]; break; + case BG_ACTIVE: colour = style->bg[GTK_STATE_ACTIVE]; break; + case BG_SELECTED: colour = style->bg[GTK_STATE_SELECTED]; break; + case BG_INSENSITIVE: colour = style->bg[GTK_STATE_INSENSITIVE]; break; + case BASE_NORMAL: colour = style->base[GTK_STATE_NORMAL]; break; + case BASE_PRELIGHT: colour = style->base[GTK_STATE_PRELIGHT]; break; + case BASE_ACTIVE: colour = style->base[GTK_STATE_ACTIVE]; break; + case BASE_SELECTED: colour = style->base[GTK_STATE_SELECTED]; break; + case BASE_INSENSITIVE: colour = style->base[GTK_STATE_INSENSITIVE]; break; + case TEXT_NORMAL: colour = style->text[GTK_STATE_NORMAL]; break; + case TEXT_PRELIGHT: colour = style->text[GTK_STATE_PRELIGHT]; break; + case TEXT_ACTIVE: colour = style->text[GTK_STATE_ACTIVE]; break; + case TEXT_SELECTED: colour = style->text[GTK_STATE_SELECTED]; break; + case TEXT_INSENSITIVE: colour = style->text[GTK_STATE_INSENSITIVE]; break; + case LIGHT_NORMAL: colour = style->light[GTK_STATE_NORMAL]; break; + case LIGHT_PRELIGHT: colour = style->light[GTK_STATE_PRELIGHT]; break; + case LIGHT_ACTIVE: colour = style->light[GTK_STATE_ACTIVE]; break; + case LIGHT_SELECTED: colour = style->light[GTK_STATE_SELECTED]; break; + case LIGHT_INSENSITIVE: colour = style->light[GTK_STATE_INSENSITIVE]; break; + case DARK_NORMAL: colour = style->dark[GTK_STATE_NORMAL]; break; + case DARK_PRELIGHT: colour = style->dark[GTK_STATE_PRELIGHT]; break; + case DARK_ACTIVE: colour = style->dark[GTK_STATE_ACTIVE]; break; + case DARK_SELECTED: colour = style->dark[GTK_STATE_SELECTED]; break; + case DARK_INSENSITIVE: colour = style->dark[GTK_STATE_INSENSITIVE]; break; + case MID_NORMAL: colour = style->mid[GTK_STATE_NORMAL]; break; + case MID_PRELIGHT: colour = style->mid[GTK_STATE_PRELIGHT]; break; + case MID_ACTIVE: colour = style->mid[GTK_STATE_ACTIVE]; break; + case MID_SELECTED: colour = style->mid[GTK_STATE_SELECTED]; break; + case MID_INSENSITIVE: colour = style->mid[GTK_STATE_INSENSITIVE]; break; + case TAA_NORMAL: colour = style->text_aa[GTK_STATE_NORMAL]; break; + case TAA_PRELIGHT: colour = style->text_aa[GTK_STATE_PRELIGHT]; break; + case TAA_ACTIVE: colour = style->text_aa[GTK_STATE_ACTIVE]; break; + case TAA_SELECTED: colour = style->text_aa[GTK_STATE_SELECTED]; break; + case TAA_INSENSITIVE: colour = style->text_aa[GTK_STATE_INSENSITIVE]; + } + colour_str = GtkTtk_gdk_color_to_string(&colour); + } else { + if (GtkTtk_gtk_style_lookup_color(style, Tcl_GetString(objv[1]), &colour)){ + colour_str = GtkTtk_gdk_color_to_string(&colour); + } + } + + if (colour_str) { + Tcl_SetResult(interp, (char *) colour_str, TCL_VOLATILE); + GtkTtk_g_free(colour_str); + return TCL_OK; + } + Tcl_SetResult(interp, (char *) "colour not found: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) Tcl_GetString(objv[1]), NULL); + return TCL_ERROR; +}; /* Gtkttk_ThemeColour */ + +#ifndef GTKTTK_LOAD_GTK_DYNAMICALLY +#ifndef GTK_STYLE_GET_PRIVATE +struct _GtkStylePrivate { + GSList *color_hashes; +}; +typedef struct _GtkStylePrivate GtkStylePrivate; +#define GTK_STYLE_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GTK_TYPE_STYLE, GtkStylePrivate)) +#endif +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + +int Gtkttk_ColourKeys(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + GtkTtk_WidgetCache **wc = (GtkTtk_WidgetCache **) clientData; + GtkStyle *style; + if (!wc) { + Tcl_SetResult(interp, (char *) "empty wc!", TCL_STATIC); + return TCL_ERROR; + } + style = GtkTtk_GetGtkWindowStyle(wc[0]->gtkWindow); + if (!style) { + Tcl_SetResult(interp, (char *) "empty style!", TCL_STATIC); + return TCL_ERROR; + } +#ifndef GTKTTK_LOAD_GTK_DYNAMICALLY + GtkStylePrivate *priv = GTK_STYLE_GET_PRIVATE(style); + GSList *iter; + Tcl_Obj *list = Tcl_NewListObj(0, NULL); + for (iter = priv->color_hashes; iter != NULL; iter = iter->next) { + GHashTable *hash = (GHashTable *) iter->data; + GList *keys = GtkTtk_g_hash_table_get_keys(hash); + for (; keys != NULL; keys = keys->next) { + Tcl_ListObjAppendElement(NULL, list, + Tcl_NewStringObj((char *) keys->data, -1)); + } + } + Tcl_SetObjResult(interp, list); +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + return TCL_OK; +}; /* Gtkttk_ColourKeys */ + +int Gtkttk_InitialiseLibrary(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + static const char *Methods[] = { + "required", + "gdk", "gdk_pixbuf", "gdk_pixbuf_xlib", + "glib", "gobject", + "gtk", + (char *) NULL + }; + enum methods { + L_REQUIRED, + L_GDK, L_GDK_PIXBUF, L_GDK_PIXBUF_XLIB, + L_GLIB, L_GOBJECT, + L_GTK + }; + int index, status; + if (objc != 2 && objc != 3) { + Tcl_WrongNumArgs(interp, 1, objv, "required|library ?filename?"); + return TCL_ERROR; + } + if (Tcl_GetIndexFromObj(interp, objv[1], (const char **) Methods, + "method", 0, &index) != TCL_OK) + return TCL_ERROR; + Tcl_MutexLock(>kTtkMutex); + switch ((enum methods) index) { + case L_REQUIRED: +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(1)); +#else + Tcl_SetObjResult(interp, Tcl_NewBooleanObj(0)); +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + Tcl_MutexUnlock(>kTtkMutex); + return TCL_OK; +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY + case L_GDK: + if (!GTKTTK_LAST_SYMBOL_gdk && objc > 2) { + status = GtkTtk_InitialiseSymbols_gdk(interp, objv[2]); + } + break; + case L_GDK_PIXBUF: + if (!GTKTTK_LAST_SYMBOL_gdk_pixbuf && objc > 2) { + status = GtkTtk_InitialiseSymbols_gdk_pixbuf(interp, objv[2]); + } + break; + case L_GDK_PIXBUF_XLIB: +#ifndef __WIN32__ + if (!GTKTTK_LAST_SYMBOL_gdk_pixbuf_xlib && objc > 2) { + status = GtkTtk_InitialiseSymbols_gdk_pixbuf_xlib(interp, objv[2]); + } +#endif + break; + case L_GLIB: + if (!GTKTTK_LAST_SYMBOL_glib && objc > 2) { + status = GtkTtk_InitialiseSymbols_glib(interp, objv[2]); + } + break; + case L_GOBJECT: + if (!GTKTTK_LAST_SYMBOL_gobject && objc > 2) { + status = GtkTtk_InitialiseSymbols_gobject(interp, objv[2]); + } + break; + case L_GTK: + if (!GTKTTK_LAST_SYMBOL_gtk && objc > 2) { + status = GtkTtk_InitialiseSymbols_gtk(interp, objv[2]); + } + break; +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + } + Tcl_MutexUnlock(>kTtkMutex); + return status; +}; /* Gtkttk_InitialiseLibrary */ + +int Gtkttk_SetPalette(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { +#if 0 + static const char *Methods[] = { + "-background", "-foreground", + "-buttonBackground", "-buttonForeground", + "-selectBackground", "-selectForeground", + "-windowBackground", "-windowForeground", + "-linkColor", "-visitedLinkColor", + "-contrast", + (char *) NULL + }; + enum methods { + CLR_background, CLR_foreground, + CLR_buttonBackground, CLR_buttonForeground, + CLR_selectBackground, CLR_selectForeground, + CLR_windowBackground, CLR_windowForeground, + CLR_linkColor, CLR_visitedLinkColor, + CLR_contrast + }; + int index, contrast_; + char *value; + if ((objc-1)%2) { + Tcl_WrongNumArgs(interp, 1, objv, "?-key value?"); + return TCL_ERROR; + } + Tcl_MutexLock(>kTtkMutex); + Tcl_MutexUnlock(>kTtkMutex); +#endif + return TCL_OK; +}; /* Gtkttk_SetPalette */ + +int Gtkttk_SetStyle(ClientData clientData, Tcl_Interp *interp, + int objc, Tcl_Obj *const objv[]) { + if (objc != 2) {Tcl_WrongNumArgs(interp, 1, objv, "style"); return TCL_ERROR;} + Tcl_MutexLock(>kTtkMutex); +#if 0 + GtkTtk_WidgetCache **wc_array = (GtkTtk_WidgetCache **) clientData; + GtkTtk_WidgetCache *wc = wc_array[0]; + if (qApp) { + int len; + const char* str = Tcl_GetStringFromObj(objv[1], &len); + QString style = QString::fromUtf8(str, len); + QStyle *new_style = QStyleFactory::create(style); + QStyle *todelete = NULL; + if (new_style == NULL) { + Tcl_SetResult(interp, (char *) "unknwon style: \"", TCL_STATIC); + Tcl_AppendResult(interp, str, "\"", NULL); + Tcl_MutexUnlock(>kTtkMutex); + return TCL_ERROR; + } + //qApp->setStyle(style); + /* Is this style the qApp style? */ + if (wc->GtkTtk_Style_Owner) todelete = wc->GtkTtk_Style; + +#ifdef GTKTTK_GTK_VERSION_3 + if (strcmp(qApp->style().name(), str) == 0) { + wc->GtkTtk_Style = &(qApp->style()); +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + if (qApp->style()->objectName() == style) { + wc->GtkTtk_Style = qApp->style(); +#endif /* GTKTTK_GTK_VERSION_4 */ + wc->GtkTtk_Style_Owner = false; + } else { + wc->GtkTtk_Style = QStyleFactory::create(style); + wc->GtkTtk_Style_Owner = true; + } + GtkTtk_StoreStyleNameLowers(wc); + wc->GtkTtk_QScrollBar_Widget->setStyle(wc->GtkTtk_Style); + wc->GtkTtk_QComboBox_RW_Widget->setStyle(wc->GtkTtk_Style); + wc->GtkTtk_QComboBox_RO_Widget->setStyle(wc->GtkTtk_Style); + wc->GtkTtk_QWidget_WidgetParent->setStyle(wc->GtkTtk_Style); + wc->GtkTtk_QWidget_Widget->setStyle(wc->GtkTtk_Style); +#ifdef GTKTTK_GTK_VERSION_3 + wc->GtkTtk_QWidget_Widget->polish(); +#endif /* GTKTTK_GTK_VERSION_3 */ + wc->GtkTtk_QSlider_Hor_Widget->setStyle(wc->GtkTtk_Style); + wc->GtkTtk_QSlider_Ver_Widget->setStyle(wc->GtkTtk_Style); + wc->GtkTtk_QProgressBar_Hor_Widget->setStyle(wc->GtkTtk_Style); + wc->GtkTtk_GTKabWidget_Widget->setStyle(wc->GtkTtk_Style); + wc->GtkTtk_QPixmap_BackgroundTile = +#ifdef GTKTTK_GTK_VERSION_3 + (wc->GtkTtk_QWidget_Widget)->paletteBackgroundPixmap(); +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + (wc->GtkTtk_QWidget_Widget)->palette().window().texture(); +#endif /* GTKTTK_GTK_VERSION_4 */ + wc->GtkTtk_Style->polish(wc->GtkTtk_QWidget_Widget); + if (todelete) delete todelete; +#if 0 + // Print Scrollbar statistics... +#define SC_PRINT_INFO(subcontrol) \ + wc->GtkTtk_Style->querySubControlMetrics(QStyle::CC_ScrollBar,\ + wc->GtkTtk_QScrollBar_Widget, subcontrol).x(),\ + wc->GtkTtk_Style->querySubControlMetrics(QStyle::CC_ScrollBar,\ + wc->GtkTtk_QScrollBar_Widget, subcontrol).y(),\ + wc->GtkTtk_Style->querySubControlMetrics(QStyle::CC_ScrollBar,\ + wc->GtkTtk_QScrollBar_Widget, subcontrol).width(),\ + wc->GtkTtk_Style->querySubControlMetrics(QStyle::CC_ScrollBar,\ + wc->GtkTtk_QScrollBar_Widget, subcontrol).height() + printf("SC_ScrollBarAddLine: x=%d, y=%d, w=%d, h=%d\n", SC_PRINT_INFO(QStyle::SC_ScrollBarAddLine)); + printf("SC_ScrollBarSubLine: x=%d, y=%d, w=%d, h=%d\n", SC_PRINT_INFO(QStyle::SC_ScrollBarSubLine)); + printf("SC_ScrollBarAddPage: x=%d, y=%d, w=%d, h=%d\n", SC_PRINT_INFO(QStyle::SC_ScrollBarAddPage)); + printf("SC_ScrollBarSubPage: x=%d, y=%d, w=%d, h=%d\n", SC_PRINT_INFO(QStyle::SC_ScrollBarSubPage)); + printf("SC_ScrollBarFirst: x=%d, y=%d, w=%d, h=%d\n", SC_PRINT_INFO(QStyle::SC_ScrollBarFirst)); + printf("SC_ScrollBarLast: x=%d, y=%d, w=%d, h=%d\n", SC_PRINT_INFO(QStyle::SC_ScrollBarLast)); +#endif + } + memcpy(wc_array[1], wc_array[0], sizeof(GtkTtk_WidgetCache)); + wc_array[0]->orientation = TTK_ORIENT_HORIZONTAL; + wc_array[1]->orientation = TTK_ORIENT_VERTICAL; + /* Save the name of the current theme... */ + Tcl_SetVar(interp, "ttk::theme::gtkTtk::theme", +#ifdef GTKTTK_GTK_VERSION_3 + wc->GtkTtk_Style->name(), TCL_GLOBAL_ONLY); +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + wc->GtkTtk_Style->objectName().toUtf8().data(), TCL_GLOBAL_ONLY); +#endif /* GTKTTK_GTK_VERSION_4 */ +#endif + Tcl_MutexUnlock(>kTtkMutex); + return TCL_OK; +}; /* Gtkttk_SetStyle */ + +extern "C" int DLLEXPORT +Gtkttk_Init(Tcl_Interp *interp) +{ + Ttk_Theme themePtr; + Tk_Window tkwin; + char tmpScript[1024]; + GtkTtk_WidgetCache **wc = NULL; + GtkSettings *settings = NULL; + gchar *strval = NULL; + + if (Tcl_InitStubs(interp, TCL_VERSION, 0) == NULL) + return TCL_ERROR; + if (Tk_InitStubs(interp, TK_VERSION, 0) == NULL) + return TCL_ERROR; + if (Ttk_InitStubs(interp) == NULL) + return TCL_ERROR; + + tkwin = Tk_MainWindow(interp); + if (tkwin == NULL) return TCL_ERROR; + + themePtr = Ttk_CreateTheme(interp, "gtkTtk", NULL); + if (!themePtr) return TCL_ERROR; + + Tcl_CreateObjCommand(interp, + "ttk::theme::gtkTtk::initialiseLibrary", + Gtkttk_InitialiseLibrary, (ClientData) wc, NULL); + if (Tcl_Eval(interp, initScript) != TCL_OK) { + return TCL_ERROR; + } +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY + if (!GtkTtk_GtkAppCreated) { + if (Tcl_Eval(interp, libsInitScript) != TCL_OK) { + return TCL_ERROR; + } + } +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + + /* + * Initialise Gtk: + */ + Tcl_MutexLock(>kTtkMutex); + wc = GtkTtk_CreateGtkApp(interp); + ++GtkTtk_GtkAppCreated; + + /* + * Register the various widgets... + */ + GtkTtk_Init_Background(interp, wc, themePtr); + GtkTtk_Init_Button(interp, wc, themePtr); + GtkTtk_Init_CheckButton(interp, wc, themePtr); + GtkTtk_Init_RadioButton(interp, wc, themePtr); + GtkTtk_Init_ToolButton(interp, wc, themePtr); + GtkTtk_Init_Labelframe(interp, wc, themePtr); + GtkTtk_Init_Entry(interp, wc, themePtr); + GtkTtk_Init_Menubutton(interp, wc, themePtr); + GtkTtk_Init_Scrollbar(interp, wc, themePtr); + GtkTtk_Init_Scale(interp, wc, themePtr); + GtkTtk_Init_Progress(interp, wc, themePtr); + GtkTtk_Init_SizeGrip(interp, wc, themePtr); + GtkTtk_Init_Paned(interp, wc, themePtr); + GtkTtk_Init_Notebook(interp, wc, themePtr); + GtkTtk_Init_Combobox(interp, wc, themePtr); +#if 0 + GtkTtk_Init_TreeView(interp, wc, themePtr); + //GtkTtk_Init_Separator(interp, wc, themePtr); + //GtkTtk_Init_Arrows(interp, wc, themePtr); +#endif + Tcl_CreateExitHandler(&GtkTtk_ExitProc, 0); + //Tcl_CreateThreadExitHandler(&GtkTtk_ExitProc, 0); + + /* + * Register the TileGtk package... + */ + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::gtkEnum", + Gtkttk_GtkEnum, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::setSettingsString", + Gtkttk_SetSettingsString, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::settingsProperty", + Gtkttk_SettingsProperty, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::widgetStyleProperty", + Gtkttk_WidgetStyleProperty, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::widgetProperty", + Gtkttk_WidgetProperty, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::currentThemeName", + Gtkttk_ThemeName, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::gtkDirectory", + Gtkttk_GtkDirectory, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::setStyle", + Gtkttk_SetStyle, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, "ttk::theme::gtkTtk::gtk_method", + Gtkttk_gtk_method, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, + "ttk::theme::gtkTtk::currentThemeColour", + Gtkttk_ThemeColour, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, + "ttk::theme::gtkTtk::currentThemeColourKeys", + Gtkttk_ColourKeys, (ClientData) wc, NULL); +#if 0 + Tcl_CreateObjCommand(interp, + "ttk::theme::gtkTtk::setPalette", + Gtkttk_SetPalette, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, + "ttk::theme::gtkTtk::getPixelMetric", + Gtkttk_GetPixelMetric, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, + "ttk::theme::gtkTtk::getStyleHint", + Gtkttk_GetStyleHint, (ClientData) wc, NULL); + Tcl_CreateObjCommand(interp, + "ttk::theme::gtkTtk::getSubControlMetrics", + Gtkttk_GetSubControlMetrics, (ClientData) wc, NULL); +#endif + /* Save the name of the current theme... */ + strcpy(tmpScript, "namespace eval ttk::theme::gtkTtk { variable theme "); + settings = GtkTtk_gtk_settings_get_default(); + if (settings) { + GtkTtk_g_object_get(settings, "gtk-theme-name", &strval, NULL); + strcat(tmpScript, "{"); + if (strval) { + strcat(tmpScript, strval); + GtkTtk_g_free(strval); + } + strcat(tmpScript, "}"); + } else { + strcat(tmpScript, "{}"); + } + strcat(tmpScript, " };"); + Tcl_MutexUnlock(>kTtkMutex); + + if (Tcl_Eval(interp, tmpScript) != TCL_OK) { + return TCL_ERROR; + } + if (Tcl_Eval(interp, "ttk::theme::gtkTtk::init") != TCL_OK) { + return TCL_ERROR; + } + Tcl_PkgProvide(interp, "ttk::theme::gtkTtk", PACKAGE_VERSION); + Tcl_PkgProvide(interp, PACKAGE_NAME, PACKAGE_VERSION); + return TCL_OK; +}; /* GtkTtk_Init */ + +int DLLEXPORT +GtkTtk_Finish(Tcl_Interp *interp) +{ + Tcl_MutexLock(>kTtkMutex); + if (GtkTtk_GtkAppCreated < 0) {Tcl_MutexUnlock(>kTtkMutex); return 0;} + --GtkTtk_GtkAppCreated; + if (GtkTtk_GtkAppCreated == 0) GtkTtk_DestroyGtkApp(); + Tcl_MutexUnlock(>kTtkMutex); + return 0; +}; /* GtkTtk_Finish */ diff --git a/src/gtkTtk/generic/gtkTtk_Labelframe.cpp b/src/gtkTtk/generic/gtkTtk_Labelframe.cpp new file mode 100644 index 0000000..d6d3833 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Labelframe.cpp @@ -0,0 +1,104 @@ +/* + * gtkTtk_Labelframe.cpp + * ----------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable labelframe_statemap[] = +{ +}; +#endif + +typedef struct { +} LabelframeBorderElement; + + +static Ttk_ElementOptionSpec LabelframeBorderElementOptions[] = { + {NULL} +}; + +static void LabelframeBorderElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + *paddingPtr = Ttk_UniformPadding(GtkTtk_ScalePx(tkwin, LabelframeUniformPadding)); +} + +static void LabelframeBorderElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + GtkWidget *widget = GtkTtk_GetFrame(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + // GTKTTK_ATTACH_STYLE_TO_WIDGET; + // GTKTTK_SETUP_WIDGET_SIZE(b.width, b.height); + // GTKTTK_WIDGET_SET_FOCUS(widget); + GTKTTK_DEFAULT_BACKGROUND; + // GtkTtk_gtk_paint_flat_box(style, gdkDrawable, gtkState, gtkShadow, NULL, + // widget, "frame", 0, 0, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, 0, 0); + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + GtkTtk_gtk_paint_shadow(style, gdkDrawable, gtkState, gtkShadow, NULL, widget, + "frame", 0, 0, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec LabelframeBorderElementSpec = { + TK_STYLE_VERSION_2, + sizeof(LabelframeBorderElement), + LabelframeBorderElementOptions, + LabelframeBorderElementGeometry, + LabelframeBorderElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +TTK_BEGIN_LAYOUT(LabelframeLayout) + /* Note: labelframe widget does its own layout */ + TTK_NODE("Labelframe.border", TTK_FILL_BOTH) +TTK_END_LAYOUT + +int GtkTtk_Init_Labelframe(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Labelframe.border", + &LabelframeBorderElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "TLabelframe", LabelframeLayout); + + return TCL_OK; +}; /* GtkTtk_Init_Labelframe */ diff --git a/src/gtkTtk/generic/gtkTtk_Menubutton.cpp b/src/gtkTtk/generic/gtkTtk_Menubutton.cpp new file mode 100644 index 0000000..9f00597 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Menubutton.cpp @@ -0,0 +1,175 @@ +/* + * gtkTtk_Menubutton.cpp + * ------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Pushbuttons (Tk: "Menubutton") + */ +static Ttk_StateTable menubutton_statemap[] = +{ +}; +#endif + +typedef struct { +} MenubuttonIndicatorElement; + +static Ttk_ElementOptionSpec MenubuttonIndicatorElementOptions[] = { + {NULL} +}; + +static void MenubuttonIndicatorElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint size = 15; + GtkWidget *widget = GtkTtk_GetComboboxEntry(wc); + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, "arrow-size", &size, NULL); + + size = std::max(size, GtkTtk_ScalePx(tkwin, 14)); + *widthPtr = *heightPtr = size; + *paddingPtr = Ttk_UniformPadding(GtkTtk_ScalePx(tkwin, 4)); +} + +static void MenubuttonIndicatorElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + GtkWidget *widget = GtkTtk_GetCombobox(wc); + GtkWidget *arrow_widget = GtkTtk_GetArrow(wc); + gfloat arrow_scaling; + gint arrow_x; + gint arrow_y; + gint arrow_width; + gint arrow_height; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_paint_flat_box(style, gdkDrawable, gtkState, gtkShadow, NULL, widget, + "button", 0, 0, b.width, b.height); + /* Draw the arrow, according to the desired scaling! */ + GtkTtk_gtk_widget_style_get(arrow_widget, "arrow-scaling", + &arrow_scaling, NULL); + if (arrow_scaling == 0.0) arrow_scaling = 1.0; + arrow_width = b.width * arrow_scaling; + arrow_height = b.height * arrow_scaling; + arrow_x = (b.width - arrow_width) / 2; + arrow_y = (b.height - arrow_height) / 2; + GtkTtk_gtk_paint_arrow(style, gdkDrawable, gtkState, gtkShadow, NULL, + arrow_widget, "combo", GTK_ARROW_DOWN, TRUE, + arrow_x, arrow_y, arrow_width, arrow_height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec MenubuttonIndicatorElementSpec = { + TK_STYLE_VERSION_2, + sizeof(MenubuttonIndicatorElement), + MenubuttonIndicatorElementOptions, + MenubuttonIndicatorElementGeometry, + MenubuttonIndicatorElementDraw +}; + +typedef struct { +} MenubuttonElement; + +static Ttk_ElementOptionSpec MenubuttonElementOptions[] = { + {NULL} +}; + +static void MenubuttonElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetCombobox(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_GET_WIDGET_SIZE(*widthPtr, *heightPtr); + *paddingPtr = Ttk_UniformPadding(GtkTtk_ScalePx(tkwin, PushButtonUniformPadding)); +} + +static void MenubuttonElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + GtkWidget *widget = GtkTtk_GetCombobox(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_STYLE_BACKGROUND_DEFAULT; + GTKTTK_DEFAULT_BACKGROUND; + GTKTTK_STYLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, gtkShadow, NULL, widget, + "button", 0, 0, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec MenubuttonElementSpec = { + TK_STYLE_VERSION_2, + sizeof(MenubuttonElement), + MenubuttonElementOptions, + MenubuttonElementGeometry, + MenubuttonElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +TTK_BEGIN_LAYOUT(MenubuttonLayout) + TTK_GROUP("Menubutton.border", TTK_FILL_BOTH, + TTK_GROUP("Menubutton.focus", TTK_FILL_BOTH, + TTK_NODE("Menubutton.indicator", TTK_PACK_RIGHT) + TTK_GROUP("Menubutton.padding", TTK_PACK_LEFT|TTK_EXPAND|TTK_FILL_X, + TTK_NODE("Menubutton.label", TTK_PACK_LEFT)))) +TTK_END_LAYOUT + +int GtkTtk_Init_Menubutton(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Menubutton.indicator", + &MenubuttonIndicatorElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Menubutton.border", + &MenubuttonElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "TMenubutton", MenubuttonLayout); + return TCL_OK; +}; /* GtkTtk_Init_Menubutton */ diff --git a/src/gtkTtk/generic/gtkTtk_Notebook.cpp b/src/gtkTtk/generic/gtkTtk_Notebook.cpp new file mode 100644 index 0000000..8301876 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Notebook.cpp @@ -0,0 +1,178 @@ +/* + * gtkTtk_Notebook.cpp + * --------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable notebook_statemap[] = +{ +}; +#endif + +typedef struct { +} NotebookTabElement; + + +static Ttk_ElementOptionSpec NotebookTabElementOptions[] = { + {NULL} +}; + +static void NotebookTabElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetNotebook(wc); + gint focus_width = 1, tab_curvature = 1; + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, "focus-line-width", &focus_width, + "tab-curvature", &tab_curvature, NULL); + *paddingPtr = Ttk_UniformPadding(std::max(tab_curvature + focus_width + + ((GtkNotebook *)widget)->tab_hborder, + GtkTtk_ScalePx(tkwin, 6))); + // *paddingPtr = Ttk_MakePadding(7, 6, 7, 6); +} + +#define TAB_BASE_OVERLAP_MAX 10 +static void NotebookTabElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + int height_with_overlap = b.height + GtkTtk_ScalePx(tkwin, TAB_BASE_OVERLAP_MAX); + int dh = 0; + /* GTKTTK_SETUP_GTK_DRAWABLE_PIXMAP_SIZE(b.width, height_with_overlap); */ + /* GtkWidget *widget = GtkTtk_GetNotebook(wc); */ + /* 10 Aug 2009: Notebook widgets usually have a lighter background. + * To avoid multiple background colours inside the widget, + * use a frame for drawing instead of a notebook gtk widget. */ + GtkWidget *widget = GtkTtk_GetFrame(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET_SIZE(b.width, height_with_overlap); + GtkTtk_gtk_style_apply_default_background(style, gdkDrawable, TRUE, + gtkState, NULL, 0, 0, b.width, height_with_overlap); + + if (state & TTK_STATE_SELECTED) { + dh = 1 /*widget->style->ythickness - 1*/; + } + + if (state & TTK_STATE_USER1 && state & TTK_STATE_USER2) { + /* This is the only tab in the widget! */ + } else if (state & TTK_STATE_USER1) { + /* This is the first tab! */ + } else if (state & TTK_STATE_USER2) { + /* This is the last tab! */ + } + GTKTTK_DEFAULT_BACKGROUND; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_TABS|GTKTTK_SECTION_ALL); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_extension(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, (char *) "tab", 0, 0, b.width, b.height + dh, GTK_POS_BOTTOM); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height + dh, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec NotebookTabElementSpec = { + TK_STYLE_VERSION_2, + sizeof(NotebookTabElement), + NotebookTabElementOptions, + NotebookTabElementGeometry, + NotebookTabElementDraw +}; + +typedef struct { +} NotebookClientElement; + + +static Ttk_ElementOptionSpec NotebookClientElementOptions[] = { + {NULL} +}; + +static void NotebookClientElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + int tabBarBaseHeight = 0; + int client_pad = GtkTtk_ScalePx(tkwin, NotebookClientUniformPadding); + *paddingPtr = Ttk_MakePadding(client_pad, + client_pad + tabBarBaseHeight, + client_pad, client_pad); +} + +static void NotebookClientElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + /* GtkWidget *widget = GtkTtk_GetNotebook(wc); */ + /* 10 Aug 2009: Notebook widgets usually have a lighter background. + * To avoid multiple background colours inside the widget, + * use a frame for drawing instead of a notebook gtk widget. */ + GtkWidget *widget = GtkTtk_GetFrame(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + // GtkTtk_gtk_paint_box_gap(style, gdkDrawable, + // GTK_STATE_NORMAL,GTK_SHADOW_OUT, + // NULL, widget, (char *) "notebook", 0, 0, b.width, b.height, + // GTK_POS_TOP, 0, 0); + GtkTtk_gtk_paint_box(style, gdkDrawable, GTK_STATE_NORMAL, GTK_SHADOW_OUT, + NULL, widget, (char *) "notebook", 0, 0, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec NotebookClientElementSpec = { + TK_STYLE_VERSION_2, + sizeof(NotebookClientElement), + NotebookClientElementOptions, + NotebookClientElementGeometry, + NotebookClientElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +int GtkTtk_Init_Notebook(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Notebook.tab", + &NotebookTabElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Notebook.client", + &NotebookClientElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + + return TCL_OK; +}; /* GtkTtk_Init_Notebook */ diff --git a/src/gtkTtk/generic/gtkTtk_Paned.cpp b/src/gtkTtk/generic/gtkTtk_Paned.cpp new file mode 100644 index 0000000..1b5c7a1 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Paned.cpp @@ -0,0 +1,117 @@ +/* + * gtkTtk_Paned.cpp + * --------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable paned_statemap[] = +{ +}; +#endif + +typedef struct { +} PanedSashGripElement; + +static Ttk_ElementOptionSpec PanedSashGripElementOptions[] = { + {NULL} +}; + +static void PanedSashGripElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + GtkWidget *widget = GtkTtk_GetPaned(wc); + gint size = 5; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, "handle-size", &size, NULL); + size = std::max(size, GtkTtk_ScalePx(tkwin, 7)); + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + *widthPtr = size; + } else { + *heightPtr = size; + } + *paddingPtr = Ttk_UniformPadding(PanedUniformPadding); +} + +static void PanedSashGripElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + GtkWidget *widget = GtkTtk_GetPaned(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_SASH|GTKTTK_SECTION_ALL); + GTKTTK_DEFAULT_BACKGROUND; + GtkTtk_gtk_paint_handle(style, gdkDrawable, gtkState, GTK_SHADOW_NONE, + NULL, widget, "paned", 0, 0, b.width, b.height, + wc->gtkOrientation); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +}; /* PanedSashGripElementDraw */ + +static Ttk_ElementSpec PanedSashGripElementSpec = { + TK_STYLE_VERSION_2, + sizeof(PanedSashGripElement), + PanedSashGripElementOptions, + PanedSashGripElementGeometry, + PanedSashGripElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +TTK_BEGIN_LAYOUT(HorizontalSashLayout) + TTK_GROUP("Sash.hsash", TTK_FILL_BOTH, + TTK_NODE("Sash.hgrip", TTK_FILL_BOTH)) +TTK_END_LAYOUT + +TTK_BEGIN_LAYOUT(VerticalSashLayout) + TTK_GROUP("Sash.vsash", TTK_FILL_BOTH, + TTK_NODE("Sash.vgrip", TTK_FILL_BOTH)) +TTK_END_LAYOUT + +int GtkTtk_Init_Paned(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "hgrip", + &PanedSashGripElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "vgrip", + &PanedSashGripElementSpec, (void *) wc[1]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "Horizontal.Sash", HorizontalSashLayout); + Ttk_RegisterLayout(themePtr, "Vertical.Sash", VerticalSashLayout); + + return TCL_OK; +}; /* GtkTtk_Init_Paned */ diff --git a/src/gtkTtk/generic/gtkTtk_Progress.cpp b/src/gtkTtk/generic/gtkTtk_Progress.cpp new file mode 100644 index 0000000..2e199b3 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Progress.cpp @@ -0,0 +1,199 @@ +/* + * gtkTtk_Progress.cpp + * --------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable progress_statemap[] = +{ +}; +#endif + +typedef struct { +} ProgressTroughElement; + +static Ttk_ElementOptionSpec ProgressTroughElementOptions[] = { + {NULL} +}; + +static void ProgressTroughElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + *paddingPtr = Ttk_UniformPadding(0); +} + +static void ProgressTroughElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + GtkWidget *widget = GtkTtk_GetProgressBar(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_TROUGH|GTKTTK_SECTION_ALL); + // GTKTTK_SETUP_WIDGET_SIZE(b.width, b.height); + GTKTTK_WIDGET_SET_FOCUS(widget); + GTKTTK_DEFAULT_BACKGROUND; + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, widget, + "trough", 0, 0, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ProgressTroughElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ProgressTroughElement), + ProgressTroughElementOptions, + ProgressTroughElementGeometry, + ProgressTroughElementDraw +}; + +typedef struct { + Tcl_Obj *orientObj; + Tcl_Obj *lengthObj; + Tcl_Obj *modeObj; + Tcl_Obj *maximumObj; + Tcl_Obj *valueObj; +} ProgressBarElement; + +#define TO_CHAR_STAR (char *) + +static Ttk_ElementOptionSpec ProgressBarElementOptions[] = { + { TO_CHAR_STAR "-orient", TK_OPTION_ANY, + Tk_Offset(ProgressBarElement, orientObj), TO_CHAR_STAR "horizontal"}, + { TO_CHAR_STAR "-length", TK_OPTION_PIXELS, + Tk_Offset(ProgressBarElement, lengthObj), TO_CHAR_STAR "100" }, + { TO_CHAR_STAR "-mode", TK_OPTION_STRING_TABLE, + Tk_Offset(ProgressBarElement, modeObj), TO_CHAR_STAR "determinate" }, + { TO_CHAR_STAR "-maximum", TK_OPTION_DOUBLE, + Tk_Offset(ProgressBarElement, maximumObj), TO_CHAR_STAR "100" }, + { TO_CHAR_STAR "-value", TK_OPTION_DOUBLE, + Tk_Offset(ProgressBarElement, valueObj), TO_CHAR_STAR "0.0" }, + { NULL } +}; + +static void ProgressBarElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + *widthPtr = *heightPtr = GtkTtk_ScalePx(tkwin, ProgressBarThumbSize); +} + +static void ProgressBarElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + //ProgressBarElement *pbar = (ProgressBarElement *) elementRecord; + //int width = Tk_Width(tkwin), height = Tk_Height(tkwin); + //bool determinate = true; + //double value, maximum; + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + GtkWidget *widget = GtkTtk_GetProgressBar(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_DEFAULT_BACKGROUND; + // Tcl_GetDoubleFromObj(NULL, pbar->valueObj, &value); + // Tcl_GetDoubleFromObj(NULL, pbar->maximumObj, &maximum); + // if (strncmp(Tcl_GetString(pbar->modeObj), "determinate", 10) != 0) { + // determinate = false; + // } + + // if (determinate) { + // GtkTtk_gtk_progress_bar_set_bar_style((GtkProgressBar *) widget, + // GTK_PROGRESS_DISCRETE); + // GtkTtk_gtk_progress_bar_set_fraction((GtkProgressBar *) widget, + // GtkTtk_ValueFromSlider(wc, tkwin, b)); + // } else { + // GtkTtk_gtk_progress_bar_set_bar_style((GtkProgressBar *) widget, + // GTK_PROGRESS_CONTINUOUS); + // GtkTtk_gtk_progress_bar_set_fraction((GtkProgressBar *) widget, + // GtkTtk_ValueFromSlider(wc, tkwin, b)); + // } + + GTKTTK_WIDGET_SET_FOCUS(widget); + // GTKTTK_DEFAULT_BACKGROUND; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_SCROLLBAR|GTKTTK_SECTION_ALL); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, gtkShadow, NULL, widget, + "bar", 0, 0, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ProgressBarElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ProgressBarElement), + ProgressBarElementOptions, + ProgressBarElementGeometry, + ProgressBarElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +TTK_BEGIN_LAYOUT(VerticalProgressBarLayout) + TTK_GROUP("Vertical.Progressbar.trough", TTK_FILL_BOTH, + TTK_NODE("Vertical.Progressbar.pbar", TTK_PACK_BOTTOM|TTK_FILL_X)) +TTK_END_LAYOUT + +TTK_BEGIN_LAYOUT(HorizontalProgressBarLayout) + TTK_GROUP("Horizontal.Progressbar.trough", TTK_FILL_BOTH, + TTK_NODE("Horizontal.Progressbar.pbar", TTK_PACK_LEFT|TTK_FILL_Y)) +TTK_END_LAYOUT + +int GtkTtk_Init_Progress(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Horizontal.Progressbar.trough", + &ProgressTroughElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Progressbar.trough", + &ProgressTroughElementSpec, (void *) wc[1]); + + Ttk_RegisterElement(interp, themePtr, "Horizontal.Progressbar.pbar", + &ProgressBarElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Progressbar.pbar", + &ProgressBarElementSpec, (void *) wc[1]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, + "Horizontal.TProgressbar", HorizontalProgressBarLayout); + Ttk_RegisterLayout(themePtr, + "Vertical.TProgressbar", VerticalProgressBarLayout); + + return TCL_OK; +}; /* GtkTtk_Init_Progress */ diff --git a/src/gtkTtk/generic/gtkTtk_RadioButton.cpp b/src/gtkTtk/generic/gtkTtk_RadioButton.cpp new file mode 100644 index 0000000..3f3cebb --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_RadioButton.cpp @@ -0,0 +1,192 @@ +/* + * gtkTtk_RadioButton.cpp + * ------------------------ + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +typedef struct { +} RadioButtonIndicatorElement; + + +static Ttk_ElementOptionSpec RadioButtonIndicatorElementOptions[] = { + {NULL} +}; + +static void RadioButtonIndicatorElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint size, spacing = RadioButtonHorizontalPadding; + gint focus_width, focus_pad; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetRadioButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, + "indicator-size", &size, + "indicator-spacing", &spacing, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + size = std::max(size, GtkTtk_ScalePx(tkwin, 14)); + spacing = std::max(spacing, GtkTtk_ScalePx(tkwin, 3)); + *widthPtr = size+focus_width+focus_pad; + *heightPtr = size+spacing*2+focus_pad; + size = focus_width; + *paddingPtr = Ttk_MakePadding(*heightPtr, size, *widthPtr, size); +} + +static void RadioButtonIndicatorElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + gint indicator_size, x, y; + const gint MAGIC_HEIGHT_WIDTH_COMPLEMENT = GtkTtk_ScalePx(tkwin, 40); + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetRadioButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET_SIZE(b.width+MAGIC_HEIGHT_WIDTH_COMPLEMENT, + b.height+MAGIC_HEIGHT_WIDTH_COMPLEMENT); + GTKTTK_STYLE_BACKGROUND_DEFAULT; + GTKTTK_DEFAULT_BACKGROUND_SIZE(b.width+MAGIC_HEIGHT_WIDTH_COMPLEMENT, + b.height+MAGIC_HEIGHT_WIDTH_COMPLEMENT); + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_widget_style_get(widget, + "indicator-size", &indicator_size, NULL); + indicator_size = std::max(indicator_size, GtkTtk_ScalePx(tkwin, 14)); + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + x = (b.width - indicator_size) / 2; + y = (b.height - indicator_size) / 2; + GtkTtk_gtk_paint_option(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "radiobutton", x, y, indicator_size, indicator_size); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec RadioButtonIndicatorElementSpec = { + TK_STYLE_VERSION_2, + sizeof(RadioButtonIndicatorElement), + RadioButtonIndicatorElementOptions, + RadioButtonIndicatorElementGeometry, + RadioButtonIndicatorElementDraw +}; + +typedef struct { +} RadioButtonBorderElement; + + +static Ttk_ElementOptionSpec RadioButtonBorderElementOptions[] = { + {NULL} +}; + +static void RadioButtonBorderElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint focus_width; + gint focus_pad; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetRadioButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + *paddingPtr = Ttk_UniformPadding(focus_width + focus_pad); +} + +static void RadioButtonBorderElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetRadioButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_STYLE_BACKGROUND_DEFAULT; + GTKTTK_DEFAULT_BACKGROUND; + if (state & TTK_STATE_FOCUS) { + gint border_width = ((GtkContainer*) widget)->border_width; + gint focus_width; + gint focus_pad; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS|GTKTTK_SECTION_ALL); + GtkTtk_gtk_widget_style_get(widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + GtkTtk_gtk_paint_focus(style, gdkDrawable, gtkState, NULL, widget, + "radiobutton", b.x + border_width, b.y + border_width, + b.width - 2 * border_width, b.height - 2 * border_width); + } + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec RadioButtonBorderElementSpec = { + TK_STYLE_VERSION_2, + sizeof(RadioButtonBorderElement), + RadioButtonBorderElementOptions, + RadioButtonBorderElementGeometry, + RadioButtonBorderElementDraw +}; + + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +/* + * TTK_BEGIN_LAYOUT(RadiobuttonLayout) + * TTK_GROUP("Radiobutton.border", TTK_FILL_BOTH, + * TTK_GROUP("Radiobutton.padding", TTK_FILL_BOTH, + * TTK_NODE("Radiobutton.indicator", TTK_PACK_LEFT) + * TTK_GROUP("Radiobutton.focus", TTK_PACK_LEFT, + * TTK_NODE("Radiobutton.label", TTK_FILL_BOTH)))) + * TTK_END_LAYOUT + */ +TTK_BEGIN_LAYOUT(RadiobuttonLayout) + TTK_GROUP("Radiobutton.border", TTK_FILL_BOTH, + TTK_GROUP("Radiobutton.padding", TTK_FILL_BOTH, + TTK_NODE("Radiobutton.indicator", TTK_PACK_LEFT) + TTK_NODE("Radiobutton.label", TTK_PACK_LEFT|TTK_STICK_W|TTK_FILL_BOTH))) +TTK_END_LAYOUT + +int GtkTtk_Init_RadioButton(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Radiobutton.border", + &RadioButtonBorderElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Radiobutton.indicator", + &RadioButtonIndicatorElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "TRadiobutton", RadiobuttonLayout); + + return TCL_OK; +}; /* GtkTtk_Init_RadioButton */ diff --git a/src/gtkTtk/generic/gtkTtk_Scale.cpp b/src/gtkTtk/generic/gtkTtk_Scale.cpp new file mode 100644 index 0000000..b6eabad --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Scale.cpp @@ -0,0 +1,203 @@ +/* + * gtkTtk_Scale.cpp + * --------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable scale_statemap[] = +{ +}; +#endif + +typedef struct { +} ScaleTroughElement; + +static Ttk_ElementOptionSpec ScaleTroughElementOptions[] = { + {NULL} +}; + +static void ScaleTroughElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint trough_border = 0; + GtkWidget *widget = GtkTtk_GetScale(wc); + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, "trough-border", &trough_border, NULL); + int xt = widget->style->xthickness; + int yt = widget->style->ythickness; + *paddingPtr = Ttk_MakePadding(xt + trough_border, + yt + trough_border, + xt + trough_border, + yt + trough_border); +} + +static void ScaleTroughElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetScale(wc); + gboolean trough_side_details = FALSE; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_STYLE_BACKGROUND_DEFAULT; + GTKTTK_DEFAULT_BACKGROUND; + GTKTTK_STYLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_TROUGH|GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_widget_style_get(widget, "trough-side-details", + &trough_side_details, NULL); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + if (trough_side_details) { + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, + widget, "trough-upper", 0, 0, b.width, b.height); + } else { + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, + widget, "trough", 0, 0, b.width, b.height); + } + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ScaleTroughElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ScaleTroughElement), + ScaleTroughElementOptions, + ScaleTroughElementGeometry, + ScaleTroughElementDraw +}; + +typedef struct { + Tcl_Obj *lengthObj; /* the length of the slider (if a flat style) */ + Tcl_Obj *widthObj; /* the width of the slider (height if horizontal) */ + Tcl_Obj *orientObj; /* orientation of overall slider */ +} ScaleSliderElement; + +static Ttk_ElementOptionSpec ScaleSliderElementOptions[] = { + {NULL} +}; + +static void ScaleSliderElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint slider_len = 0, slider_width = ScaleThumbMinimumLen; + GtkWidget *widget = GtkTtk_GetScale(wc); + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, + "slider-length", &slider_len, + "slider-width", &slider_width, NULL); + slider_width = std::max(slider_width, GtkTtk_ScalePx(tkwin, 14)); + slider_len = std::max(slider_len, GtkTtk_ScalePx(tkwin, 24)); + *heightPtr = *widthPtr = slider_width; + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + *heightPtr = slider_width; + *widthPtr = slider_len; + } else { + *widthPtr = slider_width; + *heightPtr = slider_len; + } + *paddingPtr = Ttk_UniformPadding(0); +} + +static void ScaleSliderElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetScale(wc); + GtkAdjustment *adj = NULL; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_STYLE_BACKGROUND_DEFAULT; + GTKTTK_DEFAULT_BACKGROUND; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_WIDGET_SET_FOCUS(widget); + adj = GtkTtk_gtk_range_get_adjustment((GtkRange *) widget); + GtkTtk_gtk_adjustment_set_value(adj, + GtkTtk_ValueFromSlider(wc, tkwin, b)); + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_SCROLLBAR|GTKTTK_SECTION_ALL); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_slider(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, + (wc->orientation == TTK_ORIENT_HORIZONTAL) ? "hscale" : "vscale", + 0, 0, b.width, b.height, wc->gtkOrientation); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ScaleSliderElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ScaleSliderElement), + ScaleSliderElementOptions, + ScaleSliderElementGeometry, + ScaleSliderElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +TTK_BEGIN_LAYOUT(VerticalScaleLayout) + TTK_GROUP("Vertical.Scale.trough", TTK_FILL_BOTH, + TTK_NODE("Vertical.Scale.slider", TTK_PACK_TOP) ) +TTK_END_LAYOUT + +TTK_BEGIN_LAYOUT(HorizontalScaleLayout) + TTK_GROUP("Horizontal.Scale.trough", TTK_FILL_BOTH, + TTK_NODE("Horizontal.Scale.slider", TTK_PACK_LEFT) ) +TTK_END_LAYOUT + +int GtkTtk_Init_Scale(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Horizontal.Scale.trough", + &ScaleTroughElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Scale.trough", + &ScaleTroughElementSpec, (void *) wc[1]); + Ttk_RegisterElement(interp, themePtr, "Horizontal.Scale.slider", + &ScaleSliderElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Scale.slider", + &ScaleSliderElementSpec, (void *) wc[1]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, + "Horizontal.TScale", HorizontalScaleLayout); + Ttk_RegisterLayout(themePtr, + "Vertical.TScale", VerticalScaleLayout); + + return TCL_OK; +}; /* GtkTtk_Init_Scale */ diff --git a/src/gtkTtk/generic/gtkTtk_Scrollbar.cpp b/src/gtkTtk/generic/gtkTtk_Scrollbar.cpp new file mode 100644 index 0000000..7e43531 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Scrollbar.cpp @@ -0,0 +1,423 @@ +/* + * gtkTtk_Scrollbar.cpp + * ------------------------ + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable scrollbar_statemap[] = +{ +}; +#endif + +typedef struct { +} ScrollbarTroughElement; + +static Ttk_ElementOptionSpec ScrollbarTroughElementOptions[] = { + {NULL} +}; + +static void ScrollbarTroughElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint trough_border = 0; + int xt = 0, yt = 0; + GtkWidget *widget = GtkTtk_GetScrollBar(wc); + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, "trough-border", &trough_border, NULL); + xt = widget->style->xthickness; + yt = widget->style->ythickness; + *paddingPtr = Ttk_MakePadding(xt + trough_border, + yt + trough_border, + xt + trough_border, + yt + trough_border); +} + +static void ScrollbarTroughElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_SETUP_GTK_DRAWABLE; + GtkWidget *widget = GtkTtk_GetScrollBar(wc); + gboolean trough_side_details = FALSE; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_TROUGH|GTKTTK_SECTION_ALL); + //GTKTTK_SETUP_WIDGET_SIZE(b.width, b.height); + GTKTTK_WIDGET_SET_FOCUS(widget); + GtkTtk_gtk_widget_style_get(widget, "trough-side-details", + &trough_side_details, NULL); + GTKTTK_DEFAULT_BACKGROUND; + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + if (trough_side_details) { + int trough_change_pos_x = b.width, trough_change_pos_y = b.height; + if (wc->gtkOrientation == GTK_ORIENTATION_HORIZONTAL) + trough_change_pos_x = b.width / 2; + else + trough_change_pos_y = b.height / 2; + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, widget, + "trough-upper", 0, 0, trough_change_pos_x, trough_change_pos_y); + if (wc->gtkOrientation == GTK_ORIENTATION_HORIZONTAL) + trough_change_pos_y = 0; + else + trough_change_pos_x = 0; + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, widget, + "trough-lower", trough_change_pos_x, trough_change_pos_y, + b.width-trough_change_pos_x, b.height-trough_change_pos_y); + } else { + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, widget, + "trough", 0, 0, b.width, b.height); + } + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ScrollbarTroughElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ScrollbarTroughElement), + ScrollbarTroughElementOptions, + ScrollbarTroughElementGeometry, + ScrollbarTroughElementDraw +}; + +typedef struct { +} ScrollbarThumbElement; + +static Ttk_ElementOptionSpec ScrollbarThumbElementOptions[] = { + {NULL} +}; + +static void ScrollbarThumbElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint slider_width = 0, slider_min = ScrollbarThumbMinimumLen; + GtkWidget *widget = GtkTtk_GetScrollBar(wc); + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, "slider-width", &slider_width, + "min-slider-length", &slider_min, NULL); + slider_width = std::max(slider_width, GtkTtk_ScalePx(tkwin, 14)); + slider_min = std::max(slider_min, GtkTtk_ScalePx(tkwin, 24)); + *heightPtr = *widthPtr = slider_min; + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + *heightPtr = slider_width; + *widthPtr = slider_min; + } else { + *widthPtr = slider_width; + *heightPtr = slider_min; + } + *paddingPtr = Ttk_UniformPadding(0); +} + +static void ScrollbarThumbElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_SETUP_GTK_DRAWABLE; + GtkWidget *widget = GtkTtk_GetScrollBar(wc); + GtkAdjustment *adj = NULL; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + // GTKTTK_SETUP_WIDGET_SIZE(b.width, b.height); + GTKTTK_WIDGET_SET_FOCUS(widget); + adj = GtkTtk_gtk_range_get_adjustment((GtkRange *) widget); + GtkTtk_gtk_adjustment_set_value(adj,GtkTtk_ValueFromSlider(wc, tkwin, b)); + GTKTTK_DEFAULT_BACKGROUND; + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, widget, + "trough", 0, 0, b.width, b.height); + + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_SCROLLBAR|GTKTTK_SECTION_ALL); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_slider(style, gdkDrawable, gtkState, gtkShadow, NULL, widget, + "slider", 0, 0, b.width, b.height, + wc->gtkOrientation); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ScrollbarThumbElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ScrollbarThumbElement), + ScrollbarThumbElementOptions, + ScrollbarThumbElementGeometry, + ScrollbarThumbElementDraw +}; + +typedef struct { +} ScrollbarUpArrowElement; + +static Ttk_ElementOptionSpec ScrollbarUpArrowElementOptions[] = { + {NULL} +}; + +static void ScrollbarUpArrowElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint stepper_size = 0, slider_width = 0; + GtkWidget *widget = GtkTtk_GetScrollBar(wc); + int xt = 0, yt = 0, trough_border = 0; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, "stepper-size", &stepper_size, + "slider-width", &slider_width, NULL); + stepper_size = std::max(stepper_size, GtkTtk_ScalePx(tkwin, 14)); + slider_width = std::max(slider_width, GtkTtk_ScalePx(tkwin, 14)); + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + *widthPtr = stepper_size; + *heightPtr = slider_width; + } else { + *widthPtr = slider_width; + *heightPtr = stepper_size; + } + xt = widget->style->xthickness; + yt = widget->style->ythickness; + *paddingPtr = Ttk_MakePadding(trough_border - xt, + trough_border - yt, + trough_border + xt, + trough_border + yt); +} + +static void ScrollbarUpArrowElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_SETUP_GTK_DRAWABLE; + GtkWidget *widget = GtkTtk_GetScrollBar(wc); + int horizontal = wc->orientation == TTK_ORIENT_HORIZONTAL; + gfloat arrow_scaling; + gint arrow_x; + gint arrow_y; + gint arrow_width; + gint arrow_height; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_STEPPERS|GTKTTK_SECTION_ALL); + // GTKTTK_SETUP_WIDGET_SIZE(b.width, b.height); + GTKTTK_WIDGET_SET_FOCUS(widget); + GTKTTK_DEFAULT_BACKGROUND; + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, + widget, horizontal ? "hscrollbar":"vscrollbar", + 0, 0, b.width, b.height); + /* Draw the arrow, according to the desired scaling! */ + GtkTtk_gtk_widget_style_get(widget, "arrow-scaling", &arrow_scaling, NULL); + if (arrow_scaling == 0.0) arrow_scaling = 1.0; + arrow_width = b.width * arrow_scaling; + arrow_height = b.height * arrow_scaling; + arrow_x = (b.width - arrow_width) / 2; + arrow_y = (b.height - arrow_height) / 2; + + GtkTtk_gtk_paint_arrow(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, horizontal ? "hscrollbar":"vscrollbar", + horizontal? GTK_ARROW_LEFT : GTK_ARROW_UP, FALSE, + arrow_x, arrow_y, arrow_width, arrow_height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ScrollbarUpArrowElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ScrollbarUpArrowElement), + ScrollbarUpArrowElementOptions, + ScrollbarUpArrowElementGeometry, + ScrollbarUpArrowElementDraw +}; + +typedef struct { +} ScrollbarDownArrowElement; + +static Ttk_ElementOptionSpec ScrollbarDownArrowElementOptions[] = { + {NULL} +}; + +static void ScrollbarDownArrowElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + ScrollbarUpArrowElementGeometry(clientData, elementRecord, tkwin, + widthPtr, heightPtr, paddingPtr); +} + +static void ScrollbarDownArrowElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GTKTTK_SETUP_GTK_DRAWABLE; + GtkWidget *widget = GtkTtk_GetScrollBar(wc); + int horizontal = wc->orientation == TTK_ORIENT_HORIZONTAL; + GTKTTK_ENSURE_WIDGET_OK; + gfloat arrow_scaling; + gint arrow_x; + gint arrow_y; + gint arrow_width; + gint arrow_height; + GTKTTK_STYLE_FROM_WIDGET; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_STEPPERS|GTKTTK_SECTION_ALL); + // GTKTTK_SETUP_WIDGET_SIZE(b.width, b.height); + GTKTTK_WIDGET_SET_FOCUS(widget); + GTKTTK_DEFAULT_BACKGROUND; + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, GTK_SHADOW_IN, NULL, + widget, horizontal ? "hscrollbar":"vscrollbar", + 0, 0, b.width, b.height); + /* Draw the arrow, according to the desired scaling! */ + GtkTtk_gtk_widget_style_get(widget, "arrow-scaling", &arrow_scaling, NULL); + if (arrow_scaling == 0.0) arrow_scaling = 1.0; + arrow_width = b.width * arrow_scaling; + arrow_height = b.height * arrow_scaling; + arrow_x = (b.width - arrow_width) / 2; + arrow_y = (b.height - arrow_height) / 2; + + GtkTtk_gtk_paint_arrow(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, horizontal ? "hscrollbar":"vscrollbar", + horizontal? GTK_ARROW_RIGHT : GTK_ARROW_DOWN, TRUE, + arrow_x, arrow_y, arrow_width, arrow_height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ScrollbarDownArrowElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ScrollbarDownArrowElement), + ScrollbarDownArrowElementOptions, + ScrollbarDownArrowElementGeometry, + ScrollbarDownArrowElementDraw +}; + +typedef struct { +} ScrollbarEmptyArrowElement; +static Ttk_ElementOptionSpec ScrollbarEmptyArrowElementOptions[] = { + {NULL} +}; + +static void ScrollbarUpSubArrowElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + ScrollbarUpArrowElementDraw(clientData, elementRecord, tkwin, d, b, state); +} + +static void ScrollbarDownSubArrowElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned stte) +{ + ScrollbarDownArrowElementDraw(clientData, elementRecord, tkwin, d, b, stte); +} + +static Ttk_ElementSpec ScrollbarUpSubArrowElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ScrollbarEmptyArrowElement), + ScrollbarEmptyArrowElementOptions, + ScrollbarUpArrowElementGeometry, + ScrollbarUpSubArrowElementDraw +}; + +static Ttk_ElementSpec ScrollbarDownSubArrowElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ScrollbarEmptyArrowElement), + ScrollbarEmptyArrowElementOptions, + ScrollbarUpArrowElementGeometry, + ScrollbarDownSubArrowElementDraw +}; + + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +// TTK_BEGIN_LAYOUT(HorizontalScrollbarLayout) +// TTK_GROUP("Horizontal.Scrollbar.trough", TTK_FILL_X, +// TTK_NODE("Horizontal.Scrollbar.leftarrow", TTK_PACK_LEFT) +// TTK_NODE("Horizontal.Scrollbar.rightarrow", TTK_PACK_RIGHT) +// TTK_NODE("Horizontal.Scrollbar.thumb", TTK_FILL_BOTH)) +// TTK_END_LAYOUT +// +// TTK_BEGIN_LAYOUT(VerticalScrollbarLayout) +// TTK_GROUP("Vertical.Scrollbar.trough", TTK_FILL_Y, +// TTK_NODE("Vertical.Scrollbar.uparrow", TTK_PACK_TOP) +// TTK_NODE("Vertical.Scrollbar.downarrow", TTK_PACK_BOTTOM) +// TTK_NODE("Vertical.Scrollbar.thumb", TTK_FILL_BOTH)) +// TTK_END_LAYOUT + +int GtkTtk_Init_Scrollbar(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Horizontal.Scrollbar.trough", + &ScrollbarTroughElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Scrollbar.trough", + &ScrollbarTroughElementSpec, (void *) wc[1]); + Ttk_RegisterElement(interp, themePtr, "Horizontal.Scrollbar.thumb", + &ScrollbarThumbElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Scrollbar.thumb", + &ScrollbarThumbElementSpec, (void *) wc[1]); + Ttk_RegisterElement(interp, themePtr, "Horizontal.Scrollbar.leftarrow", + &ScrollbarUpArrowElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Scrollbar.uparrow", + &ScrollbarUpArrowElementSpec, (void *) wc[1]); + Ttk_RegisterElement(interp, themePtr, "Horizontal.Scrollbar.rightarrow", + &ScrollbarDownArrowElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Scrollbar.downarrow", + &ScrollbarDownArrowElementSpec, (void *) wc[1]); + Ttk_RegisterElement(interp, themePtr, "Horizontal.Scrollbar.subleftarrow", + &ScrollbarUpSubArrowElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Scrollbar.subuparrow", + &ScrollbarUpSubArrowElementSpec, (void *) wc[1]); + Ttk_RegisterElement(interp, themePtr, "Horizontal.Scrollbar.subrightarrow", + &ScrollbarDownSubArrowElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Vertical.Scrollbar.subdownarrow", + &ScrollbarDownSubArrowElementSpec, (void *) wc[1]); + Ttk_RegisterElement(interp, themePtr, "Scrollbar.grip", + &ScrollbarTroughElementSpec, NULL); + + /* + * Register layouts: + */ + //Ttk_RegisterLayout(themePtr, "Vertical.TScrollbar", + // VerticalScrollbarLayout); + //Ttk_RegisterLayout(themePtr, "Horizontal.TScrollbar", + // HorizontalScrollbarLayout); + + return TCL_OK; +}; /* GtkTtk_Init_Scrollbar */ diff --git a/src/gtkTtk/generic/gtkTtk_Separator.cpp b/src/gtkTtk/generic/gtkTtk_Separator.cpp new file mode 100644 index 0000000..9bb0732 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Separator.cpp @@ -0,0 +1,178 @@ +/* + * gtkTtk_Separator.cpp + * --------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable separator_statemap[] = +{ +#ifdef GTKTTK_GTK_VERSION_3 + {QStyle::Style_Default, TTK_STATE_DISABLED, 0}, + {QStyle::Style_Enabled, 0, 0} +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + {QStyle::State_None, TTK_STATE_DISABLED, 0}, + {QStyle::State_Enabled, 0, 0} +#endif /* GTKTTK_GTK_VERSION_4 */ +}; + +typedef struct { + Tcl_Obj *orientObj; + Tcl_Obj *borderObj; +} SeparatorElement; + +#define TO_CHAR_STAR (char *) +static Ttk_ElementOptionSpec SeparatorElementOptions[] = { + { TO_CHAR_STAR "-orient", TK_OPTION_ANY, + Tk_Offset(SeparatorElement, orientObj), TO_CHAR_STAR "horizontal" }, + { TO_CHAR_STAR "-background", TK_OPTION_BORDER, + Tk_Offset(SeparatorElement,borderObj), DEFAULT_BACKGROUND }, + {NULL} +}; + +static void SeparatorElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + NULL_PROXY_ORIENTED_WIDGET(GtkTtk_QWidget_Widget); + if (orient == TTK_ORIENT_HORIZONTAL) { + *heightPtr = PMW(PM_DefaultFrameWidth, wc->GtkTtk_QWidget_Widget); + } else { + *widthPtr = PMW(PM_DefaultFrameWidth, wc->GtkTtk_QWidget_Widget); + } + *paddingPtr = Ttk_UniformPadding(0); +} + +static void SeparatorElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + NULL_PROXY_ORIENTED_WIDGET(GtkTtk_QWidget_Widget); + Tcl_MutexLock(>kTtkMutex); + QPixmap pixmap(b.width, b.height); + QPainter painter(&pixmap); + GTKTTK_PAINT_BACKGROUND(b.width, b.height); +#ifdef GTKTTK_GTK_VERSION_3 + QStyle::SFlags sflags = GtkTtk_StateTableLookup(separator_statemap, state); + if (orient == TTK_ORIENT_HORIZONTAL) { + sflags |= QStyle::Style_Horizontal; + } + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_Separator, &painter, + QRect(0, 0, b.width, b.height), qApp->palette().active(), sflags); +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + QStyleOption option; + option.state |= + (QStyle::StateFlag) GtkTtk_StateTableLookup(separator_statemap, state); + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_Q3Separator, &option, + &painter); +#endif /* GTKTTK_GTK_VERSION_4 */ + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + Tcl_MutexUnlock(>kTtkMutex); +}; /* SeparatorElementDraw */ + +static void GeneralSeparatorElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GtkTtk_WidgetCache **wc = (GtkTtk_WidgetCache **) clientData; + if (wc == NULL) return; + SeparatorElement *separator = (SeparatorElement *) elementRecord; + int orient; + Ttk_GetOrientFromObj(NULL, separator->orientObj, &orient); + switch (orient) { + case TTK_ORIENT_HORIZONTAL: + SeparatorElementGeometry((void *) wc[0], elementRecord, tkwin, + widthPtr, heightPtr, paddingPtr); + break; + case TTK_ORIENT_VERTICAL: + SeparatorElementGeometry((void *) wc[1], elementRecord, tkwin, + widthPtr, heightPtr, paddingPtr); + break; + } +} + +static void GeneralSeparatorElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GtkTtk_WidgetCache **wc = (GtkTtk_WidgetCache **) clientData; + if (wc == NULL) return; + SeparatorElement *separator = (SeparatorElement *) elementRecord; + int orient; + Ttk_GetOrientFromObj(NULL, separator->orientObj, &orient); + switch (orient) { + case TTK_ORIENT_HORIZONTAL: + SeparatorElementDraw((void *) wc[0], elementRecord, tkwin, + d, b, state); + break; + case TTK_ORIENT_VERTICAL: + SeparatorElementDraw((void *) wc[1], elementRecord, tkwin, + d, b, state); + break; + } +}; /* GeneralSeparatorElementDraw */ + +static Ttk_ElementSpec SeparatorElementSpec = { + TK_STYLE_VERSION_2, + sizeof(SeparatorElement), + SeparatorElementOptions, + SeparatorElementGeometry, + SeparatorElementDraw +}; + +static Ttk_ElementSpec GeneralSeparatorElementSpec = { + TK_STYLE_VERSION_2, + sizeof(SeparatorElement), + SeparatorElementOptions, + GeneralSeparatorElementGeometry, + GeneralSeparatorElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +TTK_BEGIN_LAYOUT(SeparatorLayout) + TTK_NODE("Separator.separator", TTK_FILL_BOTH) +TTK_END_LAYOUT + +int GtkTtk_Init_Separator(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "separator", + &GeneralSeparatorElementSpec, (void *) wc); + Ttk_RegisterElement(interp, themePtr, "hseparator", + &SeparatorElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "vseparator", + &SeparatorElementSpec, (void *) wc[1]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "TSeparator", SeparatorLayout); + + return TCL_OK; +}; /* GtkTtk_Init_Separator */ diff --git a/src/gtkTtk/generic/gtkTtk_SizeGrip.cpp b/src/gtkTtk/generic/gtkTtk_SizeGrip.cpp new file mode 100644 index 0000000..615df46 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_SizeGrip.cpp @@ -0,0 +1,103 @@ +/* + * gtkTtk_SizeGrip.cpp + * --------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#if 0 +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable size_grip_statemap[] = +{ +}; +#endif + +typedef struct { +} SizeGripElement; + +static Ttk_ElementOptionSpec SizeGripElementOptions[] = { + {NULL} +}; + +static void SizeGripElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetStatusBar(wc); + *widthPtr = GtkTtk_ScalePx(tkwin, 18); + *heightPtr = GtkTtk_ScalePx(tkwin, 18); + GTKTTK_ENSURE_WIDGET_OK; + *paddingPtr = Ttk_MakePadding(0, 0, widget->style->xthickness, + widget->style->ythickness); +} + +static void SizeGripElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + /* GTKTTK_SETUP_GTK_DRAWABLE; */ + GtkWidget *widget = wc->gtkWindow; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + // GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + // GTKTTK_SECTION_ALL); + GTKTTK_DEFAULT_BACKGROUND; + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + GtkTtk_gtk_paint_resize_grip(style, gdkDrawable, GTK_STATE_NORMAL, NULL, widget, + "window", GDK_WINDOW_EDGE_SOUTH_EAST, 0, 0, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +}; /* SizeGripElementDraw */ + +static Ttk_ElementSpec SizeGripElementSpec = { + TK_STYLE_VERSION_2, + sizeof(SizeGripElement), + SizeGripElementOptions, + SizeGripElementGeometry, + SizeGripElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +TTK_BEGIN_LAYOUT(SizegripLayout) + TTK_NODE("Sizegrip.sizegrip", TTK_PACK_BOTTOM|TTK_STICK_S|TTK_STICK_E) +TTK_END_LAYOUT + +int GtkTtk_Init_SizeGrip(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "sizegrip", + &SizeGripElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "TSizegrip", SizegripLayout); + + return TCL_OK; +}; /* GtkTtk_Init_SizeGrip */ diff --git a/src/gtkTtk/generic/gtkTtk_Symbols.cpp b/src/gtkTtk/generic/gtkTtk_Symbols.cpp new file mode 100644 index 0000000..e2dc20d --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Symbols.cpp @@ -0,0 +1,804 @@ +/* + * gtkTtk_Symbols.cpp + * ------------------------ + * + * This file is part of the GtkTtk package, a ttk based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2012 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ +/* THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT! */ +#include "gtkTtk_Symbols.h" +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY +#if (TCL_MAJOR_VERSION >= 8) && (TCL_MINOR_VERSION >= 6) +#define LOAD_SYMBOLS_WITH_TCL +#endif + +#ifndef LOAD_SYMBOLS_WITH_TCL +#include +#endif + +Ptr_g_free GtkTtk_g_free = 0; +Ptr_g_hash_table_get_keys GtkTtk_g_hash_table_get_keys = 0; +Ptr_g_malloc GtkTtk_g_malloc = 0; +Ptr_g_malloc0 GtkTtk_g_malloc0 = 0; +Ptr_g_object_get GtkTtk_g_object_get = 0; +Ptr_g_object_unref GtkTtk_g_object_unref = 0; +Ptr_g_option_context_add_main_entries GtkTtk_g_option_context_add_main_entries = 0; +Ptr_g_option_context_new GtkTtk_g_option_context_new = 0; +Ptr_g_strfreev GtkTtk_g_strfreev = 0; +Ptr_gdk_color_to_string GtkTtk_gdk_color_to_string = 0; +Ptr_gdk_display_get_default GtkTtk_gdk_display_get_default = 0; +Ptr_gdk_display_get_screen GtkTtk_gdk_display_get_screen = 0; +Ptr_gdk_drawable_set_colormap GtkTtk_gdk_drawable_set_colormap = 0; +Ptr_gdk_gc_new GtkTtk_gdk_gc_new = 0; +Ptr_gdk_pixbuf_get_from_drawable GtkTtk_gdk_pixbuf_get_from_drawable = 0; +Ptr_gdk_pixbuf_new GtkTtk_gdk_pixbuf_new = 0; +Ptr_gdk_pixbuf_unref GtkTtk_gdk_pixbuf_unref = 0; +Ptr_gdk_pixbuf_xlib_render_to_drawable GtkTtk_gdk_pixbuf_xlib_render_to_drawable = 0; +Ptr_gdk_pixmap_foreign_new_for_screen GtkTtk_gdk_pixmap_foreign_new_for_screen = 0; +Ptr_gdk_pixmap_new GtkTtk_gdk_pixmap_new = 0; +Ptr_gdk_x11_colormap_foreign_new GtkTtk_gdk_x11_colormap_foreign_new = 0; +Ptr_gdk_x11_lookup_xdisplay GtkTtk_gdk_x11_lookup_xdisplay = 0; +Ptr_gdk_x11_screen_lookup_visual GtkTtk_gdk_x11_screen_lookup_visual = 0; +Ptr_gtk_adjustment_new GtkTtk_gtk_adjustment_new = 0; +Ptr_gtk_adjustment_set_value GtkTtk_gtk_adjustment_set_value = 0; +Ptr_gtk_arrow_new GtkTtk_gtk_arrow_new = 0; +Ptr_gtk_border_free GtkTtk_gtk_border_free = 0; +Ptr_gtk_button_get_relief GtkTtk_gtk_button_get_relief = 0; +Ptr_gtk_button_new GtkTtk_gtk_button_new = 0; +Ptr_gtk_button_set_relief GtkTtk_gtk_button_set_relief = 0; +Ptr_gtk_check_button_new GtkTtk_gtk_check_button_new = 0; +Ptr_gtk_combo_box_entry_new GtkTtk_gtk_combo_box_entry_new = 0; +Ptr_gtk_combo_box_new GtkTtk_gtk_combo_box_new = 0; +Ptr_gtk_container_add GtkTtk_gtk_container_add = 0; +Ptr_gtk_disable_setlocale GtkTtk_gtk_disable_setlocale = 0; +Ptr_gtk_entry_new GtkTtk_gtk_entry_new = 0; +Ptr_gtk_fixed_new GtkTtk_gtk_fixed_new = 0; +Ptr_gtk_frame_new GtkTtk_gtk_frame_new = 0; +Ptr_gtk_hpaned_new GtkTtk_gtk_hpaned_new = 0; +Ptr_gtk_hscale_new_with_range GtkTtk_gtk_hscale_new_with_range = 0; +Ptr_gtk_hscrollbar_new GtkTtk_gtk_hscrollbar_new = 0; +Ptr_gtk_init_check GtkTtk_gtk_init_check = 0; +Ptr_gtk_notebook_new GtkTtk_gtk_notebook_new = 0; +Ptr_gtk_object_get GtkTtk_gtk_object_get = 0; +Ptr_gtk_paint_arrow GtkTtk_gtk_paint_arrow = 0; +Ptr_gtk_paint_box GtkTtk_gtk_paint_box = 0; +Ptr_gtk_paint_box_gap GtkTtk_gtk_paint_box_gap = 0; +Ptr_gtk_paint_check GtkTtk_gtk_paint_check = 0; +Ptr_gtk_paint_extension GtkTtk_gtk_paint_extension = 0; +Ptr_gtk_paint_flat_box GtkTtk_gtk_paint_flat_box = 0; +Ptr_gtk_paint_focus GtkTtk_gtk_paint_focus = 0; +Ptr_gtk_paint_handle GtkTtk_gtk_paint_handle = 0; +Ptr_gtk_paint_option GtkTtk_gtk_paint_option = 0; +Ptr_gtk_paint_resize_grip GtkTtk_gtk_paint_resize_grip = 0; +Ptr_gtk_paint_shadow GtkTtk_gtk_paint_shadow = 0; +Ptr_gtk_paint_slider GtkTtk_gtk_paint_slider = 0; +Ptr_gtk_progress_bar_new GtkTtk_gtk_progress_bar_new = 0; +Ptr_gtk_progress_bar_set_bar_style GtkTtk_gtk_progress_bar_set_bar_style = 0; +Ptr_gtk_progress_bar_set_fraction GtkTtk_gtk_progress_bar_set_fraction = 0; +Ptr_gtk_progress_bar_set_orientation GtkTtk_gtk_progress_bar_set_orientation = 0; +Ptr_gtk_range_get_adjustment GtkTtk_gtk_range_get_adjustment = 0; +Ptr_gtk_rc_get_default_files GtkTtk_gtk_rc_get_default_files = 0; +Ptr_gtk_rc_get_style GtkTtk_gtk_rc_get_style = 0; +Ptr_gtk_rc_get_theme_dir GtkTtk_gtk_rc_get_theme_dir = 0; +Ptr_gtk_rc_reparse_all_for_settings GtkTtk_gtk_rc_reparse_all_for_settings = 0; +Ptr_gtk_rc_reset_styles GtkTtk_gtk_rc_reset_styles = 0; +Ptr_gtk_rc_set_default_files GtkTtk_gtk_rc_set_default_files = 0; +Ptr_gtk_settings_get_default GtkTtk_gtk_settings_get_default = 0; +Ptr_gtk_statusbar_new GtkTtk_gtk_statusbar_new = 0; +Ptr_gtk_style_apply_default_background GtkTtk_gtk_style_apply_default_background = 0; +Ptr_gtk_style_attach GtkTtk_gtk_style_attach = 0; +Ptr_gtk_style_lookup_color GtkTtk_gtk_style_lookup_color = 0; +Ptr_gtk_toolbar_new GtkTtk_gtk_toolbar_new = 0; +Ptr_gtk_vpaned_new GtkTtk_gtk_vpaned_new = 0; +Ptr_gtk_vscale_new_with_range GtkTtk_gtk_vscale_new_with_range = 0; +Ptr_gtk_vscrollbar_new GtkTtk_gtk_vscrollbar_new = 0; +Ptr_gtk_widget_destroy GtkTtk_gtk_widget_destroy = 0; +Ptr_gtk_widget_realize GtkTtk_gtk_widget_realize = 0; +Ptr_gtk_widget_set_size_request GtkTtk_gtk_widget_set_size_request = 0; +Ptr_gtk_widget_size_request GtkTtk_gtk_widget_size_request = 0; +Ptr_gtk_widget_style_get GtkTtk_gtk_widget_style_get = 0; +Ptr_gtk_window_new GtkTtk_gtk_window_new = 0; +Ptr_xlib_rgb_init GtkTtk_xlib_rgb_init = 0; + +int GtkTtk_InitialiseSymbols_gdk(Tcl_Interp *interp, Tcl_Obj *file_name) { +#ifdef LOAD_SYMBOLS_WITH_TCL + Tcl_LoadHandle loadHandle; + int status; + status = Tcl_LoadFile(interp, file_name, NULL, 0, NULL, &loadHandle); + if (status != TCL_OK) return status; + GtkTtk_gdk_color_to_string = (Ptr_gdk_color_to_string) Tcl_FindSymbol(interp, loadHandle, "gdk_color_to_string"); + if (GtkTtk_gdk_color_to_string == NULL) return TCL_ERROR; + GtkTtk_gdk_display_get_default = (Ptr_gdk_display_get_default) Tcl_FindSymbol(interp, loadHandle, "gdk_display_get_default"); + if (GtkTtk_gdk_display_get_default == NULL) return TCL_ERROR; + GtkTtk_gdk_display_get_screen = (Ptr_gdk_display_get_screen) Tcl_FindSymbol(interp, loadHandle, "gdk_display_get_screen"); + if (GtkTtk_gdk_display_get_screen == NULL) return TCL_ERROR; + GtkTtk_gdk_drawable_set_colormap = (Ptr_gdk_drawable_set_colormap) Tcl_FindSymbol(interp, loadHandle, "gdk_drawable_set_colormap"); + if (GtkTtk_gdk_drawable_set_colormap == NULL) return TCL_ERROR; + GtkTtk_gdk_gc_new = (Ptr_gdk_gc_new) Tcl_FindSymbol(interp, loadHandle, "gdk_gc_new"); + if (GtkTtk_gdk_gc_new == NULL) return TCL_ERROR; + GtkTtk_gdk_pixbuf_get_from_drawable = (Ptr_gdk_pixbuf_get_from_drawable) Tcl_FindSymbol(interp, loadHandle, "gdk_pixbuf_get_from_drawable"); + if (GtkTtk_gdk_pixbuf_get_from_drawable == NULL) return TCL_ERROR; + GtkTtk_gdk_pixmap_foreign_new_for_screen = (Ptr_gdk_pixmap_foreign_new_for_screen) Tcl_FindSymbol(interp, loadHandle, "gdk_pixmap_foreign_new_for_screen"); + if (GtkTtk_gdk_pixmap_foreign_new_for_screen == NULL) return TCL_ERROR; + GtkTtk_gdk_pixmap_new = (Ptr_gdk_pixmap_new) Tcl_FindSymbol(interp, loadHandle, "gdk_pixmap_new"); + if (GtkTtk_gdk_pixmap_new == NULL) return TCL_ERROR; + GtkTtk_gdk_x11_colormap_foreign_new = (Ptr_gdk_x11_colormap_foreign_new) Tcl_FindSymbol(interp, loadHandle, "gdk_x11_colormap_foreign_new"); + if (GtkTtk_gdk_x11_colormap_foreign_new == NULL) return TCL_ERROR; + GtkTtk_gdk_x11_lookup_xdisplay = (Ptr_gdk_x11_lookup_xdisplay) Tcl_FindSymbol(interp, loadHandle, "gdk_x11_lookup_xdisplay"); + if (GtkTtk_gdk_x11_lookup_xdisplay == NULL) return TCL_ERROR; + GtkTtk_gdk_x11_screen_lookup_visual = (Ptr_gdk_x11_screen_lookup_visual) Tcl_FindSymbol(interp, loadHandle, "gdk_x11_screen_lookup_visual"); + if (GtkTtk_gdk_x11_screen_lookup_visual == NULL) return TCL_ERROR; +#else + const char *fname = Tcl_GetString(file_name); + GModule *m = g_module_open(fname, G_MODULE_BIND_LAZY); + if (!m) { + Tcl_SetResult(interp, (char *) "cannot open module: ", TCL_STATIC); + Tcl_AppendResult(interp, fname, (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_color_to_string", (gpointer *) &GtkTtk_gdk_color_to_string)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_color_to_string", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_display_get_default", (gpointer *) &GtkTtk_gdk_display_get_default)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_display_get_default", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_display_get_screen", (gpointer *) &GtkTtk_gdk_display_get_screen)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_display_get_screen", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_drawable_set_colormap", (gpointer *) &GtkTtk_gdk_drawable_set_colormap)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_drawable_set_colormap", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_gc_new", (gpointer *) &GtkTtk_gdk_gc_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_gc_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_pixbuf_get_from_drawable", (gpointer *) &GtkTtk_gdk_pixbuf_get_from_drawable)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_pixbuf_get_from_drawable", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_pixmap_foreign_new_for_screen", (gpointer *) &GtkTtk_gdk_pixmap_foreign_new_for_screen)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_pixmap_foreign_new_for_screen", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_pixmap_new", (gpointer *) &GtkTtk_gdk_pixmap_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_pixmap_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_x11_colormap_foreign_new", (gpointer *) &GtkTtk_gdk_x11_colormap_foreign_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_x11_colormap_foreign_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_x11_lookup_xdisplay", (gpointer *) &GtkTtk_gdk_x11_lookup_xdisplay)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_x11_lookup_xdisplay", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_x11_screen_lookup_visual", (gpointer *) &GtkTtk_gdk_x11_screen_lookup_visual)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_x11_screen_lookup_visual", (char *) NULL); + return TCL_ERROR; + } +#endif + return TCL_OK; +}; /* GtkTtk_InitialiseSymbols_gdk */ + + +int GtkTtk_InitialiseSymbols_gdk_pixbuf(Tcl_Interp *interp, Tcl_Obj *file_name) { +#ifdef LOAD_SYMBOLS_WITH_TCL + Tcl_LoadHandle loadHandle; + int status; + status = Tcl_LoadFile(interp, file_name, NULL, 0, NULL, &loadHandle); + if (status != TCL_OK) return status; + GtkTtk_gdk_pixbuf_new = (Ptr_gdk_pixbuf_new) Tcl_FindSymbol(interp, loadHandle, "gdk_pixbuf_new"); + if (GtkTtk_gdk_pixbuf_new == NULL) return TCL_ERROR; + GtkTtk_gdk_pixbuf_unref = (Ptr_gdk_pixbuf_unref) Tcl_FindSymbol(interp, loadHandle, "gdk_pixbuf_unref"); + if (GtkTtk_gdk_pixbuf_unref == NULL) return TCL_ERROR; +#else + const char *fname = Tcl_GetString(file_name); + GModule *m = g_module_open(fname, G_MODULE_BIND_LAZY); + if (!m) { + Tcl_SetResult(interp, (char *) "cannot open module: ", TCL_STATIC); + Tcl_AppendResult(interp, fname, (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_pixbuf_new", (gpointer *) &GtkTtk_gdk_pixbuf_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_pixbuf_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_pixbuf_unref", (gpointer *) &GtkTtk_gdk_pixbuf_unref)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_pixbuf_unref", (char *) NULL); + return TCL_ERROR; + } +#endif + return TCL_OK; +}; /* GtkTtk_InitialiseSymbols_gdk_pixbuf */ + + +int GtkTtk_InitialiseSymbols_gdk_pixbuf_xlib(Tcl_Interp *interp, Tcl_Obj *file_name) { +#ifdef LOAD_SYMBOLS_WITH_TCL + Tcl_LoadHandle loadHandle; + int status; + status = Tcl_LoadFile(interp, file_name, NULL, 0, NULL, &loadHandle); + if (status != TCL_OK) return status; + GtkTtk_gdk_pixbuf_xlib_render_to_drawable = (Ptr_gdk_pixbuf_xlib_render_to_drawable) Tcl_FindSymbol(interp, loadHandle, "gdk_pixbuf_xlib_render_to_drawable"); + if (GtkTtk_gdk_pixbuf_xlib_render_to_drawable == NULL) return TCL_ERROR; + GtkTtk_xlib_rgb_init = (Ptr_xlib_rgb_init) Tcl_FindSymbol(interp, loadHandle, "xlib_rgb_init"); + if (GtkTtk_xlib_rgb_init == NULL) return TCL_ERROR; +#else + const char *fname = Tcl_GetString(file_name); + GModule *m = g_module_open(fname, G_MODULE_BIND_LAZY); + if (!m) { + Tcl_SetResult(interp, (char *) "cannot open module: ", TCL_STATIC); + Tcl_AppendResult(interp, fname, (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gdk_pixbuf_xlib_render_to_drawable", (gpointer *) &GtkTtk_gdk_pixbuf_xlib_render_to_drawable)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gdk_pixbuf_xlib_render_to_drawable", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "xlib_rgb_init", (gpointer *) &GtkTtk_xlib_rgb_init)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "xlib_rgb_init", (char *) NULL); + return TCL_ERROR; + } +#endif + return TCL_OK; +}; /* GtkTtk_InitialiseSymbols_gdk_pixbuf_xlib */ + + +int GtkTtk_InitialiseSymbols_glib(Tcl_Interp *interp, Tcl_Obj *file_name) { +#ifdef LOAD_SYMBOLS_WITH_TCL + Tcl_LoadHandle loadHandle; + int status; + status = Tcl_LoadFile(interp, file_name, NULL, 0, NULL, &loadHandle); + if (status != TCL_OK) return status; + GtkTtk_g_free = (Ptr_g_free) Tcl_FindSymbol(interp, loadHandle, "g_free"); + if (GtkTtk_g_free == NULL) return TCL_ERROR; + GtkTtk_g_hash_table_get_keys = (Ptr_g_hash_table_get_keys) Tcl_FindSymbol(interp, loadHandle, "g_hash_table_get_keys"); + if (GtkTtk_g_hash_table_get_keys == NULL) return TCL_ERROR; + GtkTtk_g_malloc = (Ptr_g_malloc) Tcl_FindSymbol(interp, loadHandle, "g_malloc"); + if (GtkTtk_g_malloc == NULL) return TCL_ERROR; + GtkTtk_g_malloc0 = (Ptr_g_malloc0) Tcl_FindSymbol(interp, loadHandle, "g_malloc0"); + if (GtkTtk_g_malloc0 == NULL) return TCL_ERROR; + GtkTtk_g_option_context_add_main_entries = (Ptr_g_option_context_add_main_entries) Tcl_FindSymbol(interp, loadHandle, "g_option_context_add_main_entries"); + if (GtkTtk_g_option_context_add_main_entries == NULL) return TCL_ERROR; + GtkTtk_g_option_context_new = (Ptr_g_option_context_new) Tcl_FindSymbol(interp, loadHandle, "g_option_context_new"); + if (GtkTtk_g_option_context_new == NULL) return TCL_ERROR; + GtkTtk_g_strfreev = (Ptr_g_strfreev) Tcl_FindSymbol(interp, loadHandle, "g_strfreev"); + if (GtkTtk_g_strfreev == NULL) return TCL_ERROR; +#else + const char *fname = Tcl_GetString(file_name); + GModule *m = g_module_open(fname, G_MODULE_BIND_LAZY); + if (!m) { + Tcl_SetResult(interp, (char *) "cannot open module: ", TCL_STATIC); + Tcl_AppendResult(interp, fname, (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_free", (gpointer *) &GtkTtk_g_free)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_free", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_hash_table_get_keys", (gpointer *) &GtkTtk_g_hash_table_get_keys)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_hash_table_get_keys", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_malloc", (gpointer *) &GtkTtk_g_malloc)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_malloc", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_malloc0", (gpointer *) &GtkTtk_g_malloc0)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_malloc0", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_option_context_add_main_entries", (gpointer *) &GtkTtk_g_option_context_add_main_entries)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_option_context_add_main_entries", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_option_context_new", (gpointer *) &GtkTtk_g_option_context_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_option_context_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_strfreev", (gpointer *) &GtkTtk_g_strfreev)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_strfreev", (char *) NULL); + return TCL_ERROR; + } +#endif + return TCL_OK; +}; /* GtkTtk_InitialiseSymbols_glib */ + + +int GtkTtk_InitialiseSymbols_gobject(Tcl_Interp *interp, Tcl_Obj *file_name) { +#ifdef LOAD_SYMBOLS_WITH_TCL + Tcl_LoadHandle loadHandle; + int status; + status = Tcl_LoadFile(interp, file_name, NULL, 0, NULL, &loadHandle); + if (status != TCL_OK) return status; + GtkTtk_g_object_get = (Ptr_g_object_get) Tcl_FindSymbol(interp, loadHandle, "g_object_get"); + if (GtkTtk_g_object_get == NULL) return TCL_ERROR; + GtkTtk_g_object_unref = (Ptr_g_object_unref) Tcl_FindSymbol(interp, loadHandle, "g_object_unref"); + if (GtkTtk_g_object_unref == NULL) return TCL_ERROR; +#else + const char *fname = Tcl_GetString(file_name); + GModule *m = g_module_open(fname, G_MODULE_BIND_LAZY); + if (!m) { + Tcl_SetResult(interp, (char *) "cannot open module: ", TCL_STATIC); + Tcl_AppendResult(interp, fname, (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_object_get", (gpointer *) &GtkTtk_g_object_get)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_object_get", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_object_unref", (gpointer *) &GtkTtk_g_object_unref)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_object_unref", (char *) NULL); + return TCL_ERROR; + } +#endif + return TCL_OK; +}; /* GtkTtk_InitialiseSymbols_gobject */ + + +int GtkTtk_InitialiseSymbols_gtk(Tcl_Interp *interp, Tcl_Obj *file_name) { +#ifdef LOAD_SYMBOLS_WITH_TCL + Tcl_LoadHandle loadHandle; + int status; + status = Tcl_LoadFile(interp, file_name, NULL, 0, NULL, &loadHandle); + if (status != TCL_OK) return status; + GtkTtk_gtk_adjustment_new = (Ptr_gtk_adjustment_new) Tcl_FindSymbol(interp, loadHandle, "gtk_adjustment_new"); + if (GtkTtk_gtk_adjustment_new == NULL) return TCL_ERROR; + GtkTtk_gtk_adjustment_set_value = (Ptr_gtk_adjustment_set_value) Tcl_FindSymbol(interp, loadHandle, "gtk_adjustment_set_value"); + if (GtkTtk_gtk_adjustment_set_value == NULL) return TCL_ERROR; + GtkTtk_gtk_arrow_new = (Ptr_gtk_arrow_new) Tcl_FindSymbol(interp, loadHandle, "gtk_arrow_new"); + if (GtkTtk_gtk_arrow_new == NULL) return TCL_ERROR; + GtkTtk_gtk_border_free = (Ptr_gtk_border_free) Tcl_FindSymbol(interp, loadHandle, "gtk_border_free"); + if (GtkTtk_gtk_border_free == NULL) return TCL_ERROR; + GtkTtk_gtk_button_get_relief = (Ptr_gtk_button_get_relief) Tcl_FindSymbol(interp, loadHandle, "gtk_button_get_relief"); + if (GtkTtk_gtk_button_get_relief == NULL) return TCL_ERROR; + GtkTtk_gtk_button_new = (Ptr_gtk_button_new) Tcl_FindSymbol(interp, loadHandle, "gtk_button_new"); + if (GtkTtk_gtk_button_new == NULL) return TCL_ERROR; + GtkTtk_gtk_button_set_relief = (Ptr_gtk_button_set_relief) Tcl_FindSymbol(interp, loadHandle, "gtk_button_set_relief"); + if (GtkTtk_gtk_button_set_relief == NULL) return TCL_ERROR; + GtkTtk_gtk_check_button_new = (Ptr_gtk_check_button_new) Tcl_FindSymbol(interp, loadHandle, "gtk_check_button_new"); + if (GtkTtk_gtk_check_button_new == NULL) return TCL_ERROR; + GtkTtk_gtk_combo_box_entry_new = (Ptr_gtk_combo_box_entry_new) Tcl_FindSymbol(interp, loadHandle, "gtk_combo_box_entry_new"); + if (GtkTtk_gtk_combo_box_entry_new == NULL) return TCL_ERROR; + GtkTtk_gtk_combo_box_new = (Ptr_gtk_combo_box_new) Tcl_FindSymbol(interp, loadHandle, "gtk_combo_box_new"); + if (GtkTtk_gtk_combo_box_new == NULL) return TCL_ERROR; + GtkTtk_gtk_container_add = (Ptr_gtk_container_add) Tcl_FindSymbol(interp, loadHandle, "gtk_container_add"); + if (GtkTtk_gtk_container_add == NULL) return TCL_ERROR; + GtkTtk_gtk_disable_setlocale = (Ptr_gtk_disable_setlocale) Tcl_FindSymbol(interp, loadHandle, "gtk_disable_setlocale"); + if (GtkTtk_gtk_disable_setlocale == NULL) return TCL_ERROR; + GtkTtk_gtk_entry_new = (Ptr_gtk_entry_new) Tcl_FindSymbol(interp, loadHandle, "gtk_entry_new"); + if (GtkTtk_gtk_entry_new == NULL) return TCL_ERROR; + GtkTtk_gtk_fixed_new = (Ptr_gtk_fixed_new) Tcl_FindSymbol(interp, loadHandle, "gtk_fixed_new"); + if (GtkTtk_gtk_fixed_new == NULL) return TCL_ERROR; + GtkTtk_gtk_frame_new = (Ptr_gtk_frame_new) Tcl_FindSymbol(interp, loadHandle, "gtk_frame_new"); + if (GtkTtk_gtk_frame_new == NULL) return TCL_ERROR; + GtkTtk_gtk_hpaned_new = (Ptr_gtk_hpaned_new) Tcl_FindSymbol(interp, loadHandle, "gtk_hpaned_new"); + if (GtkTtk_gtk_hpaned_new == NULL) return TCL_ERROR; + GtkTtk_gtk_hscale_new_with_range = (Ptr_gtk_hscale_new_with_range) Tcl_FindSymbol(interp, loadHandle, "gtk_hscale_new_with_range"); + if (GtkTtk_gtk_hscale_new_with_range == NULL) return TCL_ERROR; + GtkTtk_gtk_hscrollbar_new = (Ptr_gtk_hscrollbar_new) Tcl_FindSymbol(interp, loadHandle, "gtk_hscrollbar_new"); + if (GtkTtk_gtk_hscrollbar_new == NULL) return TCL_ERROR; + GtkTtk_gtk_init_check = (Ptr_gtk_init_check) Tcl_FindSymbol(interp, loadHandle, "gtk_init_check"); + if (GtkTtk_gtk_init_check == NULL) return TCL_ERROR; + GtkTtk_gtk_notebook_new = (Ptr_gtk_notebook_new) Tcl_FindSymbol(interp, loadHandle, "gtk_notebook_new"); + if (GtkTtk_gtk_notebook_new == NULL) return TCL_ERROR; + GtkTtk_gtk_object_get = (Ptr_gtk_object_get) Tcl_FindSymbol(interp, loadHandle, "gtk_object_get"); + if (GtkTtk_gtk_object_get == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_arrow = (Ptr_gtk_paint_arrow) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_arrow"); + if (GtkTtk_gtk_paint_arrow == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_box = (Ptr_gtk_paint_box) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_box"); + if (GtkTtk_gtk_paint_box == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_box_gap = (Ptr_gtk_paint_box_gap) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_box_gap"); + if (GtkTtk_gtk_paint_box_gap == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_check = (Ptr_gtk_paint_check) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_check"); + if (GtkTtk_gtk_paint_check == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_extension = (Ptr_gtk_paint_extension) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_extension"); + if (GtkTtk_gtk_paint_extension == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_flat_box = (Ptr_gtk_paint_flat_box) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_flat_box"); + if (GtkTtk_gtk_paint_flat_box == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_focus = (Ptr_gtk_paint_focus) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_focus"); + if (GtkTtk_gtk_paint_focus == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_handle = (Ptr_gtk_paint_handle) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_handle"); + if (GtkTtk_gtk_paint_handle == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_option = (Ptr_gtk_paint_option) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_option"); + if (GtkTtk_gtk_paint_option == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_resize_grip = (Ptr_gtk_paint_resize_grip) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_resize_grip"); + if (GtkTtk_gtk_paint_resize_grip == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_shadow = (Ptr_gtk_paint_shadow) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_shadow"); + if (GtkTtk_gtk_paint_shadow == NULL) return TCL_ERROR; + GtkTtk_gtk_paint_slider = (Ptr_gtk_paint_slider) Tcl_FindSymbol(interp, loadHandle, "gtk_paint_slider"); + if (GtkTtk_gtk_paint_slider == NULL) return TCL_ERROR; + GtkTtk_gtk_progress_bar_new = (Ptr_gtk_progress_bar_new) Tcl_FindSymbol(interp, loadHandle, "gtk_progress_bar_new"); + if (GtkTtk_gtk_progress_bar_new == NULL) return TCL_ERROR; + GtkTtk_gtk_progress_bar_set_bar_style = (Ptr_gtk_progress_bar_set_bar_style) Tcl_FindSymbol(interp, loadHandle, "gtk_progress_bar_set_bar_style"); + if (GtkTtk_gtk_progress_bar_set_bar_style == NULL) return TCL_ERROR; + GtkTtk_gtk_progress_bar_set_fraction = (Ptr_gtk_progress_bar_set_fraction) Tcl_FindSymbol(interp, loadHandle, "gtk_progress_bar_set_fraction"); + if (GtkTtk_gtk_progress_bar_set_fraction == NULL) return TCL_ERROR; + GtkTtk_gtk_progress_bar_set_orientation = (Ptr_gtk_progress_bar_set_orientation) Tcl_FindSymbol(interp, loadHandle, "gtk_progress_bar_set_orientation"); + if (GtkTtk_gtk_progress_bar_set_orientation == NULL) return TCL_ERROR; + GtkTtk_gtk_range_get_adjustment = (Ptr_gtk_range_get_adjustment) Tcl_FindSymbol(interp, loadHandle, "gtk_range_get_adjustment"); + if (GtkTtk_gtk_range_get_adjustment == NULL) return TCL_ERROR; + GtkTtk_gtk_rc_get_default_files = (Ptr_gtk_rc_get_default_files) Tcl_FindSymbol(interp, loadHandle, "gtk_rc_get_default_files"); + if (GtkTtk_gtk_rc_get_default_files == NULL) return TCL_ERROR; + GtkTtk_gtk_rc_get_style = (Ptr_gtk_rc_get_style) Tcl_FindSymbol(interp, loadHandle, "gtk_rc_get_style"); + if (GtkTtk_gtk_rc_get_style == NULL) return TCL_ERROR; + GtkTtk_gtk_rc_get_theme_dir = (Ptr_gtk_rc_get_theme_dir) Tcl_FindSymbol(interp, loadHandle, "gtk_rc_get_theme_dir"); + if (GtkTtk_gtk_rc_get_theme_dir == NULL) return TCL_ERROR; + GtkTtk_gtk_rc_reparse_all_for_settings = (Ptr_gtk_rc_reparse_all_for_settings) Tcl_FindSymbol(interp, loadHandle, "gtk_rc_reparse_all_for_settings"); + if (GtkTtk_gtk_rc_reparse_all_for_settings == NULL) return TCL_ERROR; + GtkTtk_gtk_rc_reset_styles = (Ptr_gtk_rc_reset_styles) Tcl_FindSymbol(interp, loadHandle, "gtk_rc_reset_styles"); + if (GtkTtk_gtk_rc_reset_styles == NULL) return TCL_ERROR; + GtkTtk_gtk_rc_set_default_files = (Ptr_gtk_rc_set_default_files) Tcl_FindSymbol(interp, loadHandle, "gtk_rc_set_default_files"); + if (GtkTtk_gtk_rc_set_default_files == NULL) return TCL_ERROR; + GtkTtk_gtk_settings_get_default = (Ptr_gtk_settings_get_default) Tcl_FindSymbol(interp, loadHandle, "gtk_settings_get_default"); + if (GtkTtk_gtk_settings_get_default == NULL) return TCL_ERROR; + GtkTtk_gtk_statusbar_new = (Ptr_gtk_statusbar_new) Tcl_FindSymbol(interp, loadHandle, "gtk_statusbar_new"); + if (GtkTtk_gtk_statusbar_new == NULL) return TCL_ERROR; + GtkTtk_gtk_style_apply_default_background = (Ptr_gtk_style_apply_default_background) Tcl_FindSymbol(interp, loadHandle, "gtk_style_apply_default_background"); + if (GtkTtk_gtk_style_apply_default_background == NULL) return TCL_ERROR; + GtkTtk_gtk_style_attach = (Ptr_gtk_style_attach) Tcl_FindSymbol(interp, loadHandle, "gtk_style_attach"); + if (GtkTtk_gtk_style_attach == NULL) return TCL_ERROR; + GtkTtk_gtk_style_lookup_color = (Ptr_gtk_style_lookup_color) Tcl_FindSymbol(interp, loadHandle, "gtk_style_lookup_color"); + if (GtkTtk_gtk_style_lookup_color == NULL) return TCL_ERROR; + GtkTtk_gtk_toolbar_new = (Ptr_gtk_toolbar_new) Tcl_FindSymbol(interp, loadHandle, "gtk_toolbar_new"); + if (GtkTtk_gtk_toolbar_new == NULL) return TCL_ERROR; + GtkTtk_gtk_vpaned_new = (Ptr_gtk_vpaned_new) Tcl_FindSymbol(interp, loadHandle, "gtk_vpaned_new"); + if (GtkTtk_gtk_vpaned_new == NULL) return TCL_ERROR; + GtkTtk_gtk_vscale_new_with_range = (Ptr_gtk_vscale_new_with_range) Tcl_FindSymbol(interp, loadHandle, "gtk_vscale_new_with_range"); + if (GtkTtk_gtk_vscale_new_with_range == NULL) return TCL_ERROR; + GtkTtk_gtk_vscrollbar_new = (Ptr_gtk_vscrollbar_new) Tcl_FindSymbol(interp, loadHandle, "gtk_vscrollbar_new"); + if (GtkTtk_gtk_vscrollbar_new == NULL) return TCL_ERROR; + GtkTtk_gtk_widget_destroy = (Ptr_gtk_widget_destroy) Tcl_FindSymbol(interp, loadHandle, "gtk_widget_destroy"); + if (GtkTtk_gtk_widget_destroy == NULL) return TCL_ERROR; + GtkTtk_gtk_widget_realize = (Ptr_gtk_widget_realize) Tcl_FindSymbol(interp, loadHandle, "gtk_widget_realize"); + if (GtkTtk_gtk_widget_realize == NULL) return TCL_ERROR; + GtkTtk_gtk_widget_set_size_request = (Ptr_gtk_widget_set_size_request) Tcl_FindSymbol(interp, loadHandle, "gtk_widget_set_size_request"); + if (GtkTtk_gtk_widget_set_size_request == NULL) return TCL_ERROR; + GtkTtk_gtk_widget_size_request = (Ptr_gtk_widget_size_request) Tcl_FindSymbol(interp, loadHandle, "gtk_widget_size_request"); + if (GtkTtk_gtk_widget_size_request == NULL) return TCL_ERROR; + GtkTtk_gtk_widget_style_get = (Ptr_gtk_widget_style_get) Tcl_FindSymbol(interp, loadHandle, "gtk_widget_style_get"); + if (GtkTtk_gtk_widget_style_get == NULL) return TCL_ERROR; + GtkTtk_gtk_window_new = (Ptr_gtk_window_new) Tcl_FindSymbol(interp, loadHandle, "gtk_window_new"); + if (GtkTtk_gtk_window_new == NULL) return TCL_ERROR; +#else + const char *fname = Tcl_GetString(file_name); + GModule *m = g_module_open(fname, G_MODULE_BIND_LAZY); + if (!m) { + Tcl_SetResult(interp, (char *) "cannot open module: ", TCL_STATIC); + Tcl_AppendResult(interp, fname, (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_adjustment_new", (gpointer *) &GtkTtk_gtk_adjustment_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_adjustment_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_adjustment_set_value", (gpointer *) &GtkTtk_gtk_adjustment_set_value)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_adjustment_set_value", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_arrow_new", (gpointer *) &GtkTtk_gtk_arrow_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_arrow_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_border_free", (gpointer *) &GtkTtk_gtk_border_free)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_border_free", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_button_get_relief", (gpointer *) &GtkTtk_gtk_button_get_relief)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_button_get_relief", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_button_new", (gpointer *) &GtkTtk_gtk_button_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_button_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_button_set_relief", (gpointer *) &GtkTtk_gtk_button_set_relief)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_button_set_relief", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_check_button_new", (gpointer *) &GtkTtk_gtk_check_button_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_check_button_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_combo_box_entry_new", (gpointer *) &GtkTtk_gtk_combo_box_entry_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_combo_box_entry_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_combo_box_new", (gpointer *) &GtkTtk_gtk_combo_box_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_combo_box_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_container_add", (gpointer *) &GtkTtk_gtk_container_add)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_container_add", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_disable_setlocale", (gpointer *) &GtkTtk_gtk_disable_setlocale)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_disable_setlocale", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_entry_new", (gpointer *) &GtkTtk_gtk_entry_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_entry_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_fixed_new", (gpointer *) &GtkTtk_gtk_fixed_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_fixed_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_frame_new", (gpointer *) &GtkTtk_gtk_frame_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_frame_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_hpaned_new", (gpointer *) &GtkTtk_gtk_hpaned_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_hpaned_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_hscale_new_with_range", (gpointer *) &GtkTtk_gtk_hscale_new_with_range)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_hscale_new_with_range", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_hscrollbar_new", (gpointer *) &GtkTtk_gtk_hscrollbar_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_hscrollbar_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_init_check", (gpointer *) &GtkTtk_gtk_init_check)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_init_check", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_notebook_new", (gpointer *) &GtkTtk_gtk_notebook_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_notebook_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_object_get", (gpointer *) &GtkTtk_gtk_object_get)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_object_get", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_arrow", (gpointer *) &GtkTtk_gtk_paint_arrow)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_arrow", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_box", (gpointer *) &GtkTtk_gtk_paint_box)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_box", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_box_gap", (gpointer *) &GtkTtk_gtk_paint_box_gap)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_box_gap", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_check", (gpointer *) &GtkTtk_gtk_paint_check)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_check", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_extension", (gpointer *) &GtkTtk_gtk_paint_extension)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_extension", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_flat_box", (gpointer *) &GtkTtk_gtk_paint_flat_box)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_flat_box", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_focus", (gpointer *) &GtkTtk_gtk_paint_focus)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_focus", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_handle", (gpointer *) &GtkTtk_gtk_paint_handle)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_handle", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_option", (gpointer *) &GtkTtk_gtk_paint_option)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_option", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_resize_grip", (gpointer *) &GtkTtk_gtk_paint_resize_grip)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_resize_grip", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_shadow", (gpointer *) &GtkTtk_gtk_paint_shadow)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_shadow", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_paint_slider", (gpointer *) &GtkTtk_gtk_paint_slider)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_paint_slider", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_progress_bar_new", (gpointer *) &GtkTtk_gtk_progress_bar_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_progress_bar_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_progress_bar_set_bar_style", (gpointer *) &GtkTtk_gtk_progress_bar_set_bar_style)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_progress_bar_set_bar_style", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_progress_bar_set_fraction", (gpointer *) &GtkTtk_gtk_progress_bar_set_fraction)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_progress_bar_set_fraction", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_progress_bar_set_orientation", (gpointer *) &GtkTtk_gtk_progress_bar_set_orientation)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_progress_bar_set_orientation", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_range_get_adjustment", (gpointer *) &GtkTtk_gtk_range_get_adjustment)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_range_get_adjustment", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_rc_get_default_files", (gpointer *) &GtkTtk_gtk_rc_get_default_files)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_rc_get_default_files", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_rc_get_style", (gpointer *) &GtkTtk_gtk_rc_get_style)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_rc_get_style", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_rc_get_theme_dir", (gpointer *) &GtkTtk_gtk_rc_get_theme_dir)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_rc_get_theme_dir", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_rc_reparse_all_for_settings", (gpointer *) &GtkTtk_gtk_rc_reparse_all_for_settings)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_rc_reparse_all_for_settings", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_rc_reset_styles", (gpointer *) &GtkTtk_gtk_rc_reset_styles)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_rc_reset_styles", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_rc_set_default_files", (gpointer *) &GtkTtk_gtk_rc_set_default_files)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_rc_set_default_files", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_settings_get_default", (gpointer *) &GtkTtk_gtk_settings_get_default)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_settings_get_default", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_statusbar_new", (gpointer *) &GtkTtk_gtk_statusbar_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_statusbar_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_style_apply_default_background", (gpointer *) &GtkTtk_gtk_style_apply_default_background)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_style_apply_default_background", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_style_attach", (gpointer *) &GtkTtk_gtk_style_attach)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_style_attach", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_style_lookup_color", (gpointer *) &GtkTtk_gtk_style_lookup_color)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_style_lookup_color", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_toolbar_new", (gpointer *) &GtkTtk_gtk_toolbar_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_toolbar_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_vpaned_new", (gpointer *) &GtkTtk_gtk_vpaned_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_vpaned_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_vscale_new_with_range", (gpointer *) &GtkTtk_gtk_vscale_new_with_range)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_vscale_new_with_range", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_vscrollbar_new", (gpointer *) &GtkTtk_gtk_vscrollbar_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_vscrollbar_new", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_widget_destroy", (gpointer *) &GtkTtk_gtk_widget_destroy)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_widget_destroy", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_widget_realize", (gpointer *) &GtkTtk_gtk_widget_realize)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_widget_realize", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_widget_set_size_request", (gpointer *) &GtkTtk_gtk_widget_set_size_request)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_widget_set_size_request", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_widget_size_request", (gpointer *) &GtkTtk_gtk_widget_size_request)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_widget_size_request", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_widget_style_get", (gpointer *) &GtkTtk_gtk_widget_style_get)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_widget_style_get", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "gtk_window_new", (gpointer *) &GtkTtk_gtk_window_new)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "gtk_window_new", (char *) NULL); + return TCL_ERROR; + } +#endif + return TCL_OK; +}; /* GtkTtk_InitialiseSymbols_gtk */ + +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ diff --git a/src/gtkTtk/generic/gtkTtk_Symbols.h b/src/gtkTtk/generic/gtkTtk_Symbols.h new file mode 100644 index 0000000..9385408 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Symbols.h @@ -0,0 +1,375 @@ +/* + * gtkTtk_Symbols.h + * -------------------- + * + * This file is part of the GtkTtk package, a ttk based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2012 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ +/* THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT! */ +#ifndef _GTKTTK_SYMBOLS +#define _GTKTTK_SYMBOLS +#include "tcl.h" +#ifdef LOAD_SYMBOLS_WITH_TCL +#else +#include +#endif +#include +#include +#include +#ifndef __WIN32__ +#include +#else +#include +#endif + +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY +extern "C" { + typedef void (*Ptr_g_free)(gpointer mem); + extern Ptr_g_free GtkTtk_g_free; + typedef GList* (*Ptr_g_hash_table_get_keys)(GHashTable *hash_table); + extern Ptr_g_hash_table_get_keys GtkTtk_g_hash_table_get_keys; + typedef gpointer (*Ptr_g_malloc)(gsize n_bytes); + extern Ptr_g_malloc GtkTtk_g_malloc; + typedef gpointer (*Ptr_g_malloc0)(gsize n_bytes); + extern Ptr_g_malloc0 GtkTtk_g_malloc0; + typedef void (*Ptr_g_object_get)(gpointer object, const gchar *first_property_name, ...); + extern Ptr_g_object_get GtkTtk_g_object_get; + typedef void (*Ptr_g_object_unref)(gpointer object); + extern Ptr_g_object_unref GtkTtk_g_object_unref; + typedef void (*Ptr_g_option_context_add_main_entries)(GOptionContext *context, const GOptionEntry *entries, const gchar *translation_domain); + extern Ptr_g_option_context_add_main_entries GtkTtk_g_option_context_add_main_entries; + typedef GOptionContext* (*Ptr_g_option_context_new)(const gchar *parameter_string); + extern Ptr_g_option_context_new GtkTtk_g_option_context_new; + typedef void (*Ptr_g_strfreev)(gchar **str_array); + extern Ptr_g_strfreev GtkTtk_g_strfreev; + typedef gchar* (*Ptr_gdk_color_to_string)(const GdkColor *color); + extern Ptr_gdk_color_to_string GtkTtk_gdk_color_to_string; + typedef GdkDisplay* (*Ptr_gdk_display_get_default)(void); + extern Ptr_gdk_display_get_default GtkTtk_gdk_display_get_default; + typedef GdkScreen* (*Ptr_gdk_display_get_screen)(GdkDisplay*, gint); + extern Ptr_gdk_display_get_screen GtkTtk_gdk_display_get_screen; + typedef void (*Ptr_gdk_drawable_set_colormap)(GdkColormap*); + extern Ptr_gdk_drawable_set_colormap GtkTtk_gdk_drawable_set_colormap; + typedef GdkGC* (*Ptr_gdk_gc_new)(GdkDrawable *drawable); + extern Ptr_gdk_gc_new GtkTtk_gdk_gc_new; + typedef GdkPixbuf* (*Ptr_gdk_pixbuf_get_from_drawable)(GdkPixbuf *dest, GdkDrawable *src, GdkColormap *cmap, int src_x, int src_y, int dest_x, int dest_y, int width, int height); + extern Ptr_gdk_pixbuf_get_from_drawable GtkTtk_gdk_pixbuf_get_from_drawable; + typedef GdkPixbuf* (*Ptr_gdk_pixbuf_new)(GdkColorspace colorspace, gboolean has_alpha, int bits_per_sample, int width, int height); + extern Ptr_gdk_pixbuf_new GtkTtk_gdk_pixbuf_new; + typedef void (*Ptr_gdk_pixbuf_unref)(GdkPixbuf *pixbuf); + extern Ptr_gdk_pixbuf_unref GtkTtk_gdk_pixbuf_unref; + typedef GdkPixmap* (*Ptr_gdk_pixmap_foreign_new_for_screen)(GdkScreen *screen, GdkNativeWindow anid, gint width, gint height, gint depth); + extern Ptr_gdk_pixmap_foreign_new_for_screen GtkTtk_gdk_pixmap_foreign_new_for_screen; + typedef GdkPixmap* (*Ptr_gdk_pixmap_new)(GdkDrawable *drawable, gint width, gint height, gint depth); + extern Ptr_gdk_pixmap_new GtkTtk_gdk_pixmap_new; + typedef GdkColormap* (*Ptr_gdk_x11_colormap_foreign_new)(GdkVisual *visual, Colormap xcolormap); + extern Ptr_gdk_x11_colormap_foreign_new GtkTtk_gdk_x11_colormap_foreign_new; + typedef GdkDisplay* (*Ptr_gdk_x11_lookup_xdisplay)(Display *xdisplay); + extern Ptr_gdk_x11_lookup_xdisplay GtkTtk_gdk_x11_lookup_xdisplay; + typedef GdkVisual* (*Ptr_gdk_x11_screen_lookup_visual)(GdkScreen *screen, VisualID xvisualid); + extern Ptr_gdk_x11_screen_lookup_visual GtkTtk_gdk_x11_screen_lookup_visual; + typedef GtkObject* (*Ptr_gtk_adjustment_new)(double, double, double, double, double, double); + extern Ptr_gtk_adjustment_new GtkTtk_gtk_adjustment_new; + typedef void (*Ptr_gtk_adjustment_set_value)(GtkAdjustment *adjustment, gdouble value); + extern Ptr_gtk_adjustment_set_value GtkTtk_gtk_adjustment_set_value; + typedef GtkWidget* (*Ptr_gtk_arrow_new)(GtkArrowType at, GtkShadowType st); + extern Ptr_gtk_arrow_new GtkTtk_gtk_arrow_new; + typedef void (*Ptr_gtk_border_free)(GtkBorder*); + extern Ptr_gtk_border_free GtkTtk_gtk_border_free; + typedef GtkReliefStyle (*Ptr_gtk_button_get_relief)(GtkButton *button); + extern Ptr_gtk_button_get_relief GtkTtk_gtk_button_get_relief; + typedef GtkWidget* (*Ptr_gtk_button_new)(void); + extern Ptr_gtk_button_new GtkTtk_gtk_button_new; + typedef void (*Ptr_gtk_button_set_relief)(GtkButton *button, GtkReliefStyle newstyle); + extern Ptr_gtk_button_set_relief GtkTtk_gtk_button_set_relief; + typedef GtkWidget* (*Ptr_gtk_check_button_new)(void); + extern Ptr_gtk_check_button_new GtkTtk_gtk_check_button_new; + typedef GtkWidget* (*Ptr_gtk_combo_box_entry_new)(void); + extern Ptr_gtk_combo_box_entry_new GtkTtk_gtk_combo_box_entry_new; + typedef GtkWidget* (*Ptr_gtk_combo_box_new)(void); + extern Ptr_gtk_combo_box_new GtkTtk_gtk_combo_box_new; + typedef void (*Ptr_gtk_container_add)(GtkContainer *container, GtkWidget *widget); + extern Ptr_gtk_container_add GtkTtk_gtk_container_add; + typedef void (*Ptr_gtk_disable_setlocale)(void); + extern Ptr_gtk_disable_setlocale GtkTtk_gtk_disable_setlocale; + typedef GtkWidget* (*Ptr_gtk_entry_new)(void); + extern Ptr_gtk_entry_new GtkTtk_gtk_entry_new; + typedef GtkWidget* (*Ptr_gtk_fixed_new)(void); + extern Ptr_gtk_fixed_new GtkTtk_gtk_fixed_new; + typedef GtkWidget* (*Ptr_gtk_frame_new)(const gchar *label); + extern Ptr_gtk_frame_new GtkTtk_gtk_frame_new; + typedef GtkWidget* (*Ptr_gtk_hpaned_new)(void); + extern Ptr_gtk_hpaned_new GtkTtk_gtk_hpaned_new; + typedef GtkWidget* (*Ptr_gtk_hscale_new_with_range)(gdouble min, gdouble max, gdouble step); + extern Ptr_gtk_hscale_new_with_range GtkTtk_gtk_hscale_new_with_range; + typedef GtkWidget* (*Ptr_gtk_hscrollbar_new)(GtkAdjustment *); + extern Ptr_gtk_hscrollbar_new GtkTtk_gtk_hscrollbar_new; + typedef gboolean (*Ptr_gtk_init_check)(int *argc, char ***argv); + extern Ptr_gtk_init_check GtkTtk_gtk_init_check; + typedef GtkWidget* (*Ptr_gtk_notebook_new)(void); + extern Ptr_gtk_notebook_new GtkTtk_gtk_notebook_new; + typedef void (*Ptr_gtk_object_get)(GtkObject *object, const gchar *first_property_name, ...); + extern Ptr_gtk_object_get GtkTtk_gtk_object_get; + typedef void (*Ptr_gtk_paint_arrow)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, GtkArrowType, gboolean, gint , gint , gint , gint); + extern Ptr_gtk_paint_arrow GtkTtk_gtk_paint_arrow; + typedef void (*Ptr_gtk_paint_box)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint); + extern Ptr_gtk_paint_box GtkTtk_gtk_paint_box; + typedef void (*Ptr_gtk_paint_box_gap)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint, gint, gint , gint, GtkPositionType, gint gap_x, gint gap_width); + extern Ptr_gtk_paint_box_gap GtkTtk_gtk_paint_box_gap; + typedef void (*Ptr_gtk_paint_check)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint); + extern Ptr_gtk_paint_check GtkTtk_gtk_paint_check; + typedef void (*Ptr_gtk_paint_extension)(GtkStyle *, GdkWindow *, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint, gint, gint, gint, GtkPositionType); + extern Ptr_gtk_paint_extension GtkTtk_gtk_paint_extension; + typedef void (*Ptr_gtk_paint_flat_box)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint); + extern Ptr_gtk_paint_flat_box GtkTtk_gtk_paint_flat_box; + typedef void (*Ptr_gtk_paint_focus)(GtkStyle *style, GdkWindow *window, GtkStateType state_type, GdkRectangle *area, GtkWidget *widget, const gchar *detail, gint x, gint y, gint width, gint height); + extern Ptr_gtk_paint_focus GtkTtk_gtk_paint_focus; + typedef void (*Ptr_gtk_paint_handle)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint, GtkOrientation); + extern Ptr_gtk_paint_handle GtkTtk_gtk_paint_handle; + typedef void (*Ptr_gtk_paint_option)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint); + extern Ptr_gtk_paint_option GtkTtk_gtk_paint_option; + typedef void (*Ptr_gtk_paint_resize_grip)(GtkStyle*,GdkWindow*, GtkStateType, const GdkRectangle *, GtkWidget *, const gchar *, GdkWindowEdge, gint , gint , gint , gint); + extern Ptr_gtk_paint_resize_grip GtkTtk_gtk_paint_resize_grip; + typedef void (*Ptr_gtk_paint_shadow)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint); + extern Ptr_gtk_paint_shadow GtkTtk_gtk_paint_shadow; + typedef void (*Ptr_gtk_paint_slider)(GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint, GtkOrientation); + extern Ptr_gtk_paint_slider GtkTtk_gtk_paint_slider; + typedef GtkWidget* (*Ptr_gtk_progress_bar_new)(void); + extern Ptr_gtk_progress_bar_new GtkTtk_gtk_progress_bar_new; + typedef void (*Ptr_gtk_progress_bar_set_bar_style)(GtkProgressBar *pbar, GtkProgressBarStyle style); + extern Ptr_gtk_progress_bar_set_bar_style GtkTtk_gtk_progress_bar_set_bar_style; + typedef void (*Ptr_gtk_progress_bar_set_fraction)(GtkProgressBar *pbar, gdouble fraction); + extern Ptr_gtk_progress_bar_set_fraction GtkTtk_gtk_progress_bar_set_fraction; + typedef void (*Ptr_gtk_progress_bar_set_orientation)(GtkProgressBar *pbar, GtkProgressBarOrientation orientation); + extern Ptr_gtk_progress_bar_set_orientation GtkTtk_gtk_progress_bar_set_orientation; + typedef GtkAdjustment * (*Ptr_gtk_range_get_adjustment)(GtkRange *range); + extern Ptr_gtk_range_get_adjustment GtkTtk_gtk_range_get_adjustment; + typedef gchar** (*Ptr_gtk_rc_get_default_files)(void); + extern Ptr_gtk_rc_get_default_files GtkTtk_gtk_rc_get_default_files; + typedef GtkStyle * (*Ptr_gtk_rc_get_style)(GtkWidget*); + extern Ptr_gtk_rc_get_style GtkTtk_gtk_rc_get_style; + typedef gchar* (*Ptr_gtk_rc_get_theme_dir)(void); + extern Ptr_gtk_rc_get_theme_dir GtkTtk_gtk_rc_get_theme_dir; + typedef gboolean (*Ptr_gtk_rc_reparse_all_for_settings)(GtkSettings *settings, gboolean force_load); + extern Ptr_gtk_rc_reparse_all_for_settings GtkTtk_gtk_rc_reparse_all_for_settings; + typedef void (*Ptr_gtk_rc_reset_styles)(GtkSettings *settings); + extern Ptr_gtk_rc_reset_styles GtkTtk_gtk_rc_reset_styles; + typedef void (*Ptr_gtk_rc_set_default_files)(gchar **filenames); + extern Ptr_gtk_rc_set_default_files GtkTtk_gtk_rc_set_default_files; + typedef GtkSettings * (*Ptr_gtk_settings_get_default)(void); + extern Ptr_gtk_settings_get_default GtkTtk_gtk_settings_get_default; + typedef GtkWidget* (*Ptr_gtk_statusbar_new)(void); + extern Ptr_gtk_statusbar_new GtkTtk_gtk_statusbar_new; + typedef void (*Ptr_gtk_style_apply_default_background)(GtkStyle *style, GdkWindow *window, gboolean set_bg, GtkStateType state_type, GdkRectangle *area, gint x, gint y, gint width, gint height); + extern Ptr_gtk_style_apply_default_background GtkTtk_gtk_style_apply_default_background; + typedef GtkStyle* (*Ptr_gtk_style_attach)(GtkStyle *, GdkWindow *); + extern Ptr_gtk_style_attach GtkTtk_gtk_style_attach; + typedef gboolean (*Ptr_gtk_style_lookup_color)(GtkStyle *style, const gchar *color_name, GdkColor *color); + extern Ptr_gtk_style_lookup_color GtkTtk_gtk_style_lookup_color; + typedef GtkWidget* (*Ptr_gtk_toolbar_new)(void); + extern Ptr_gtk_toolbar_new GtkTtk_gtk_toolbar_new; + typedef GtkWidget* (*Ptr_gtk_vpaned_new)(void); + extern Ptr_gtk_vpaned_new GtkTtk_gtk_vpaned_new; + typedef GtkWidget* (*Ptr_gtk_vscale_new_with_range)(gdouble min, gdouble max, gdouble step); + extern Ptr_gtk_vscale_new_with_range GtkTtk_gtk_vscale_new_with_range; + typedef GtkWidget* (*Ptr_gtk_vscrollbar_new)(GtkAdjustment *); + extern Ptr_gtk_vscrollbar_new GtkTtk_gtk_vscrollbar_new; + typedef void (*Ptr_gtk_widget_destroy)(GtkWidget *); + extern Ptr_gtk_widget_destroy GtkTtk_gtk_widget_destroy; + typedef void (*Ptr_gtk_widget_realize)(GtkWidget *); + extern Ptr_gtk_widget_realize GtkTtk_gtk_widget_realize; + typedef void (*Ptr_gtk_widget_set_size_request)(GtkWidget *widget, gint width, gint height); + extern Ptr_gtk_widget_set_size_request GtkTtk_gtk_widget_set_size_request; + typedef void (*Ptr_gtk_widget_size_request)(GtkWidget *widget, GtkRequisition *requisition); + extern Ptr_gtk_widget_size_request GtkTtk_gtk_widget_size_request; + typedef void (*Ptr_gtk_widget_style_get)(GtkWidget *, const gchar *first_property_name, ...); + extern Ptr_gtk_widget_style_get GtkTtk_gtk_widget_style_get; + typedef GtkWidget* (*Ptr_gtk_window_new)(GtkWindowType); + extern Ptr_gtk_window_new GtkTtk_gtk_window_new; +} + +extern int GtkTtk_InitialiseSymbols_gdk(Tcl_Interp *interp, Tcl_Obj *file_name); +#define GTKTTK_LAST_SYMBOL_gdk GtkTtk_gdk_x11_screen_lookup_visual +extern int GtkTtk_InitialiseSymbols_gdk_pixbuf(Tcl_Interp *interp, Tcl_Obj *file_name); +#define GTKTTK_LAST_SYMBOL_gdk_pixbuf GtkTtk_gdk_pixbuf_unref +extern int GtkTtk_InitialiseSymbols_glib(Tcl_Interp *interp, Tcl_Obj *file_name); +#define GTKTTK_LAST_SYMBOL_glib GtkTtk_g_strfreev +extern int GtkTtk_InitialiseSymbols_gobject(Tcl_Interp *interp, Tcl_Obj *file_name); +#define GTKTTK_LAST_SYMBOL_gobject GtkTtk_g_object_unref +extern int GtkTtk_InitialiseSymbols_gtk(Tcl_Interp *interp, Tcl_Obj *file_name); +#define GTKTTK_LAST_SYMBOL_gtk GtkTtk_gtk_window_new + +#else /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + +#define GtkTtk_g_free \ + g_free +#define GtkTtk_g_hash_table_get_keys \ + g_hash_table_get_keys +#define GtkTtk_g_malloc \ + g_malloc +#define GtkTtk_g_malloc0 \ + g_malloc0 +#define GtkTtk_g_object_get \ + g_object_get +#define GtkTtk_g_object_unref \ + g_object_unref +#define GtkTtk_g_option_context_add_main_entries \ + g_option_context_add_main_entries +#define GtkTtk_g_option_context_new \ + g_option_context_new +#define GtkTtk_g_strfreev \ + g_strfreev +#define GtkTtk_gdk_color_to_string \ + gdk_color_to_string +#define GtkTtk_gdk_display_get_default \ + gdk_display_get_default +#define GtkTtk_gdk_display_get_screen \ + gdk_display_get_screen +#define GtkTtk_gdk_drawable_set_colormap \ + gdk_drawable_set_colormap +#define GtkTtk_gdk_gc_new \ + gdk_gc_new +#define GtkTtk_gdk_pixbuf_get_from_drawable \ + gdk_pixbuf_get_from_drawable +#define GtkTtk_gdk_pixbuf_new \ + gdk_pixbuf_new +#define GtkTtk_gdk_pixbuf_unref \ + gdk_pixbuf_unref +#define GtkTtk_gdk_pixmap_foreign_new_for_screen \ + gdk_pixmap_foreign_new_for_screen +#define GtkTtk_gdk_pixmap_new \ + gdk_pixmap_new +#define GtkTtk_gdk_x11_colormap_foreign_new \ + gdk_x11_colormap_foreign_new +#define GtkTtk_gdk_x11_lookup_xdisplay \ + gdk_x11_lookup_xdisplay +#define GtkTtk_gdk_x11_screen_lookup_visual \ + gdk_x11_screen_lookup_visual +#define GtkTtk_gtk_adjustment_new \ + gtk_adjustment_new +#define GtkTtk_gtk_adjustment_set_value \ + gtk_adjustment_set_value +#define GtkTtk_gtk_arrow_new \ + gtk_arrow_new +#define GtkTtk_gtk_border_free \ + gtk_border_free +#define GtkTtk_gtk_button_get_relief \ + gtk_button_get_relief +#define GtkTtk_gtk_button_new \ + gtk_button_new +#define GtkTtk_gtk_button_set_relief \ + gtk_button_set_relief +#define GtkTtk_gtk_check_button_new \ + gtk_check_button_new +#define GtkTtk_gtk_combo_box_entry_new \ + gtk_combo_box_entry_new +#define GtkTtk_gtk_combo_box_new \ + gtk_combo_box_new +#define GtkTtk_gtk_container_add \ + gtk_container_add +#define GtkTtk_gtk_disable_setlocale \ + gtk_disable_setlocale +#define GtkTtk_gtk_entry_new \ + gtk_entry_new +#define GtkTtk_gtk_fixed_new \ + gtk_fixed_new +#define GtkTtk_gtk_frame_new \ + gtk_frame_new +#define GtkTtk_gtk_hpaned_new \ + gtk_hpaned_new +#define GtkTtk_gtk_hscale_new_with_range \ + gtk_hscale_new_with_range +#define GtkTtk_gtk_hscrollbar_new \ + gtk_hscrollbar_new +#define GtkTtk_gtk_init_check \ + gtk_init_check +#define GtkTtk_gtk_notebook_new \ + gtk_notebook_new +#define GtkTtk_gtk_object_get \ + gtk_object_get +#define GtkTtk_gtk_paint_arrow \ + gtk_paint_arrow +#define GtkTtk_gtk_paint_box \ + gtk_paint_box +#define GtkTtk_gtk_paint_box_gap \ + gtk_paint_box_gap +#define GtkTtk_gtk_paint_check \ + gtk_paint_check +#define GtkTtk_gtk_paint_extension \ + gtk_paint_extension +#define GtkTtk_gtk_paint_flat_box \ + gtk_paint_flat_box +#define GtkTtk_gtk_paint_focus \ + gtk_paint_focus +#define GtkTtk_gtk_paint_handle \ + gtk_paint_handle +#define GtkTtk_gtk_paint_option \ + gtk_paint_option +#define GtkTtk_gtk_paint_resize_grip \ + gtk_paint_resize_grip +#define GtkTtk_gtk_paint_shadow \ + gtk_paint_shadow +#define GtkTtk_gtk_paint_slider \ + gtk_paint_slider +#define GtkTtk_gtk_progress_bar_new \ + gtk_progress_bar_new +#define GtkTtk_gtk_progress_bar_set_bar_style \ + gtk_progress_bar_set_bar_style +#define GtkTtk_gtk_progress_bar_set_fraction \ + gtk_progress_bar_set_fraction +#define GtkTtk_gtk_progress_bar_set_orientation \ + gtk_progress_bar_set_orientation +#define GtkTtk_gtk_range_get_adjustment \ + gtk_range_get_adjustment +#define GtkTtk_gtk_rc_get_default_files \ + gtk_rc_get_default_files +#define GtkTtk_gtk_rc_get_style \ + gtk_rc_get_style +#define GtkTtk_gtk_rc_get_theme_dir \ + gtk_rc_get_theme_dir +#define GtkTtk_gtk_rc_reparse_all_for_settings \ + gtk_rc_reparse_all_for_settings +#define GtkTtk_gtk_rc_reset_styles \ + gtk_rc_reset_styles +#define GtkTtk_gtk_rc_set_default_files \ + gtk_rc_set_default_files +#define GtkTtk_gtk_settings_get_default \ + gtk_settings_get_default +#define GtkTtk_gtk_statusbar_new \ + gtk_statusbar_new +#define GtkTtk_gtk_style_apply_default_background \ + gtk_style_apply_default_background +#define GtkTtk_gtk_style_attach \ + gtk_style_attach +#define GtkTtk_gtk_style_lookup_color \ + gtk_style_lookup_color +#define GtkTtk_gtk_toolbar_new \ + gtk_toolbar_new +#define GtkTtk_gtk_vpaned_new \ + gtk_vpaned_new +#define GtkTtk_gtk_vscale_new_with_range \ + gtk_vscale_new_with_range +#define GtkTtk_gtk_vscrollbar_new \ + gtk_vscrollbar_new +#define GtkTtk_gtk_widget_destroy \ + gtk_widget_destroy +#define GtkTtk_gtk_widget_realize \ + gtk_widget_realize +#define GtkTtk_gtk_widget_set_size_request \ + gtk_widget_set_size_request +#define GtkTtk_gtk_widget_size_request \ + gtk_widget_size_request +#define GtkTtk_gtk_widget_style_get \ + gtk_widget_style_get +#define GtkTtk_gtk_window_new \ + gtk_window_new +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + +#endif /* _GTKTTK_SYMBOLS */ diff --git a/src/gtkTtk/generic/gtkTtk_TkHeaders.h b/src/gtkTtk/generic/gtkTtk_TkHeaders.h new file mode 100644 index 0000000..a23dbb2 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_TkHeaders.h @@ -0,0 +1,34 @@ +/* + * gtkTtk_TkHeaders.h + * ---------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#ifndef __GTKTTK_TK_HEADERS +#define __GTKTTK_TK_HEADERS + +#ifdef USE_TK_STUBS +/* +#define USE_TTK_STUBS 1 + */ +#endif + +#include +#include "ttkTheme.h" +#define TILE_VERSION TTK_VERSION +//#include "ttkDecls.h" + +#ifdef __WIN32__ +#include +#endif + +#endif /* __GTKTTK_TK_HEADERS */ diff --git a/src/gtkTtk/generic/gtkTtk_ToolButton.cpp b/src/gtkTtk/generic/gtkTtk_ToolButton.cpp new file mode 100644 index 0000000..30998f8 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_ToolButton.cpp @@ -0,0 +1,203 @@ +/* + * gtkTtk_ToolButton.cpp + * ----------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +typedef struct { + Tcl_Obj *defaultStateObj; +} ToolButtonElement; + +static Ttk_ElementOptionSpec ToolButtonElementOptions[] = { + { (char *) "-default", TK_OPTION_ANY, + Tk_Offset(ToolButtonElement, defaultStateObj), (char *) "normal" }, + {NULL} +}; + +static void ToolButtonElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + GTKTTK_WIDGET_CACHE_DEFINITION; + gint focus_width; + gint focus_pad; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *widget = GtkTtk_GetButton(wc); + GTKTTK_ENSURE_WIDGET_OK; + GtkTtk_gtk_widget_style_get(widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + *paddingPtr = Ttk_UniformPadding(GtkTtk_ScalePx(tkwin, PushButtonUniformPadding) + + focus_width + focus_pad); +} + +static void ToolButtonElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + GTKTTK_GTK_DRAWABLE_DEFINITIONS; + gint width, height; + gint x, y; + gint border_width; + GtkBorder default_border = { 1, 1, 1, 1 }; + GtkBorder default_outside_border = { 0, 0, 0, 0 }; + GtkBorder *tmp_border, *tmp_outside_border; + GtkReliefStyle button_relief = GTK_RELIEF_NORMAL; + gboolean interior_focus; + gint focus_width; + gint focus_pad; + GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE; + GtkWidget *toolbar = GtkTtk_GetToolBar(wc); + GtkWidget *widget = GtkTtk_GetToolButton(wc); + ToolButtonElement *bd = (ToolButtonElement *) elementRecord; + GtkButton *button = (GtkButton *) widget; + GTKTTK_ENSURE_WIDGET_OK; + GTKTTK_STYLE_FROM_WIDGET; + GTKTTK_DRAWABLE_FROM_WIDGET; + GTKTTK_DEFAULT_BACKGROUND; + GtkTtk_StateShadowTableLookup(NULL, state, gtkState, gtkShadow, + GTKTTK_SECTION_BUTTONS | GTKTTK_SECTION_ALL); + GTKTTK_WIDGET_SET_FOCUS(widget); + GTKTTK_WIDGET_SET_DEFAULT(widget, bd->defaultStateObj); + // GtkTtk_StateInfo(state, gtkState, gtkShadow, tkwin, widget); + /* Make the button relief to what suggested by the toolbar... */ + GtkTtk_gtk_widget_style_get(toolbar, "button-relief", &button_relief,NULL); + if (button_relief != GtkTtk_gtk_button_get_relief(button)) { + GtkTtk_gtk_button_set_relief(button, button_relief); + } + + /* + * The following was taken from GTK+ button drawing code. + */ + border_width = ((GtkContainer*) widget)->border_width; + GtkTtk_gtk_widget_style_get(widget, + "default-border", &tmp_border, + "default-outside-border", &tmp_outside_border, + "interior-focus", &interior_focus, NULL); + if (tmp_border) { + default_border = *tmp_border; + GtkTtk_gtk_border_free(tmp_border); + } + if (tmp_outside_border) { + default_outside_border = *tmp_outside_border; + GtkTtk_gtk_border_free(tmp_outside_border); + } + + GtkTtk_gtk_widget_style_get(widget, + "focus-line-width", &focus_width, + "focus-padding", &focus_pad, NULL); + + x = b.x + border_width; + y = b.y + border_width; + width = b.width - border_width * 2; + height = b.height - border_width * 2; + + if (has_default && button->relief == GTK_RELIEF_NORMAL) { + GtkTtk_gtk_paint_box(style, gdkDrawable, GTK_STATE_NORMAL, GTK_SHADOW_IN, + NULL, widget, "buttondefault", x, y, width, height); + x += default_border.left; + y += default_border.top; + width -= default_border.left + default_border.right; + height -= default_border.top + default_border.bottom; + } else { + x += default_outside_border.left; + y += default_outside_border.top; + width -= default_outside_border.left + default_outside_border.right; + height -= default_outside_border.top + default_outside_border.bottom; + } + + if (!interior_focus && (state & TTK_STATE_FOCUS)) { + x += focus_width + focus_pad; + y += focus_width + focus_pad; + width -= 2 * (focus_width + focus_pad); + height -= 2 * (focus_width + focus_pad); + } + + if (button->relief != GTK_RELIEF_NONE || (state & TTK_STATE_PRESSED) || + (state & TTK_STATE_ACTIVE) ) { + GtkTtk_gtk_paint_box(style, gdkDrawable, gtkState, gtkShadow, NULL, + widget, "button", x, y, width, height); + } + + if (state & TTK_STATE_FOCUS) { + gint child_displacement_x; + gint child_displacement_y; + gboolean displace_focus; + + GtkTtk_gtk_widget_style_get(widget, + "child-displacement-y", &child_displacement_y, + "child-displacement-x", &child_displacement_x, + "displace-focus", &displace_focus, NULL); + + if (interior_focus) { + x += widget->style->xthickness + focus_pad; + y += widget->style->ythickness + focus_pad; + width -= 2 * (widget->style->xthickness + focus_pad); + height -= 2 * (widget->style->ythickness + focus_pad); + } else { + x -= focus_width + focus_pad; + y -= focus_width + focus_pad; + width += 2 * (focus_width + focus_pad); + height += 2 * (focus_width + focus_pad); + } + + if ((state & TTK_STATE_PRESSED) && displace_focus) { + x += child_displacement_x; + y += child_displacement_y; + } + + GtkTtk_gtk_paint_focus(style, gdkDrawable, gtkState, NULL, widget, + "button", x, y, width, height); + } + + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + GTKTTK_CLEANUP_GTK_DRAWABLE; +} + +static Ttk_ElementSpec ToolButtonElementSpec = { + TK_STYLE_VERSION_2, + sizeof(ToolButtonElement), + ToolButtonElementOptions, + ToolButtonElementGeometry, + ToolButtonElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +TTK_BEGIN_LAYOUT(ToolbuttonLayout) + TTK_GROUP("Toolbutton.border", TTK_FILL_BOTH, + TTK_GROUP("Toolbutton.padding", TTK_FILL_BOTH, + TTK_NODE("Toolbutton.label", TTK_FILL_BOTH))) +TTK_END_LAYOUT + +int GtkTtk_Init_ToolButton(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Toolbutton.border", + &ToolButtonElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, "TToolbutton", ToolbuttonLayout); + return TCL_OK; +}; /* GtkTtk_Init_ToolButton */ diff --git a/src/gtkTtk/generic/gtkTtk_TreeView.cpp b/src/gtkTtk/generic/gtkTtk_TreeView.cpp new file mode 100644 index 0000000..33695f5 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_TreeView.cpp @@ -0,0 +1,326 @@ +/* + * gtkTtk_TreeView.cpp + * --------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_Utilities.h" +#include "gtkTtk_TkHeaders.h" +#include "gtkTtk_WidgetDefaults.h" + +#define ITEM_LAYOUT "Item" +#define CELL_LAYOUT "Cell" +#define HEADING_LAYOUT "Heading" +#define ROW_LAYOUT "Row" + +/*------------------------------------------------------------------------ + * +++ TreeView Field Element. + */ + +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable treeview_field_statemap[] = +{ +#ifdef GTKTTK_GTK_VERSION_3 + {QStyle::Style_Enabled|QStyle::Style_Down, TTK_STATE_PRESSED, 0}, + {QStyle::Style_Enabled, TTK_STATE_ACTIVE, 0}, + {QStyle::Style_Enabled, 0, 0} +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + {QStyle::State_Enabled|QStyle::State_Sunken, TTK_STATE_PRESSED, 0}, + {QStyle::State_Enabled, TTK_STATE_ACTIVE, 0}, + {QStyle::State_Enabled, 0, 0} +#endif /* GTKTTK_GTK_VERSION_4 */ +}; + +typedef struct { +} TreeViewFieldElement; + + +static Ttk_ElementOptionSpec TreeViewFieldElementOptions[] = { + {NULL} +}; + +static void TreeViewFieldElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + *paddingPtr = Ttk_UniformPadding(0); +} + +static void TreeViewFieldElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + NULL_PROXY_WIDGET(GtkTtk_QWidget_Widget); + Tcl_MutexLock(>kTtkMutex); + QPixmap pixmap(b.width, b.height); + QPainter painter(&pixmap); + GTKTTK_PAINT_BACKGROUND_BASE(b.width, b.height); + GTKTTK_SET_FOCUS(state); +#ifdef GTKTTK_GTK_VERSION_3 + QStyle::SFlags sflags =GtkTtk_StateTableLookup(treeview_field_statemap, state); + sflags |= QStyle::Style_Horizontal; + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_GroupBoxFrame, &painter, + QRect(0, 0, b.width, b.height), qApp->palette().active(), sflags, + QStyleOption(/*lineWidth*/1, /*midLineWidth*/0, + /*frameShape*/QFrame::StyledPanel, + /*frameShadow*/QFrame::Sunken)); + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_PanelLineEdit, &painter, + QRect(0, 0, b.width, b.height), qApp->palette().active(), sflags, + QStyleOption(1,1)); +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + QStyleOptionFrame option; + option.rect = QRect(0, 0, b.width, b.height); + option.lineWidth = 1; + option.state |= + (QStyle::StateFlag) GtkTtk_StateTableLookup(treeview_field_statemap, state); + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_FrameGroupBox, &option, + &painter); +#endif /* GTKTTK_GTK_VERSION_4 */ + GTKTTK_CLEAR_FOCUS(state); + // printf("x=%d, y=%d, w=%d, h=%d\n", b.x, b.y, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + Tcl_MutexUnlock(>kTtkMutex); +} + +static Ttk_ElementSpec TreeViewFieldElementSpec = { + TK_STYLE_VERSION_2, + sizeof(TreeViewFieldElement), + TreeViewFieldElementOptions, + TreeViewFieldElementGeometry, + TreeViewFieldElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ TreeView Client Element. + */ + +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable treeview_client_statemap[] = +{ +#ifdef GTKTTK_GTK_VERSION_3 + {QStyle::Style_Enabled|QStyle::Style_Down, TTK_STATE_PRESSED, 0}, + {QStyle::Style_Enabled, TTK_STATE_ACTIVE, 0}, + {QStyle::Style_Enabled, 0, 0} +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + {QStyle::State_Enabled|QStyle::State_Sunken, TTK_STATE_PRESSED, 0}, + {QStyle::State_Enabled, TTK_STATE_ACTIVE, 0}, + {QStyle::State_Enabled, 0, 0} +#endif /* GTKTTK_GTK_VERSION_4 */ +}; + +typedef struct { +} TreeViewClientElement; + + +static Ttk_ElementOptionSpec TreeViewClientElementOptions[] = { + {NULL} +}; + +static void TreeViewClientElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + *paddingPtr = Ttk_UniformPadding(0); +} + +static void TreeViewClientElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + NULL_PROXY_WIDGET(GtkTtk_QWidget_Widget); + Tcl_MutexLock(>kTtkMutex); + QPixmap pixmap(b.width, b.height); + QPainter painter(&pixmap); + GTKTTK_PAINT_BACKGROUND_BASE(b.width, b.height); +#if 0 +#ifdef GTKTTK_GTK_VERSION_3 + QStyle::SFlags sflags = + GtkTtk_StateTableLookup(treeview_client_statemap, state); + sflags |= QStyle::Style_Horizontal; + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_GroupBoxFrame, &painter, + QRect(0, 0, b.width, b.height), qApp->palette().active(), sflags, + QStyleOption(/*lineWidth*/1, /*midLineWidth*/0, + /*frameShape*/QFrame::StyledPanel, + /*frameShadow*/QFrame::Sunken)); +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + QStyleOptionFrame option; + option.rect = QRect(0, 0, b.width, b.height); + option.lineWidth = 1; + option.state |= (QStyle::StateFlag) + GtkTtk_StateTableLookup(treeview_client_statemap, state); + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_FrameGroupBox, &option, + &painter); +#endif /* GTKTTK_GTK_VERSION_4 */ +#endif + // printf("x=%d, y=%d, w=%d, h=%d\n", b.x, b.y, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + Tcl_MutexUnlock(>kTtkMutex); +} + +static Ttk_ElementSpec TreeViewClientElementSpec = { + TK_STYLE_VERSION_2, + sizeof(TreeViewClientElement), + TreeViewClientElementOptions, + TreeViewClientElementGeometry, + TreeViewClientElementDraw +}; + +/*------------------------------------------------------------------------ + * +++ TreeView Header Border Element. + */ + +/* + * Map between Tk/Tile & Gtk/GNOME state flags. + */ +static Ttk_StateTable treeheading_border_statemap[] = +{ +#ifdef GTKTTK_GTK_VERSION_3 + {QStyle::Style_Enabled|QStyle::Style_Down, TTK_STATE_PRESSED, 0}, + {QStyle::Style_Enabled, TTK_STATE_ACTIVE, 0}, + {QStyle::Style_Enabled, 0, 0} +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + {QStyle::State_Enabled|QStyle::State_Sunken, TTK_STATE_PRESSED, 0}, + {QStyle::State_Enabled, TTK_STATE_ACTIVE, 0}, + {QStyle::State_Enabled, 0, 0} +#endif /* GTKTTK_GTK_VERSION_4 */ +}; + +typedef struct { +} TreeHeadingBorderElement; + + +static Ttk_ElementOptionSpec TreeHeadingBorderElementOptions[] = { + {NULL} +}; + +static void TreeHeadingBorderElementGeometry( + void *clientData, void *elementRecord, Tk_Window tkwin, + int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + *paddingPtr = Ttk_UniformPadding(TreeViewUniformPadding); +} + +static void TreeHeadingBorderElementDraw( + void *clientData, void *elementRecord, Tk_Window tkwin, + Drawable d, Ttk_Box b, unsigned state) +{ + if (!GtkTtk_GtkInitialised()) NO_GTK_STYLE_ENGINE; + NULL_PROXY_WIDGET(GtkTtk_QWidget_Widget); + Tcl_MutexLock(>kTtkMutex); + QPixmap pixmap(b.width, b.height); + QPainter painter(&pixmap); + GTKTTK_PAINT_BACKGROUND(b.width, b.height); +#ifdef GTKTTK_GTK_VERSION_3 + QStyle::SFlags sflags = GtkTtk_StateTableLookup(treeheading_border_statemap, + state); + sflags |= QStyle::Style_Horizontal; + wc->GtkTtk_Style->drawPrimitive(QStyle::PE_HeaderSection, &painter, + QRect(0, 0, b.width, b.height), qApp->palette().active(), sflags); +#endif /* GTKTTK_GTK_VERSION_3 */ +#ifdef GTKTTK_GTK_VERSION_4 + QStyleOptionHeader option; + option.rect = QRect(0, 0, b.width, b.height); + option.state |= + (QStyle::StateFlag) GtkTtk_StateTableLookup(treeview_client_statemap, state); + wc->GtkTtk_Style->drawControl(QStyle::CE_HeaderSection, &option, + &painter); +#endif /* GTKTTK_GTK_VERSION_4 */ + // printf("x=%d, y=%d, w=%d, h=%d\n", b.x, b.y, b.width, b.height); + GtkTtk_CopyGtkPixmapOnToDrawable(gdkDrawable, d, tkwin, + 0, 0, b.width, b.height, b.x, b.y); + Tcl_MutexUnlock(>kTtkMutex); +} + +static Ttk_ElementSpec TreeHeadingBorderElementSpec = { + TK_STYLE_VERSION_2, + sizeof(TreeHeadingBorderElement), + TreeHeadingBorderElementOptions, + TreeHeadingBorderElementGeometry, + TreeHeadingBorderElementDraw +}; + + +/*------------------------------------------------------------------------ + * +++ Widget layout. + */ + +#if 0 +TTK_BEGIN_LAYOUT(TreeviewLayout) + TTK_GROUP("Treeview.field", TTK_FILL_BOTH|TTK_BORDER, + TTK_GROUP("Treeview.padding", TTK_FILL_BOTH, + TTK_NODE("Treeview.client", TTK_FILL_BOTH))) +TTK_END_LAYOUT +#endif + +TTK_BEGIN_LAYOUT(ItemLayout) + TTK_GROUP("Treeitem.padding", TTK_FILL_BOTH, + TTK_NODE("Treeitem.indicator", TTK_PACK_LEFT) + TTK_NODE("Treeitem.image", TTK_PACK_LEFT) + TTK_GROUP("Treeitem.focus", TTK_PACK_LEFT, + TTK_NODE("Treeitem.text", TTK_PACK_LEFT))) +TTK_END_LAYOUT + +TTK_BEGIN_LAYOUT(CellLayout) + TTK_GROUP("Treedata.padding", TTK_FILL_BOTH, + TTK_NODE("Treeitem.label", TTK_FILL_BOTH)) +TTK_END_LAYOUT + +TTK_BEGIN_LAYOUT(HeadingLayout) + TTK_NODE("Treeheading.cell", TTK_FILL_BOTH) + TTK_GROUP("Treeheading.border", TTK_FILL_BOTH, + TTK_NODE("Treeheading.image", TTK_PACK_RIGHT) + TTK_NODE("Treeheading.text", 0)) +TTK_END_LAYOUT + +TTK_BEGIN_LAYOUT(RowLayout) + TTK_NODE("Treeitem.row", TTK_FILL_BOTH) +TTK_END_LAYOUT + +int GtkTtk_Init_TreeView(Tcl_Interp *interp, + GtkTtk_WidgetCache **wc, Ttk_Theme themePtr) +{ + /* + * Register elements: + */ + Ttk_RegisterElement(interp, themePtr, "Treeview.field", + &TreeViewFieldElementSpec, (void *) wc[0]); + //Ttk_RegisterElement(interp, themePtr, "Treeview.client", + // &TreeViewClientElementSpec, (void *) wc[0]); + Ttk_RegisterElement(interp, themePtr, "Treeheading.border", + &TreeHeadingBorderElementSpec, (void *) wc[0]); + + /* + * Register layouts: + */ + Ttk_RegisterLayout(themePtr, ITEM_LAYOUT, ItemLayout); + Ttk_RegisterLayout(themePtr, CELL_LAYOUT, CellLayout); + Ttk_RegisterLayout(themePtr, HEADING_LAYOUT, HeadingLayout); + Ttk_RegisterLayout(themePtr, ROW_LAYOUT, RowLayout); + + return TCL_OK; +}; /* GtkTtk_Init_TreeView */ diff --git a/src/gtkTtk/generic/gtkTtk_Utilities.cpp b/src/gtkTtk/generic/gtkTtk_Utilities.cpp new file mode 100644 index 0000000..98907bb --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Utilities.cpp @@ -0,0 +1,647 @@ +/* + * gtkTtk_Utilities.cpp + * ---------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_GtkHeaders.h" +#include "gtkTtk_TkHeaders.h" +#include +#include +extern gboolean GtkTtk_GtkInitialisedFlag; +extern GtkWidget *GtkTtk_GtkWindow; + +int GtkTtk_GtkInitialised(void) { + return GtkTtk_GtkInitialisedFlag; +}; /* GtkTtk_GtkInitialised */ + +GtkWidget *GtkTtk_GetGtkWindow(void) { + return GtkTtk_GtkWindow; +}; /* GtkTtk_GetGtkWindow */ + +GtkStyle *GtkTtk_GetGtkWindowStyle(GtkWidget *gtkWindow) { + if (gtkWindow) { + return gtkWindow->style; + } + return NULL; +}; /* GtkTtk_GetGtkWindowStyle */ + +GtkStyle *GtkTtk_GetGtkStyle(void) { + return GtkTtk_GetGtkWindowStyle(GtkTtk_GetGtkWindow()); +}; /* GtkTtk_GetGtkStyle */ + +void GtkTtk_InitialiseGtkWidget(GtkTtk_WidgetCache* wc, GtkWidget* widget) { + // GtkStyle *style; + if (!wc || !widget) return; + if (!wc->protoLayout) { + wc->protoLayout = GtkTtk_gtk_fixed_new(); + GtkTtk_gtk_container_add((GtkContainer*)(wc->gtkWindow), wc->protoLayout); + } + if (!wc->protoLayout) return; + GtkTtk_gtk_container_add((GtkContainer*)(wc->protoLayout), widget); + GtkTtk_gtk_widget_realize(widget); + // style = GtkTtk_gtk_rc_get_style(widget); + // if (style) GtkTtk_gtk_style_attach(style, +}; /* GtkTtk_InitialiseGtkWidget */ + +#define GTKTTK_CHECK_WIDGET(widget, allocator_function) \ + if (!wc) return 0; \ + if (!wc->widget) { \ + wc->widget = allocator_function; \ + GtkTtk_InitialiseGtkWidget(wc, wc->widget); \ + return wc->widget; \ + } \ + return wc->widget; + +GtkWidget *GtkTtk_GetArrow(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkArrow, + GtkTtk_gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE)); +}; /* GtkTtk_GetButton */ + +GtkWidget *GtkTtk_GetButton(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkButton, GtkTtk_gtk_button_new()); +}; /* GtkTtk_GetButton */ + +GtkWidget *GtkTtk_GetCheckButton(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkCheckButton, GtkTtk_gtk_check_button_new()); +}; /* GtkTtk_GetCheckButton */ + +GtkWidget *GtkTtk_GetRadioButton(GtkTtk_WidgetCache* wc) { + return GtkTtk_GetCheckButton(wc); +}; /* GtkTtk_GetRadioButton */ + +GtkWidget *GtkTtk_GetToolBar(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkToolBar, GtkTtk_gtk_toolbar_new()); +}; /* GtkTtk_GetToolBar */ + +GtkWidget *GtkTtk_GetToolButton(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkToolButton, GtkTtk_gtk_button_new()); +}; /* GtkTtk_GetToolButton */ + +GtkWidget *GtkTtk_GetFrame(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkFrame, GtkTtk_gtk_frame_new(NULL)); +}; /* GtkTtk_GetFrame */ + +GtkWidget *GtkTtk_GetEntry(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkEntry, GtkTtk_gtk_entry_new()); +}; /* GtkTtk_GetEntry */ + +GtkWidget *GtkTtk_GetCombobox(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkCombobox, GtkTtk_gtk_combo_box_new()); +}; /* GtkTtk_GetComboboxEntry */ + +GtkWidget *GtkTtk_GetComboboxEntry(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkComboboxEntry, GtkTtk_gtk_combo_box_entry_new()); +}; /* GtkTtk_GetComboboxEntry */ + +GtkWidget *GtkTtk_GetHScrollBar(GtkTtk_WidgetCache* wc) { + GtkAdjustment *adjustment = (GtkAdjustment *) + GtkTtk_gtk_adjustment_new(0.0, 0.0, 1.0, 0, 0, 0); + GTKTTK_CHECK_WIDGET(gtkHScrollBar, GtkTtk_gtk_hscrollbar_new(adjustment)); +}; /* GtkTtk_GetHScrollBar */ + +GtkWidget *GtkTtk_GetVScrollBar(GtkTtk_WidgetCache* wc) { + GtkAdjustment *adjustment = (GtkAdjustment *) + GtkTtk_gtk_adjustment_new(0.0, 0.0, 1.0, 0, 0, 0); + GTKTTK_CHECK_WIDGET(gtkVScrollBar, GtkTtk_gtk_vscrollbar_new(adjustment)); +}; /* GtkTtk_GetVScrollBar */ + +GtkWidget *GtkTtk_GetScrollBar(GtkTtk_WidgetCache* wc) { + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + return GtkTtk_GetHScrollBar(wc); + } + return GtkTtk_GetVScrollBar(wc); +}; /* GtkTtk_GetScrollBar */ + +GtkWidget *GtkTtk_GetHScale(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkHScale, GtkTtk_gtk_hscale_new_with_range(0,1,0.001)); +}; /* GtkTtk_GetHScale */ + +GtkWidget *GtkTtk_GetVScale(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkVScale, GtkTtk_gtk_vscale_new_with_range(0,1,0.001)); +}; /* GtkTtk_GetVScale */ + +GtkWidget *GtkTtk_GetScale(GtkTtk_WidgetCache* wc) { + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + return GtkTtk_GetHScale(wc); + } + return GtkTtk_GetVScale(wc); +}; /* GtkTtk_GetScale */ + +GtkWidget *GtkTtk_GetHProgressBar(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkHProgressBar, GtkTtk_gtk_progress_bar_new()); + GtkTtk_gtk_progress_bar_set_orientation( + (GtkProgressBar*) wc->gtkHProgressBar, GTK_PROGRESS_LEFT_TO_RIGHT); + GtkTtk_gtk_progress_bar_set_fraction( + (GtkProgressBar *) wc->gtkHProgressBar, 1); +}; /* GtkTtk_GetHProgressBar */ + +GtkWidget *GtkTtk_GetVProgressBar(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkVProgressBar, GtkTtk_gtk_progress_bar_new()); + GtkTtk_gtk_progress_bar_set_orientation( + (GtkProgressBar*) wc->gtkVProgressBar, GTK_PROGRESS_BOTTOM_TO_TOP); + GtkTtk_gtk_progress_bar_set_fraction( + (GtkProgressBar *) wc->gtkVProgressBar, 1); +}; /* GtkTtk_GetVProgressBar */ + +GtkWidget *GtkTtk_GetProgressBar(GtkTtk_WidgetCache* wc) { + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + return GtkTtk_GetHProgressBar(wc); + } + return GtkTtk_GetVProgressBar(wc); +}; /* GtkTtk_GetProgressBar */ + +GtkWidget *GtkTtk_GetStatusBar(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkStatusBar, GtkTtk_gtk_statusbar_new()); +}; /* GtkTtk_GetStatusBar */ + +GtkWidget *GtkTtk_GetHPaned(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkHPaned, GtkTtk_gtk_hpaned_new()); +}; /* GtkTtk_GetHPaned */ + +GtkWidget *GtkTtk_GetVPaned(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkVPaned, GtkTtk_gtk_vpaned_new()); +}; /* GtkTtk_GetVPaned */ + +GtkWidget *GtkTtk_GetPaned(GtkTtk_WidgetCache* wc) { + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + return GtkTtk_GetHPaned(wc); + } + return GtkTtk_GetVPaned(wc); +}; /* GtkTtk_GetPaned */ + +GtkWidget *GtkTtk_GetNotebook(GtkTtk_WidgetCache* wc) { + GTKTTK_CHECK_WIDGET(gtkNotebook, GtkTtk_gtk_notebook_new()); +}; /* GtkTtk_GetNotebook */ + + +const char *GtkTtk_GtkStateStr(GtkStateType gtkState) { + switch ((GtkStateType) gtkState) { + case GTK_STATE_NORMAL: return "GTK_STATE_NORMAL"; + case GTK_STATE_ACTIVE: return "GTK_STATE_ACTIVE"; + case GTK_STATE_PRELIGHT: return "GTK_STATE_PRELIGHT"; + case GTK_STATE_SELECTED: return "GTK_STATE_SELECTED"; + case GTK_STATE_INSENSITIVE: return "GTK_STATE_INSENSITIVE"; + } + return "invalid!"; +}; /* GtkTtk_GtkStateStr */ +const char *GtkTtk_GtkShadowStr(GtkShadowType gtkShadow) { + switch ((GtkShadowType) gtkShadow) { + case GTK_SHADOW_NONE: return "GTK_SHADOW_NONE"; + case GTK_SHADOW_IN: return "GTK_SHADOW_IN"; + case GTK_SHADOW_OUT: return "GTK_SHADOW_OUT"; + case GTK_SHADOW_ETCHED_IN: return "GTK_SHADOW_ETCHED_IN"; + case GTK_SHADOW_ETCHED_OUT: return "GTK_SHADOW_ETCHED_OUT"; + } + return "invalid!"; +}; /* GtkTtk_GtkShadowStr */ + +void GtkTtk_StateInfo(int state, GtkStateType gtkState, + GtkShadowType gtkShadow, Tk_Window tkwin, GtkWidget *widget) +{ + printf("Widget: %s\n ", Tk_PathName(tkwin)); + if (state & TTK_STATE_ACTIVE) { + printf("TTK_STATE_ACTIVE %d ", TTK_STATE_ACTIVE); + } + if (state & TTK_STATE_DISABLED) { + printf("TTK_STATE_DISABLED %d ", TTK_STATE_DISABLED); + } + if (state & TTK_STATE_FOCUS) { + printf("TTK_STATE_FOCUS %d ", TTK_STATE_FOCUS); + } + if (state & TTK_STATE_PRESSED) { + printf("TTK_STATE_PRESSED %d ", TTK_STATE_PRESSED); + } + if (state & TTK_STATE_SELECTED) { + printf("TTK_STATE_SELECTED %d ", TTK_STATE_SELECTED); + } + if (state & TTK_STATE_BACKGROUND) { + printf("TTK_STATE_BACKGROUND %d ", TTK_STATE_BACKGROUND); + } + if (state & TTK_STATE_ALTERNATE) { + printf("TTK_STATE_ALTERNATE %d ", TTK_STATE_ALTERNATE); + } + if (state & TTK_STATE_INVALID) { + printf("TTK_STATE_INVALID %d ", TTK_STATE_INVALID); + } + if (state & TTK_STATE_READONLY) { + printf("TTK_STATE_READONLY %d ", TTK_STATE_READONLY); + } + if (state & TTK_STATE_USER1) { + printf("TTK_STATE_USER1 %d ", TTK_STATE_USER1); + } + if (state & TTK_STATE_USER2) { + printf("TTK_STATE_USER2 %d ", TTK_STATE_USER2); + } + if (state & TTK_STATE_USER3) { + printf("TTK_STATE_USER3 %d ", TTK_STATE_USER3); + } + if (state & TTK_STATE_USER4) { + printf("TTK_STATE_USER4 %d ", TTK_STATE_USER4); + } + if (state & TTK_STATE_USER5) { + printf("TTK_STATE_USER5 %d ", TTK_STATE_USER5); + } + if (state & TTK_STATE_USER6) { + printf("TTK_STATE_USER6 %d ", TTK_STATE_USER6); + } +#ifdef TTK_STATE_USER7 + if (state & TTK_STATE_USER7) { + printf("TTK_STATE_USER7 %d ", TTK_STATE_USER7); + } +#endif /* TTK_STATE_USER7 */ + printf(" state=%d\n", state); + printf(" GTK state: %s, shadow: %s", + GtkTtk_GtkStateStr(gtkState), GtkTtk_GtkShadowStr(gtkShadow)); +#ifndef GTKTTK_LOAD_GTK_DYNAMICALLY + if (widget) { + printf(", focus: %d, default: %d", GTK_WIDGET_HAS_FOCUS(widget), + GTK_WIDGET_HAS_DEFAULT(widget)); + } +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + printf("\n"); + fflush(0); +}; /* GtkTtk_StateInfo */ + +void GtkTtk_CopyGtkPixmapOnToDrawable(GdkPixmap *gdkDrawable, Drawable d, + Tk_Window tkwin, int x, int y, int w, int h, int x1, int x2) +{ +#ifdef __WIN32__ +#define gc_usage ((GdkGCValuesMask) \ + (GDK_GC_FOREGROUND | GDK_GC_BACKGROUND | GDK_GC_EXPOSURES)) + XGCValues gcValues; + gcValues.graphics_exposures = False; + GC gc = Tk_GetGC(tkwin, GCForeground | GCBackground | GCGraphicsExposures, + &gcValues); + GdkGC *gdkGC = GtkTtk_gdk_gc_new(gdkDrawable); + HDC hdcSrc = GtkTtk_gdk_win32_hdc_get(gdkDrawable, gdkGC, gc_usage); + /* Create a Tk Drawable from the HDC... */ + TkWinDrawable gtkD; + gtkD.type = TWD_WINDC; + gtkD.winDC.hdc = hdcSrc; + XCopyArea(Tk_Display(tkwin), (Drawable) >kD, d, gc, x, y, w, h, x1, x2); + GtkTtk_gdk_win32_hdc_release(gdkDrawable, gdkGC, gc_usage); + if (gdkGC) GtkTtk_g_object_unref(gdkGC); + Tk_FreeGC(Tk_Display(tkwin), gc); +#else + +#ifdef GTKTTK_USE_XCOPY + XGCValues gcValues; + gcValues.graphics_exposures = False; + GC gc = Tk_GetGC(tkwin, GCForeground | GCBackground | GCGraphicsExposures, + &gcValues); + XCopyArea(Tk_Display(tkwin), GDK_DRAWABLE_XID(pixmap), d, gc, + x, y, w, h, x1, x2); + Tk_FreeGC(Tk_Display(tkwin), gc); + XGCValues gcValues; + GC gc; + + gcValues.function = GXcopy; + gcValues.graphics_exposures = False; + gc = Tk_GetGC(tkwin, GCFunction|GCGraphicsExposures, &gcValues); + + XCopyArea(Tk_Display(tkwin), d, Tk_WindowId(tkwin), gc, + 0, 0, (unsigned) Tk_Width(tkwin), (unsigned) Tk_Height(tkwin), + 0, 0); + + Tk_FreePixmap(Tk_Display(tkwin), d); + Tk_FreeGC(Tk_Display(tkwin), gc); +#else + GdkPixbuf *imgb; + Display *dpy = Tk_Display(tkwin); + Visual *vis = Tk_Visual(tkwin); + int depth = Tk_Depth(tkwin); + XGCValues gcValues; + gcValues.graphics_exposures = False; + GC gc = Tk_GetGC(tkwin, GCGraphicsExposures, &gcValues); + if (w <= 0 || h <= 0) { + Tk_FreeGC(dpy, gc); + return; + } + imgb = GtkTtk_gdk_pixbuf_new(GDK_COLORSPACE_RGB, false, 8, w, h); + if (!imgb) { + Tk_FreeGC(dpy, gc); + return; + } + imgb = GtkTtk_gdk_pixbuf_get_from_drawable(imgb, gdkDrawable, + NULL, x, y, 0, 0, w, h); + if (imgb) { + int rowstride = gdk_pixbuf_get_rowstride(imgb); + int nchan = gdk_pixbuf_get_n_channels(imgb); + const guchar *pixels = gdk_pixbuf_get_pixels(imgb); + if (depth == 24 || depth == 32) { + char *buf = (char *) malloc((size_t) w * (size_t) h * 4); + if (buf) { + XImage *ximg = XCreateImage(dpy, vis, (unsigned int) depth, ZPixmap, 0, + buf, (unsigned int) w, (unsigned int) h, 32, w * 4); + if (ximg) { + unsigned long rmask = vis->red_mask ? vis->red_mask : 0xff0000UL; + unsigned long gmask = vis->green_mask ? vis->green_mask : 0x00ff00UL; + unsigned long bmask = vis->blue_mask ? vis->blue_mask : 0x0000ffUL; + int rshift = __builtin_ctzl(rmask); + int gshift = __builtin_ctzl(gmask); + int bshift = __builtin_ctzl(bmask); + for (int row = 0; row < h; ++row) { + const guchar *src = pixels + row * rowstride; + for (int col = 0; col < w; ++col) { + unsigned long px = + (((unsigned long) src[col * nchan + 0] << rshift) & rmask) | + (((unsigned long) src[col * nchan + 1] << gshift) & gmask) | + (((unsigned long) src[col * nchan + 2] << bshift) & bmask); + XPutPixel(ximg, col, row, px); + } + } + XPutImage(dpy, d, gc, ximg, 0, 0, x1, x2, (unsigned int) w, (unsigned int) h); + XDestroyImage(ximg); + } else { + free(buf); + } + } + } else { + XImage *ximg = XCreateImage(dpy, vis, (unsigned int) depth, ZPixmap, 0, + NULL, (unsigned int) w, (unsigned int) h, 8, 0); + if (ximg) { + ximg->data = (char *) calloc((size_t) ximg->bytes_per_line, (size_t) h); + if (ximg->data) { + for (int row = 0; row < h; ++row) { + const guchar *src = pixels + row * rowstride; + for (int col = 0; col < w; ++col) { + unsigned long px = ((unsigned long) (src[col * nchan + 0] >> 3) << 11) | + ((unsigned long) (src[col * nchan + 1] >> 2) << 5) | + ((unsigned long) (src[col * nchan + 2] >> 3)); + XPutPixel(ximg, col, row, px); + } + } + XPutImage(dpy, d, gc, ximg, 0, 0, x1, x2, (unsigned int) w, (unsigned int) h); + } + XDestroyImage(ximg); + } + } + g_object_unref(imgb); + } + Tk_FreeGC(dpy, gc); +#endif + +/* + * How to convert an X drawable to a GtkDrawable! + * + GdkPixmap *gdkDrawable = NULL; \ + GtkStyle *style = NULL; \ + GdkScreen *screen = NULL; \ + GdkColormap *cmap = NULL; \ + screen = GtkTtk_gdk_display_get_screen(wc->gdkDisplay, \ + Tk_ScreenNumber(tkwin)); \ + printf("Widget: %s, d=%d, p=%p\n", Tk_PathName(tkwin), d, \ + gdk_xid_table_lookup((XID) d));fflush(0); \ + gdkDrawable = GtkTtk_gdk_pixmap_foreign_new_for_screen(screen, d, \ + Tk_Width(tkwin), Tk_Height(tkwin), \ + DefaultDepthOfScreen(Tk_Screen(tkwin))); \ + if (!gdkDrawable) return; \ + GdkVisual *visual = GtkTtk_gdk_x11_screen_lookup_visual(screen, + XVisualIDFromVisual(Tk_Visual(tkwin))); \ + cmap = GtkTtk_gdk_x11_colormap_foreign_new(visual, Tk_Colormap(tkwin)); \ + GtkTtk_gdk_drawable_set_colormap(gdkDrawable, cmap);\ + printf("d=%d, gdkDrawable=%p, XID=%d, p=%p\n", d, gdkDrawable, \ + gdk_x11_drawable_get_xid(gdkDrawable), \ + gdk_xid_table_lookup((XID) d));fflush(0); + */ +#endif +}; /* GtkTtk_CopyGtkPixmapOnToDrawable */ + +void GtkTtk_StoreStyleNameLowers(GtkTtk_WidgetCache *wc) { +}; /* GtkTtk_StoreStyleName */ + +bool GtkTtk_ThemeIs(GtkTtk_WidgetCache *wc, const char* name) { + return false; +}; /* GtkTtk_ThemeIs */ + +/* + * GtkTtk_StateTableLookup -- + * Look up an index from a statically allocated state table. + */ +unsigned int GtkTtk_StateTableLookup(Ttk_StateTable *map, unsigned int state) { + return Ttk_StateTableLookup(map, state); + int value = 0; + while (map->onBits || map->offBits) { + if (state & map->onBits) value |= map->index; + ++map; + } + return value; +}; /* GtkTtk_StateTableLookup */ + +/* + * GTK_STATE_NORMAL: State during normal operation. + * GTK_STATE_ACTIVE: State of a currently active widget, such as a + * depressed button. + * GTK_STATE_PRELIGHT: State indicating that the mouse pointer is over the + * widget and the widget will respond to mouse clicks. + * GTK_STATE_SELECTED: State of a selected item, such the selected row in + * a list. + * GTK_STATE_INSENSITIVE: State indicating that the widget is unresponsive + * to user actions. + * + * GTK_SHADOW_NONE: No outline. + * GTK_SHADOW_IN: The outline is bevelled inwards. + * GTK_SHADOW_OUT: The outline is bevelled outwards like a button. + * GTK_SHADOW_ETCHED_IN: The outline has a sunken 3d appearance. + * GTK_SHADOW_ETCHED_OUT: The outline has a raised 3d appearance + * + * TTK_STATE_ACTIVE + * TTK_STATE_DISABLED + * TTK_STATE_FOCUS + * TTK_STATE_PRESSED + * TTK_STATE_SELECTED + * TTK_STATE_BACKGROUND + * TTK_STATE_ALTERNATE + * TTK_STATE_INVALID + * TTK_STATE_READONLY + */ +unsigned int GtkTtk_StateShadowTableLookup(GtkTtk_StateTable *map, + unsigned int state, GtkStateType& gtkState, + GtkShadowType& gtkShadow, unsigned int section) { + static GtkTtk_StateTable default_map[] = { + /* Section for: Buttons */ + /* Section common to all widgets */ + {GTK_STATE_ACTIVE, GTK_SHADOW_NONE, 0, + TTK_STATE_ACTIVE, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_INSENSITIVE, GTK_SHADOW_NONE, 0, + TTK_STATE_DISABLED, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_PRELIGHT, GTK_SHADOW_NONE, 0, + TTK_STATE_FOCUS, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_SELECTED, GTK_SHADOW_NONE, 0, + TTK_STATE_PRESSED, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_SELECTED, GTK_SHADOW_NONE, 0, + TTK_STATE_SELECTED, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_NORMAL, GTK_SHADOW_NONE, 0, + TTK_STATE_BACKGROUND, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_NORMAL, GTK_SHADOW_NONE, 0, + TTK_STATE_ALTERNATE, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_INSENSITIVE, GTK_SHADOW_NONE, 0, + TTK_STATE_INVALID, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_INSENSITIVE, GTK_SHADOW_NONE, 0, + TTK_STATE_READONLY, 0, GTKTTK_SECTION_ALL}, + {GTK_STATE_NORMAL, GTK_SHADOW_NONE, 0, + 0, 0, GTKTTK_SECTION_ALL} + }; + unsigned int value = 0; + gtkState = GTK_STATE_NORMAL; + gtkShadow = GTK_SHADOW_NONE; + if (!map) { + map = default_map; + /* Instead of writting huge tables, do some checks here... */ + if (section & GTKTTK_SECTION_STEPPERS) { + gtkShadow = GTK_SHADOW_OUT; + if (state & TTK_STATE_DISABLED) { + gtkState = GTK_STATE_INSENSITIVE; + } else if (state & TTK_STATE_PRESSED) { + gtkState = GTK_STATE_ACTIVE; + gtkShadow = GTK_SHADOW_IN; + } else if (state & TTK_STATE_ACTIVE) { + gtkState = GTK_STATE_PRELIGHT; + } + map = NULL; /* Do not search the table */ + } else if (section & GTKTTK_SECTION_BUTTONS || + section & GTKTTK_SECTION_ENTRY || + section & GTKTTK_SECTION_SCROLLBAR) { + /* Whether the button is drawn pressed or not, is defined by shadow. */ + if (state & TTK_STATE_PRESSED || state & TTK_STATE_SELECTED) { + gtkShadow = GTK_SHADOW_IN; + } else { + gtkShadow = GTK_SHADOW_OUT; + if (state & TTK_STATE_DISABLED || state & TTK_STATE_READONLY) + gtkState = GTK_STATE_INSENSITIVE; + // else if (state & TTK_STATE_ACTIVE) gtkState = GTK_STATE_PRELIGHT; + // else if (state & TTK_STATE_FOCUS) gtkState = GTK_STATE_ACTIVE; + } + if (section & GTKTTK_SECTION_ENTRY) { + if (state & TTK_STATE_FOCUS) gtkState = GTK_STATE_NORMAL; + gtkShadow = GTK_SHADOW_IN; + } + if ((state & TTK_STATE_ACTIVE) && + (!(state & TTK_STATE_PRESSED) && !(state & TTK_STATE_SELECTED))) { + gtkState = GTK_STATE_PRELIGHT; + } else { + if (!(section & GTKTTK_SECTION_SCROLLBAR) && + state & TTK_STATE_DISABLED || state & TTK_STATE_READONLY) + gtkState = GTK_STATE_INSENSITIVE; + else if (state & TTK_STATE_PRESSED) gtkState = GTK_STATE_ACTIVE; + else if (state & TTK_STATE_DISABLED) + gtkState = GTK_STATE_INSENSITIVE; + } + map = NULL; /* Do not search the table */ + } else if (section & GTKTTK_SECTION_TROUGH) { + if (state & TTK_STATE_PRESSED) { + gtkState = GTK_STATE_ACTIVE; + } else { + gtkState = GTK_STATE_INSENSITIVE; + } + gtkShadow = GTK_SHADOW_IN; + map = NULL; /* Do not search the table */ + } else if (section & GTKTTK_SECTION_SASH) { + if (state & TTK_STATE_DISABLED || state & TTK_STATE_READONLY) + gtkState = GTK_STATE_INSENSITIVE; + else if (state & TTK_STATE_FOCUS) gtkState = GTK_STATE_SELECTED; + else if (state & TTK_STATE_ACTIVE) gtkState = GTK_STATE_PRELIGHT; + map = NULL; /* Do not search the table */ + } else if (section & GTKTTK_SECTION_TABS) { + gtkState = GTK_STATE_ACTIVE; + gtkShadow = GTK_SHADOW_OUT; + if (state & TTK_STATE_DISABLED || state & TTK_STATE_READONLY) + gtkState = GTK_STATE_INSENSITIVE; + else if (state & TTK_STATE_SELECTED) gtkState = GTK_STATE_NORMAL; + else if (state & TTK_STATE_ACTIVE) gtkState = GTK_STATE_PRELIGHT; + else if (state & TTK_STATE_FOCUS) gtkState = GTK_STATE_ACTIVE; + map = NULL; /* Do not search the table */ + } + } + if (map) { + while ( (state & map->onBits) != map->onBits || + (~state & map->offBits) != map->offBits || + !(section & map->section)) { + ++map; ++value; + } + gtkState = map->state; + gtkShadow = map->shadow; + } + return (map)? map->value : value; +}; /* GtkTtk_StateShadowTableLookup */ + +static bool GtkTtk_ParsePositiveDouble(const char *s, double *out) { + if (!s || !s[0]) return false; + char *end = NULL; + double v = std::strtod(s, &end); + if (end == s || v <= 0.0) return false; + *out = v; + return true; +} + +double GtkTtk_GetDpiScale(Tk_Window tkwin) { + double val = 0.0; + if (GtkTtk_ParsePositiveDouble(std::getenv("ANODE_SCALE"), &val)) { + return std::max(0.5, std::min(val, 4.0)); + } + if (GtkTtk_ParsePositiveDouble(std::getenv("GTKTTK_SCALE"), &val)) { + return std::max(0.5, std::min(val, 4.0)); + } + Display *dpy = tkwin ? Tk_Display(tkwin) : NULL; + if (dpy) { + const char *xft_dpi = XGetDefault(dpy, "Xft", "dpi"); + if (GtkTtk_ParsePositiveDouble(xft_dpi, &val)) { + return std::max(0.5, std::min(val / 96.0, 4.0)); + } + } + if (GtkTtk_ParsePositiveDouble(std::getenv("QT_SCALE_FACTOR"), &val)) { + return std::max(0.5, std::min(val, 4.0)); + } + if (GtkTtk_ParsePositiveDouble(std::getenv("GDK_SCALE"), &val)) { + double dpi_scale = 1.0; + if (GtkTtk_ParsePositiveDouble(std::getenv("GDK_DPI_SCALE"), &dpi_scale)) { + val *= dpi_scale; + } + return std::max(0.5, std::min(val, 4.0)); + } + if (dpy) { + int scr = Tk_ScreenNumber(tkwin); + int mm = DisplayWidthMM(dpy, scr); + if (mm > 0) { + double dpi = (double)DisplayWidth(dpy, scr) * 25.4 / (double)mm; + return std::max(0.5, std::min(dpi / 96.0, 4.0)); + } + } + return 1.0; +} + +int GtkTtk_ScalePx(Tk_Window tkwin, int base_px) { + if (base_px <= 0) return 0; + double sc = GtkTtk_GetDpiScale(tkwin); + int res = (int)(base_px * sc + 0.5); + return std::max(1, res); +} + +double GtkTtk_ValueFromSlider(GtkTtk_WidgetCache *wc, Tk_Window tkwin, + Ttk_Box b) { + double value = 0.0; + double ww = Tk_Width(tkwin), wh = Tk_Height(tkwin), dx = 0.0, x; + if (wc->orientation == TTK_ORIENT_HORIZONTAL) { + dx = b.width / 2.0; + x = b.x + dx; + value = x / ww; + } else { + dx = b.height / 2.0; + x = b.y + dx; + value = x / wh; + } + if (value < 0.0) value = 0.0; + if (value > 1.0) value = 1.0; + // printf("ww:%f, b.x:%d, x:%f, dx:%f, v:%f\n", ww, b.x, x, dx, value); + return value; +}; /* GtkTtk_ValueFromSlider */ diff --git a/src/gtkTtk/generic/gtkTtk_Utilities.h b/src/gtkTtk/generic/gtkTtk_Utilities.h new file mode 100644 index 0000000..e970f42 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_Utilities.h @@ -0,0 +1,196 @@ +/* + * gtkTtk_Utilities.h + * ---------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#include "gtkTtk_GtkHeaders.h" +#include "gtkTtk_Elements.h" +#include +#include + +#define NO_GTK_STYLE_ENGINE {/*printf("NULL qApp\n");fflush(NULL);*/return;} + +#define GTKTTK_ENSURE_GTK_STYLE_ENGINE_ACTIVE \ + if (!GtkTtk_GtkInitialised()) return; + +#define GTKTTK_ENSURE_WIDGET_OK \ + if (!widget) return; + +#define GTKTTK_ATTACH_STYLE_TO_WIDGET \ + style = GtkTtk_gtk_style_attach(style, widget->window); + +#define GTKTTK_WIDGET_CACHE_DEFINITION \ + GtkTtk_WidgetCache *wc = (GtkTtk_WidgetCache *) clientData; + +#define GTKTTK_ORIENTATION_DEFINITION \ + int orientation = wc->orientation; + +#define GTKTTK_GTK_DRAWABLE_DEFINITIONS \ + GtkTtk_WidgetCache *wc = (GtkTtk_WidgetCache *) clientData; \ + GdkPixmap *gdkDrawable = NULL; \ + GtkStyle *style = NULL; \ + GtkStateType gtkState = GTK_STATE_NORMAL; \ + GtkShadowType gtkShadow = GTK_SHADOW_NONE; + +#define GTKTTK_SETUP_GTK_DRAWABLE \ + GTKTTK_SETUP_GTK_DRAWABLE_PIXMAP_SIZE(b.width, b.height) + +#define GTKTTK_SETUP_GTK_DRAWABLE_PIXMAP_SIZE(pw, ph) \ + if (!wc) return; \ + style = GtkTtk_GetGtkWindowStyle(wc->gtkWindow); \ + if (!style) return; \ + gdkDrawable = GtkTtk_gdk_pixmap_new(wc->gtkWindow->window, pw, ph, -1); \ + style = GtkTtk_GetGtkWindowStyle(wc->gtkWindow); + +#define GTKTTK_STYLE_BACKGROUND_DEFAULT \ + if (wc && wc->gtkWindow) style = GtkTtk_GetGtkWindowStyle(wc->gtkWindow); \ + if (!style) return; + +#define GTKTTK_STYLE_FROM_WIDGET \ + style = GtkTtk_GetGtkWindowStyle(widget); \ + if (!style) style = GtkTtk_GetGtkWindowStyle(wc->gtkWindow); \ + if (!style) return; + +#define GTKTTK_DRAWABLE_FROM_WIDGET_SIZE(pw, ph) \ + gdkDrawable = GtkTtk_gdk_pixmap_new(widget->window, pw, ph, -1); + +#define GTKTTK_DRAWABLE_FROM_WIDGET \ + GTKTTK_DRAWABLE_FROM_WIDGET_SIZE(b.width, b.height) + +// #define GTKTTK_DRAWABLE_FROM_WIDGET \ +// gdkDrawable = gdk_pixmap_foreign_new(Tk_WindowId(tkwin)); \ +// GdkColormap gdkColormap = gdk_x11_colormap_foreign_new(gdkx_visual_get(Tk_Visual(tkwin)), Tk_Colormap(tkwin)); \ +// gdk_drawable_set_colormap(gdkDrawable, gdkColormap); + +#define GTKTTK_DEFAULT_BACKGROUND_SIZE(pw, ph) \ + GtkTtk_gtk_style_apply_default_background(style, gdkDrawable, TRUE, \ + gtkState, NULL, 0, 0, pw, ph); + +#define GTKTTK_DEFAULT_BACKGROUND \ + GTKTTK_DEFAULT_BACKGROUND_SIZE(b.width, b.height) + +#define GTKTTK_CLEANUP_GTK_DRAWABLE \ + if (gdkDrawable) GtkTtk_g_object_unref(gdkDrawable); + +#define GTKTTK_SETUP_STATE_SHADOW(statemap, shadowmap) \ + gtkState = (GtkStateType) \ + GtkTtk_StateTableLookup(statemap, state); \ + gtkShadow = (GtkShadowType) \ + GtkTtk_StateTableLookup(shadowmap, state); + +#define GTKTTK_SETUP_WIDGET_SIZE(width, height) \ + GtkTtk_gtk_widget_set_size_request(widget, width, height); + +#define GTKTTK_GET_WIDGET_SIZE(widthPtr, heightPtr) \ + if (widget) { \ + GtkRequisition size; \ + GtkTtk_gtk_widget_size_request(widget, &size); \ + widthPtr = size.width; \ + heightPtr = size.height; \ + } + +#define GTKTTK_WIDGET_SETUP_DEFAULT(obj) \ + int defaultState = TTK_BUTTON_DEFAULT_DISABLED; \ + int has_default = (defaultState == TTK_BUTTON_DEFAULT_ACTIVE); \ + /*Ttk_GetButtonDefaultStateFromObj(NULL, obj, &defaultState);*/ + +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY + +#define GTKTTK_WIDGET_SET_FOCUS(widget) + +#define GTKTTK_WIDGET_SET_DEFAULT(widget, obj) \ + int defaultState = TTK_BUTTON_DEFAULT_DISABLED; \ + int has_default = (defaultState == TTK_BUTTON_DEFAULT_ACTIVE); + +#else /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + +#define GTKTTK_WIDGET_SET_FOCUS(widget) \ + if (state & TTK_STATE_FOCUS) { \ + GTK_WIDGET_SET_FLAGS(widget, GTK_HAS_FOCUS); \ + } else { \ + GTK_WIDGET_UNSET_FLAGS(widget, GTK_HAS_FOCUS); \ + } + +#define GTKTTK_WIDGET_SET_DEFAULT(widget, obj) \ + int defaultState = TTK_BUTTON_DEFAULT_DISABLED; \ + int has_default = (defaultState == TTK_BUTTON_DEFAULT_ACTIVE); \ + /*Ttk_GetButtonDefaultStateFromObj(NULL, obj, &defaultState);*/ \ + if (has_default) { \ + GTK_WIDGET_SET_FLAGS(widget, GTK_HAS_DEFAULT); \ + } else { \ + GTK_WIDGET_UNSET_FLAGS(widget, GTK_HAS_DEFAULT); \ + } +#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + +#define GTKTTK_DEBUG_PRINT_BOX \ + printf("x=%d, y=%d, w=%d, h=%d\n", b.x, b.y, b.width, b.height); \ + fflush(0); + +#define GTKTTK_DEBUG_PRINT_TK_WIDGET \ + printf("Widget: %s,p=%p\n", Tk_PathName(tkwin), tkwin); \ + fflush(0); + +#define GTKTTK_GTKBORDER_TO_PADDING(border) \ + Ttk_MakePadding(border.left, border.top, border.right, border.bottom) + +TCL_DECLARE_MUTEX(gtkTtkMutex); + +/* Global Symbols */ + +/* Helper Functions */ +extern int GtkTtk_GtkInitialised(void); +extern GtkWidget *GtkTtk_GetGtkWindow(void); +extern GtkStyle *GtkTtk_GetGtkWindowStyle(GtkWidget *gtkWindow); +extern GtkStyle *GtkTtk_GetGtkStyle(void); + +extern unsigned int GtkTtk_StateTableLookup(Ttk_StateTable *, unsigned int); +extern void GtkTtk_CopyGtkPixmapOnToDrawable(GdkPixmap *, Drawable, Tk_Window, + int, int, int, int, int, int); +extern void GtkTtk_StateInfo(int, GtkStateType, + GtkShadowType, Tk_Window, GtkWidget *widget = NULL); + +extern GtkWidget *GtkTtk_GetArrow(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetButton(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetCheckButton(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetRadioButton(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetToolBar(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetToolButton(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetFrame(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetEntry(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetCombobox(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetComboboxEntry(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetHScrollBar(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetVScrollBar(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetScrollBar(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetHScale(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetVScale(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetScale(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetHProgressBar(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetVProgressBar(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetProgressBar(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetStatusBar(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetPaned(GtkTtk_WidgetCache* wc); +extern GtkWidget *GtkTtk_GetNotebook(GtkTtk_WidgetCache* wc); +#if 0 +extern void GtkTtk_StoreStyleNameLowers(GtkTtk_WidgetCache *wc); +extern bool GtkTtk_ThemeIs(GtkTtk_WidgetCache *wc, const char* name); +extern void GtkTtk_SetFocus(bool focus); +#endif + +extern unsigned int GtkTtk_StateShadowTableLookup(GtkTtk_StateTable*, + unsigned int, GtkStateType&, GtkShadowType&, + unsigned int section = GTKTTK_SECTION_ALL); +extern double GtkTtk_ValueFromSlider(GtkTtk_WidgetCache *wc, Tk_Window tkwin, + Ttk_Box b); +extern double GtkTtk_GetDpiScale(Tk_Window tkwin); +extern int GtkTtk_ScalePx(Tk_Window tkwin, int base_px); diff --git a/src/gtkTtk/generic/gtkTtk_WidgetDefaults.h b/src/gtkTtk/generic/gtkTtk_WidgetDefaults.h new file mode 100644 index 0000000..5d1b688 --- /dev/null +++ b/src/gtkTtk/generic/gtkTtk_WidgetDefaults.h @@ -0,0 +1,33 @@ +/* + * gtkTtk_WidgetDefaults.h + * ------------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#define DEFAULT_BORDERWIDTH "2" +#define DEFAULT_ARROW_SIZE "15" +#define MIN_THUMB_SIZE 14 +#define BorderBorderWidth "0" +#define PushButtonUniformPadding 3 +#define PushButtonUniformPaddingDefaulted 5 +#define RadioButtonHorizontalPadding 0 +#define CheckButtonHorizontalPadding 0 +#define EntryUniformPadding 0 +#define ComboboxHorizontalPadding 0 +#define LabelframeUniformPadding 4 +#define NotebookUniformPadding 4 +#define NotebookClientUniformPadding 4 +#define TreeViewUniformPadding 4 +#define PanedUniformPadding 0 +#define ScrollbarThumbMinimumLen 2 +#define ScaleThumbMinimumLen 2 +#define ProgressBarThumbSize MIN_THUMB_SIZE diff --git a/src/gtkTtk/generic/tileGtk_Symbols.cpp b/src/gtkTtk/generic/tileGtk_Symbols.cpp new file mode 100644 index 0000000..3f62d77 --- /dev/null +++ b/src/gtkTtk/generic/tileGtk_Symbols.cpp @@ -0,0 +1,61 @@ +/* + * tileGtk_Symbols.cpp + * ------------------------ + * + * This file is part of the Tile-Gtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2012 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ +/* THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT! */ +#include "tileGtk_Symbols.h" +#ifdef TILEGTK_LOAD_GTK_DYNAMICALLY +#if (TCL_MAJOR_VERSION >= 8) && (TCL_MINOR_VERSION >= 6) +#define LOAD_SYMBOLS_WITH_TCL +#endif + +#ifndef LOAD_SYMBOLS_WITH_TCL +#include +#endif + +Ptr_g_malloc TileGtk_g_malloc = 0; +Ptr_g_malloc0 TileGtk_g_malloc0 = 0; + +int TileGtk_InitialiseSymbols_glib(Tcl_Interp *interp, Tcl_Obj *file_name) { +#ifdef LOAD_SYMBOLS_WITH_TCL + Tcl_LoadHandle loadHandle; + int status; + status = Tcl_LoadFile(interp, file_name, NULL, 0, NULL, &loadHandle); + if (status != TCL_OK) return status; + TileGtk_g_malloc = (Ptr_g_malloc) Tcl_FindSymbol(interp, loadHandle, "g_malloc"); + if (TileGtk_g_malloc == NULL) return TCL_ERROR; + TileGtk_g_malloc0 = (Ptr_g_malloc0) Tcl_FindSymbol(interp, loadHandle, "g_malloc0"); + if (TileGtk_g_malloc0 == NULL) return TCL_ERROR; +#else + const char *fname = Tcl_GetString(file_name); + GModule *m = g_module_open(fname, G_MODULE_BIND_LAZY); + if (!m) { + Tcl_SetResult(interp, (char *) "cannot open module: ", TCL_STATIC); + Tcl_AppendResult(interp, fname, (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_malloc", (gpointer *) &TileGtk_g_malloc)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_malloc", (char *) NULL); + return TCL_ERROR; + } + if (!g_module_symbol(m, "g_malloc0", (gpointer *) &TileGtk_g_malloc0)) { + Tcl_SetResult(interp, (char *) "cannot find symbol: ", TCL_STATIC); + Tcl_AppendResult(interp, (char *) "g_malloc0", (char *) NULL); + return TCL_ERROR; + } +#endif + return TCL_OK; +}; /* TileGtk_InitialiseSymbols_glib */ + +#endif /* TILEGTK_LOAD_GTK_DYNAMICALLY */ diff --git a/src/gtkTtk/generic/tileGtk_Symbols.h b/src/gtkTtk/generic/tileGtk_Symbols.h new file mode 100644 index 0000000..a748456 --- /dev/null +++ b/src/gtkTtk/generic/tileGtk_Symbols.h @@ -0,0 +1,52 @@ +/* + * tileGtk_Symbols.h + * -------------------- + * + * This file is part of the Tile-Gtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2012 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ +/* THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT! */ +#ifndef _TILEGTK_SYMBOLS +#define _TILEGTK_SYMBOLS +#include "tcl.h" +#ifdef LOAD_SYMBOLS_WITH_TCL +#else +#include +#endif +#include +#include +#include +#ifndef __WIN32__ +#include +#include +#else +#include +#endif + +#ifdef TILEGTK_LOAD_GTK_DYNAMICALLY +extern "C" { + typedef gpointer (*Ptr_g_malloc)(gsize n_bytes); + extern Ptr_g_malloc TileGtk_g_malloc; + typedef gpointer (*Ptr_g_malloc0)(gsize n_bytes); + extern Ptr_g_malloc0 TileGtk_g_malloc0; +} + +extern int TileGtk_InitialiseSymbols_glib(Tcl_Interp *interp, Tcl_Obj *file_name); +#define TILEGTK_LAST_SYMBOL_glib TileGtk_g_malloc0 + +#else /* TILEGTK_LOAD_GTK_DYNAMICALLY */ + +#define TileGtk_g_malloc \ + g_malloc +#define TileGtk_g_malloc0 \ + g_malloc0 +#endif /* TILEGTK_LOAD_GTK_DYNAMICALLY */ + +#endif /* _TILEGTK_SYMBOLS */ diff --git a/src/gtkTtk/generic/tkMacros.h b/src/gtkTtk/generic/tkMacros.h new file mode 100644 index 0000000..3f548da --- /dev/null +++ b/src/gtkTtk/generic/tkMacros.h @@ -0,0 +1,76 @@ +/* + * tkMacros.h + * ---------------------- + * + * This file is part of the gtkTtk package, a Tk/Tile based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2008 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ + +#ifndef __GTKTTK_TK_MACROS +#define __GTKTTK_TK_MACROS + +typedef struct { + long flags; + Bool input; + int initial_state; + Pixmap icon_pixmap; + Window icon_window; + int icon_x, icon_y; + Pixmap icon_mask; + XID window_group; +} XWMHints; + +typedef struct Tk_FakeWmInfo { + Tk_FakeWin *winPtr; /* Pointer to main Tk information for + * this window. */ + Window reparent; /* If the window has been reparented, this + * gives the ID of the ancestor of the window + * that is a child of the root window (may + * not be window's immediate parent). If + * the window isn't reparented, this has the + * value None. */ + char *title; /* Title to display in window caption. If + * NULL, use name of widget. Malloced. */ + char *iconName; /* Name to display in icon. Malloced. */ + XWMHints hints; /* Various pieces of information for + * window manager. */ + char *leaderName; /* Path name of leader of window group + * (corresponds to hints.window_group). + * Malloc-ed. Note: this field doesn't + * get updated if leader is destroyed. */ + Tk_FakeWin *masterPtr; /* Master window for TRANSIENT_FOR property, + * or NULL. */ + Tk_Window icon; /* Window to use as icon for this window, + * or NULL. */ + Tk_Window iconFor; /* Window for which this window is icon, or + * NULL if this isn't an icon for anyone. */ + int withdrawn; /* Non-zero means window has been withdrawn. */ + + /* + * In order to support menubars transparently under X, each toplevel + * window is encased in an additional window, called the wrapper, + * that holds the toplevel and the menubar, if any. The information + * below is used to keep track of the wrapper and the menubar. + */ + + Tk_FakeWin *wrapperPtr; /* Pointer to information about the wrapper. + * This is the "real" toplevel window as + * seen by the window manager. Although + * this is an official Tk window, it + * doesn't appear in the application's + * window hierarchy. NULL means that + * the wrapper hasn't been created yet. */ +} Tk_FakeWmInfo; + + + +#define Tk_RealToplevelWindow(tkwin) ((((Tk_FakeWmInfo *) (((Tk_FakeWin *) (tkwin))->dummy16))->wrapperPtr)->window) + +#endif /* __GTKTTK_TK_MACROS */ diff --git a/src/gtkTtk/library/GenarateSymbols.tcl b/src/gtkTtk/library/GenarateSymbols.tcl new file mode 100644 index 0000000..ebe1af9 --- /dev/null +++ b/src/gtkTtk/library/GenarateSymbols.tcl @@ -0,0 +1,536 @@ +## +## Function to return the containing lib of a symbol +## +proc symbol2lib {s} { + switch -glob $s { + gdk_pixbuf_get_from_drawable {return gdk} + gtk_* {return gtk} + g_object_* {return gobject} + g_* {return glib} + xlib_rgb_init - + gdk_pixbuf_xlib_* {return gdk_pixbuf_xlib} + gdk_pixbuf_* {return gdk_pixbuf} + gdk_* {return gdk} + xlib_* {return xlib} + default { + puts $s + } + } + return unknown +};# symbol2lib + +## +## Function name to return type/arguments map. +## +proc get_function_spec {f} { + set t {}; set a {} + switch -glob $f { + g_free { + set a {gpointer mem} + } + g_hash_table_get_keys { + set t {GList*} + set a {GHashTable *hash_table} + } + g_malloc { + set t {gpointer} + set a {gsize n_bytes} + } + g_malloc0 { + set t {gpointer} + set a {gsize n_bytes} + } + g_new0 { + set t {} + set a {} + puts "FIXME: $f" + } + g_object_get { + set a {gpointer object, const gchar *first_property_name, ...} + } + g_object_ref { + set a {gpointer object} + } + g_object_unref { + set a {gpointer object} + } + g_option_context_add_main_entries { + set a {GOptionContext *context, const GOptionEntry *entries, const gchar *translation_domain} + } + g_option_context_new { + set t {GOptionContext*} + set a {const gchar *parameter_string} + } + g_strfreev { + set a {gchar **str_array} + } + gdk_color_to_string { + set t {gchar*} + set a {const GdkColor *color} + } + gdk_display_get_default { + set t {GdkDisplay*} + } + gdk_display_get_screen { + set t {GdkScreen*} + set a {GdkDisplay*, gint} + } + gdk_drawable_unref { + set a {GdkDrawable *drawable} + } + gdk_drawable_get_colormap { + set t {GdkColormap*} + set a {GdkDrawable *drawable} + } + gdk_drawable_set_colormap { + set a {GdkColormap*} + } + gdk_pixmap_foreign_new { + set t {GdkPixmap*} + set a {GdkNativeWindow anid} + } + gdk_pixmap_foreign_new_for_screen { + set t {GdkPixmap*} + set a {GdkScreen *screen, GdkNativeWindow anid, gint width, gint height, gint depth} + } + gdk_gc_new { + set t {GdkGC*} + set a {GdkDrawable *drawable} + } + gdk_pixbuf_get_from_drawable { + set t {GdkPixbuf*} + set a {GdkPixbuf *dest, GdkDrawable *src, GdkColormap *cmap, int src_x, int src_y, int dest_x, int dest_y, int width, int height} + } + gdk_pixbuf_new { + set t {GdkPixbuf*} + set a {GdkColorspace colorspace, gboolean has_alpha, int bits_per_sample, int width, int height} + } + gdk_pixbuf_unref { + set a {GdkPixbuf *pixbuf} + } + gdk_pixbuf_xlib_render_to_drawable { + set a {GdkPixbuf *pixbuf, Drawable drawable, GC gc, int src_x, int src_y, int dest_x, int dest_y, int width, int height, XlibRgbDither dither, int x_dither, int y_dither} + } + gdk_pixmap_new { + set t {GdkPixmap*} + set a {GdkDrawable *drawable, gint width, gint height, gint depth} + } + gdk_pixmap_foreign_new_for_display { + set t {GdkPixmap*} + set a {GdkDisplay *display, GdkNativeWindow anid} + } + gdk_win32_hdc_get { + set t {HDC} + set a {GdkDrawable *drawable, GdkGC *gc, GdkGCValuesMask usage} + } + gdk_win32_hdc_release { + set a {GdkDrawable *drawable, GdkGC *gc, GdkGCValuesMask usage} + } + gdk_x11_colormap_foreign_new { + set t {GdkColormap*} + set a {GdkVisual *visual, Colormap xcolormap} + } + gdk_x11_lookup_xdisplay { + set t {GdkDisplay*} + set a {Display *xdisplay} + } + gdk_x11_screen_lookup_visual { + set t {GdkVisual*} + set a {GdkScreen *screen, VisualID xvisualid} + } + xlib_rgb_init { + set a {Display *display, Screen *screen} + } + gtk_adjustment_new { + set t {GtkObject*} + set a {double, double, double, double, double, double} + } + gtk_adjustment_set_value { + set a {GtkAdjustment *adjustment, gdouble value} + } + gtk_arrow_new { + set a {GtkArrowType at, GtkShadowType st} + set t {GtkWidget*} + } + gtk_tool_button_new { + set t {GtkToolItem*} + set a {GtkWidget *icon_widget, const gchar *label} + } + gtk_vpaned_new - + gtk_toolbar_new - + gtk_statusbar_new - + gtk_progress_bar_new - + gtk_notebook_new - + gtk_hpaned_new - + gtk_fixed_new - + gtk_entry_new - + gtk_combo_box_new - + gtk_combo_box_entry_new - + gtk_check_button_new - + gtk_button_new { + set t {GtkWidget*} + } + gtk_button_get_relief { + set t {GtkReliefStyle} + set a {GtkButton *button} + } + gtk_button_set_relief { + set t {} + set a {GtkButton *button, GtkReliefStyle newstyle} + } + gtk_border_free { + set a {GtkBorder*} + } + gtk_container_add { + set a {GtkContainer *container, GtkWidget *widget} + } + gtk_disable_setlocale { + } + gtk_frame_new { + set t {GtkWidget*} + set a {const gchar *label} + } + gtk_hscale_new_with_range { + set t {GtkWidget*} + set a {gdouble min, gdouble max, gdouble step} + } + gtk_hscrollbar_new { + set t {GtkWidget*} + set a {GtkAdjustment *} + } + gtk_init_check { + set t {gboolean} + set a {int *argc, char ***argv} + } + gtk_object_get { + set a {GtkObject *object, const gchar *first_property_name, ...} + } + gtk_paint_arrow { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, GtkArrowType, gboolean, gint , gint , gint , gint} + } + gtk_paint_box { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint} + } + gtk_paint_box_gap { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint, gint, gint , gint, GtkPositionType, gint gap_x, gint gap_width} + } + gtk_paint_check { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint} + } + gtk_paint_extension { + set a {GtkStyle *, GdkWindow *, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint, gint, gint, gint, GtkPositionType} + } + gtk_paint_flat_box { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint} + } + gtk_paint_focus { + set a {GtkStyle *style, GdkWindow *window, GtkStateType state_type, GdkRectangle *area, GtkWidget *widget, const gchar *detail, gint x, gint y, gint width, gint height} + } + gtk_paint_handle { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint, GtkOrientation} + } + gtk_paint_option { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint} + } + gtk_paint_resize_grip { + set a {GtkStyle*,GdkWindow*, GtkStateType, const GdkRectangle *, GtkWidget *, const gchar *, GdkWindowEdge, gint , gint , gint , gint} + } + gtk_paint_shadow { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint} + } + gtk_paint_slider { + set a {GtkStyle*,GdkWindow*, GtkStateType, GtkShadowType, const GdkRectangle *, GtkWidget *, const gchar *, gint , gint , gint , gint, GtkOrientation} + } + gtk_progress_bar_set_bar_style { + set a {GtkProgressBar *pbar, GtkProgressBarStyle style} + } + gtk_progress_bar_set_fraction { + set a {GtkProgressBar *pbar, gdouble fraction} + } + gtk_progress_bar_set_orientation { + set a {GtkProgressBar *pbar, GtkProgressBarOrientation orientation} + } + gtk_range_get_adjustment { + set t {GtkAdjustment *} + set a {GtkRange *range} + } + gtk_rc_get_default_files { + set t {gchar**} + } + gtk_rc_get_style { + set t {GtkStyle *} + set a {GtkWidget*} + } + gtk_rc_get_theme_dir { + set t {gchar*} + } + gtk_rc_reparse_all_for_settings { + set t {gboolean} + set a {GtkSettings *settings, gboolean force_load} + } + gtk_rc_reset_styles { + set a {GtkSettings *settings} + } + gtk_rc_set_default_files { + set a {gchar **filenames} + } + gtk_set_locale { + set t {gchar*} + } + gtk_settings_get_default { + set t {GtkSettings *} + } + gtk_style_apply_default_background { + set a {GtkStyle *style, GdkWindow *window, gboolean set_bg, GtkStateType state_type, GdkRectangle *area, gint x, gint y, gint width, gint height} + } + gtk_style_attach { + set t {GtkStyle*} + set a {GtkStyle *, GdkWindow *} + } + gtk_style_lookup_color { + set t {gboolean} + set a {GtkStyle *style, const gchar *color_name, GdkColor *color} + } + gtk_vscrollbar_new { + set t {GtkWidget*} + set a {GtkAdjustment *} + } + gtk_vscale_new_with_range { + set t {GtkWidget*} + set a {gdouble min, gdouble max, gdouble step} + } + gtk_widget_realize - + gtk_widget_destroy { + set a {GtkWidget *} + } + gtk_widget_set_size_request { + set a {GtkWidget *widget, gint width, gint height} + } + gtk_widget_size_request { + set a {GtkWidget *widget, GtkRequisition *requisition} + } + gtk_widget_style_get { + set a {GtkWidget *, const gchar *first_property_name, ...} + } + gdk_window_destroy { + set a {(GdkWindow *} + } + gdk_window_foreign_new { + set t {GdkWindow*} + set a {GdkNativeWindow} + } + gtk_window_new { + set t {GtkWidget*} + set a {GtkWindowType} + } + default { + puts " $f \{\n set t {}\n set a {}\n \}" + } + } + if {![string length $t]} {set t void} + if {![string length $a]} {set a void} + return [list $t $a] +};# get_function_spec + +set HomeDir [file dirname [file normalize [info script]]] + +set sources [file dirname $HomeDir]/generic + +## +## Force the following symbols to exist! +## +foreach s {g_malloc0 g_malloc} { + set Symbols(GtkTtk_$s) 1 +} + +proc process {data} { + global Symbols + set skip {[^)(\",=]+} + foreach lib {gtk gdk xlib g} { + foreach s [regexp -inline -all "GtkTtk_${lib}_${skip}\\\s*\\\(" $data] { + set Symbols([string trim $s { ()}]) 1 + } + } +} + +foreach file [lsort [glob -directory $sources -type f *]] { + if {[string match *gtkTtk_Symbols* $file ]} continue + set fd [open $file] + fconfigure $fd -encoding utf-8 + set data [read $fd] + close $fd + process $data +} + +## Remove definitions... +foreach s {g_new0} { + unset -nocomplain Symbols(GtkTtk_$s) +} + +switch $::tcl_platform(platform) { + windows { + set not_native {gdk_pixbuf_xlib_render_to_drawable xlib_rgb_init + gdk_x11_lookup_xdisplay} + } + unix { + set not_native {gdk_win32_hdc_get gdk_win32_hdc_release} + } + default { + } +} +foreach s $not_native { + unset -nocomplain Symbols(GtkTtk_$s) +} + +## +## Generate file gtkTtk_Symbols.cpp +## +set fc [open $sources/gtkTtk_Symbols.cpp w] +fconfigure $fc -encoding iso8859-1 +puts $fc \ +{/* + * gtkTtk_Symbols.cpp + * ------------------------ + * + * This file is part of the GtkTtk package, a ttk based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2012 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ +/* THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT! */ +#include "gtkTtk_Symbols.h" +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY +#if (TCL_MAJOR_VERSION >= 8) && (TCL_MINOR_VERSION >= 6) +#define LOAD_SYMBOLS_WITH_TCL +#endif + +#ifndef LOAD_SYMBOLS_WITH_TCL +#include +#endif +} + +## +## Generate file gtkTtk_Symbols.h +## + +set fd [open $sources/gtkTtk_Symbols.h w] +fconfigure $fd -encoding iso8859-1 +puts $fd \ +{/* + * gtkTtk_Symbols.h + * -------------------- + * + * This file is part of the GtkTtk package, a ttk based theme that uses + * Gtk/GNOME for drawing. + * + * Copyright (C) 2004-2012 by: + * Georgios Petasis, petasis@iit.demokritos.gr, + * Software and Knowledge Engineering Laboratory, + * Institute of Informatics and Telecommunications, + * National Centre for Scientific Research (NCSR) "Demokritos", + * Aghia Paraskevi, 153 10, Athens, Greece. + */ +/* THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT! */ +#ifndef _GTKTTK_SYMBOLS +#define _GTKTTK_SYMBOLS +#include "tcl.h" +#ifdef LOAD_SYMBOLS_WITH_TCL +#else +#include +#endif +#include +#include +#include +#ifndef __WIN32__ +#include +#include +#else +#include +#endif + +#ifdef GTKTTK_LOAD_GTK_DYNAMICALLY} +puts $fd "extern \"C\" \{" + +if {1} { + foreach symbol [lsort -dictionary [array names Symbols]] { + set gtk_s [string range $symbol 7 end] + set lib [symbol2lib $gtk_s] + foreach {t a} [get_function_spec $gtk_s] {break} + puts $fd " typedef $t (*Ptr_$gtk_s)($a);" + puts $fd " extern Ptr_$gtk_s $symbol;" + puts $fc "Ptr_$gtk_s $symbol = 0;" + lappend GTKSymbols($lib) $gtk_s; + #puts $fd "/*\n * $symbol: Stub for [string range $symbol 7 end]\n */" + #puts $fd "${symbol}() {\n GTKTTK_ENSURE\n}; /* $symbol */\n" + } +} + +puts $fd "\}\n" + +proc initialise_lib {lib} { + global fc fd GTKSymbols + puts $fd "extern int\ + GtkTtk_InitialiseSymbols_${lib}(Tcl_Interp *interp, Tcl_Obj *file_name);" + puts $fc "\nint\ + GtkTtk_InitialiseSymbols_${lib}(Tcl_Interp *interp, Tcl_Obj *file_name) \{" + puts $fc "#ifdef LOAD_SYMBOLS_WITH_TCL" + puts $fc " Tcl_LoadHandle loadHandle;" + puts $fc " int status;" + puts $fc " status = Tcl_LoadFile(interp, file_name, NULL, 0, NULL, &loadHandle);" + puts $fc " if (status != TCL_OK) return status;" + foreach s $GTKSymbols($lib) { + puts $fc " GtkTtk_$s = (Ptr_$s) Tcl_FindSymbol(interp, loadHandle, \"$s\");" + puts $fc " if (GtkTtk_$s == NULL) return TCL_ERROR;" + } + puts $fc "#else" + puts $fc " const char *fname = Tcl_GetString(file_name);" + puts $fc " GModule *m = g_module_open(fname, G_MODULE_BIND_LAZY);" + puts $fc " if (!m) {" + puts $fc " Tcl_SetResult(interp, (char *) \"cannot open module: \", TCL_STATIC);" + puts $fc " Tcl_AppendResult(interp, fname, (char *) NULL);" + puts $fc " return TCL_ERROR;" + puts $fc " }" + foreach s $GTKSymbols($lib) { + puts $fc " if (!g_module_symbol(m, \"$s\", (gpointer *) &GtkTtk_$s)) {" + puts $fc " Tcl_SetResult(interp, (char *) \"cannot find symbol: \", TCL_STATIC);" + puts $fc " Tcl_AppendResult(interp, (char *) \"$s\", (char *) NULL);" + puts $fc " return TCL_ERROR;" + puts $fc " }" + } + puts $fc "#endif" + puts $fc " return TCL_OK;\n\}; /* GtkTtk_InitialiseSymbols_${lib} */\n" + puts $fd "#define GTKTTK_LAST_SYMBOL_$lib GtkTtk_$s" +};# initialise_lib +foreach lib [lsort [array names GTKSymbols]] { + initialise_lib $lib +} + + +puts $fd { +#else /* GTKTTK_LOAD_GTK_DYNAMICALLY */ +} + +## +## Definitions for linking with GTK... +## +if {1} { + foreach symbol [lsort -dictionary [array names Symbols]] { + puts $fd "#define $symbol \\\n \ + [string range $symbol 7 end]" + } +} + +puts $fd \ +{#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */ + +#endif /* _GTKTTK_SYMBOLS */} +close $fd + +puts $fc \ +{#endif /* GTKTTK_LOAD_GTK_DYNAMICALLY */} +close $fc diff --git a/src/gtkTtk/library/gtkTtk.tcl b/src/gtkTtk/library/gtkTtk.tcl new file mode 100644 index 0000000..2a08ab0 --- /dev/null +++ b/src/gtkTtk/library/gtkTtk.tcl @@ -0,0 +1,1127 @@ +namespace eval ttk::theme::gtkTtk { + variable PreviewInterp {} + variable System + variable StyleToRc + + proc loadLibraries {args} { + if {![initialiseLibrary required]} {return} + package require platform + set libs {gdk gdk_pixbuf glib gobject gtk} + switch -glob [::platform::generic] { + *_64 { + set paths { + /usr/lib64 /usr/lib /usr/local/lib /usr/pkg/lib /usr/X11R6/lib /opt/gnome/lib /usr/openwin/lib /usr/lib/x86_64-linux-gnu /usr/lib/aarch64-linux-gnu + } + } + default { + set paths { + /usr/lib /usr/local/lib /usr/pkg/lib /usr/X11R6/lib /opt/gnome/lib /usr/openwin/lib + } + } + } + set ext [info sharedlibextension] + switch $::tcl_platform(platform) { + windows { + set sep \; + set prefixes {{} lib} + set names {-win32-2.0* -2.0* 20* -win32* * {}} + } + unix { + set sep : + set prefixes {lib} + set names {-x11-2.0 -2.0 20 -x11 {}} + lappend libs gdk_pixbuf_xlib + } + default {} + } + if {[info exists ::env(LD_LIBRARY_PATH)]} { + foreach path [split $::env(LD_LIBRARY_PATH) $sep] { + set path [string trim $path] + if {[string length $path] && [file isdirectory $path]} { + lappend paths $path + } + } + } + if {[info exists ::env(ProgramFiles)]} { + foreach path [glob -nocomplain -dir $::env(ProgramFiles) *gtk*] { + set path $path/bin + if {[file isdirectory $path]} { + lappend paths [file normalize $path] + } + } + } + set loaded 0 + foreach lib $libs { + set found 0 + foreach name $names { + foreach prefix $prefixes { + foreach path $paths { + if {$found} {break} + if {![file isdirectory $path]} {continue} + foreach file [glob -nocomplain -dir $path -type f \ + ${prefix}${lib}${name}$ext] { + if {$found} {break} + if {[file exists $file]} { + if {[catch {initialiseLibrary $lib $file} symbol]} { + puts " => ERROR while initialising library $lib from $file : $symbol" + } else { + incr loaded; set found 1 + break + } + };# if {[file exists $file]} + };# foreach file ... + };# foreach prefix $prefixes + };# foreach name $names + } + } + if {$loaded != [llength $libs]} { + error "Not all symbols loaded!" + } + };# loadLibraries + + proc getSystemInfo {} { + global env + variable System + + set System(HOME) {} + foreach var {HOME} { + if {[info exists env($var)]} { + set System($var) [file normalize $env($var)] + break + } + } + + set System(GTK_RC_FILES) {} + if {[info exists env(GTK_RC_FILES)]} { + set System(GTK_RC_FILES) [file normalize $env(GTK_RC_FILES)] + } elseif {[info exists env(HOME)]} { + foreach rc [glob -nocomplain -dir $System(HOME) -type f .gtkrc*] { + lappend System(GTK_RC_FILES) $rc + } + set System(GTK_RC_FILES) [lsort -dictionary $System(GTK_RC_FILES)] + } + + set System(TEMP) {} + foreach var {TEMP TMP temp tmp} { + if {[info exists env($var)]} { + set System(TEMP) [file normalize $env($var)] + break + } + } + if {![string length $System(TEMP)]} { + foreach dir {/tmp} { + if {[file isdirectory $dir] && [file writable $dir]} { + set System(TEMP) $dir; break + } + } + } + + set System(DEFAULT_FILES) [gtkDirectory default_files] + };# getSystemInfo + + ## availableStyles_AsReturned: + # Returns the available styles... + proc availableStyles_AsReturned {} { + variable StyleToRc + variable System + set styles {} + foreach dir [list $System(HOME)/.themes [gtkDirectory theme]] { + foreach theme [glob -nocomplain -type d -directory $dir *] { + if {[file exists $theme/gtk-2.0/gtkrc]} { + set style [file tail $theme] + lappend styles $style + set StyleToRc($style) [file normalize $theme/gtk-2.0/gtkrc] + } + } + } + return $styles + };# availableStyles_AsReturned + + proc updateLayouts {} { + ## Variable "theme" should be defined by the C part of the extension. + variable theme + variable GtkHScrollbar + variable GtkVScrollbar + if {![info exists theme]} {return} + ttk::style theme use gtkTtk + # puts "============================================================" + # puts "Current Gtk Theme: [currentThemeName] ($theme)" + # puts "Tab alignment: [getStyleHint -SH_TabBar_Alignment]" + # puts "Tab base overlap: [getPixelMetric -PM_TabBarBaseOverlap]" + # puts "Tab overlap: [getPixelMetric -PM_TabBarTabOverlap]" + # foreach sc {SC_ScrollBarAddLine SC_ScrollBarSubLine + # SC_ScrollBarAddPage SC_ScrollBarSubPage + # SC_ScrollBarFirst SC_ScrollBarLast + # SC_ScrollBarSlider SC_ScrollBarGroove} { + # foreach {x y w h} [getSubControlMetrics -$sc] {break} + # puts "$sc: x=$x, y=$y, w=$w, h=$h" + # } + ## + ## Update the scrollbars layouts, according to information retrieved from + ## the GTK style in use... + ## + ## has-backward-stepper: Display the standard backward arrow + ## button. + ## has-forward-stepper: Display the standard forward arrow + ## button. + ## has-secondary-backward-stepper: Display a second backward arrow button + ## on the opposite end of the scrollbar. + ## has-secondary-forward-stepper: Display a second forward arrow button + ## on the opposite end of the scrollbar. + foreach widget {GtkHScrollbar GtkVScrollbar} { + foreach p {has-backward-stepper has-forward-stepper + has-secondary-backward-stepper has-secondary-forward-stepper + trough-under-steppers trough-side-details} { + set ${widget}($p) [widgetStyleProperty $widget $p boolean] + } + foreach p {arrow-displacement-x arrow-displacement-y + slider-width stepper-size stepper-spacing trough-border} { + set ${widget}($p) [widgetStyleProperty $widget $p integer] + } + } + # parray GtkHScrollbar + # puts "============================================================" + + ## + ## Dynamically create the scrollbars layouts... + ## + set Horizontal.Scrollbar.trough [list] + if {$GtkHScrollbar(has-backward-stepper)} { + lappend Horizontal.Scrollbar.trough \ + Horizontal.Scrollbar.leftarrow -side left + } + if {$GtkHScrollbar(has-forward-stepper)} { + lappend Horizontal.Scrollbar.trough \ + Horizontal.Scrollbar.rightarrow -side right + } + if {$GtkHScrollbar(has-secondary-backward-stepper)} { + lappend Horizontal.Scrollbar.trough \ + Horizontal.Scrollbar.leftarrow -side right + } + if {$GtkHScrollbar(has-secondary-forward-stepper)} { + lappend Horizontal.Scrollbar.trough \ + Horizontal.Scrollbar.rightarrow -side left + } + lappend Horizontal.Scrollbar.trough \ + Horizontal.Scrollbar.thumb -side left -expand true -sticky we + ttk::style layout Horizontal.TScrollbar [list \ + Horizontal.Scrollbar.trough -children ${Horizontal.Scrollbar.trough}] + + set Vertical.Scrollbar.trough [list] + if {$GtkVScrollbar(has-backward-stepper)} { + lappend Vertical.Scrollbar.trough \ + Vertical.Scrollbar.uparrow -side top + } + if {$GtkVScrollbar(has-forward-stepper)} { + lappend Vertical.Scrollbar.trough \ + Vertical.Scrollbar.downarrow -side bottom + } + if {$GtkVScrollbar(has-secondary-backward-stepper)} { + lappend Vertical.Scrollbar.trough \ + Vertical.Scrollbar.uparrow -side bottom + } + if {$GtkVScrollbar(has-secondary-forward-stepper)} { + lappend Vertical.Scrollbar.trough \ + Vertical.Scrollbar.downarrow -side top + } + lappend Vertical.Scrollbar.trough \ + Vertical.Scrollbar.thumb -side top -expand true -sticky ns + ttk::style layout Vertical.TScrollbar \ + [list Vertical.Scrollbar.trough -children ${Vertical.Scrollbar.trough}] + }; # updateLayouts + + proc updateStyles {} { + syncTkClassicPaletteAndFonts + + # puts [currentThemeColourKeys] + ttk::style theme settings gtkTtk { + ttk::style configure . \ + -background [currentThemeColour bg(NORMAL)] \ + -foreground [currentThemeColour fg(NORMAL)] \ + -selectforeground [currentThemeColour fg(SELECTED)] \ + -selectbackground [currentThemeColour bg(SELECTED)] \ + -font TkDefaultFont \ + ; + + # Configuration of the ttk::Treeview + ttk::style map Treeview -foreground [list \ + active [currentThemeColour fg(ACTIVE)] \ + disabled [currentThemeColour fg(INSENSITIVE)] \ + focus [currentThemeColour fg(PRELIGHT)] \ + pressed [currentThemeColour fg(ACTIVE)] \ + selected [currentThemeColour fg(SELECTED)] \ + ] -background [list \ + active [currentThemeColour bg(ACTIVE)] \ + disabled [currentThemeColour bg(INSENSITIVE)] \ + pressed [currentThemeColour bg(ACTIVE)] \ + selected [currentThemeColour bg(SELECTED)] \ + ] + + ttk::style map Treeview.Heading -foreground [list \ + pressed [currentThemeColour bg(PRELIGHT)] \ + ] -background [list \ + pressed [currentThemeColour fg(PRELIGHT)] \ + ] + set tv_rowh [expr {[font metrics TkDefaultFont -linespace] + [spx 8]}] + ttk::style configure Treeview.Heading -relief raised \ + -font TkHeadingFont \ + -background [currentThemeColour bg(ACTIVE)] \ + -padding [list [spx 8] [spx 3] [spx 8] [spx 3]] + ttk::style configure Treeview.Item \ + -indicatormargins [list [spx 2] [spx 2] [spx 4] [spx 2]] \ + -indicatorsize [spx 9] + ttk::style configure Treeview \ + -font TkDefaultFont \ + -fieldbackground [currentThemeColour bg(INSENSITIVE)] \ + -rowheight $tv_rowh + + set base_bg [ttk::style lookup . -background] + set base_fg [ttk::style lookup . -foreground] + set text_fg [ttk::style lookup Treeview -foreground] + set select_bg [ttk::style lookup . -selectbackground] + set select_fg [ttk::style lookup . -selectforeground] + + option add *Menu.Background $base_bg + option add *Menu.Foreground $base_fg + option add *Menu.activeBackground $select_bg + option add *Menu.activeForeground $select_fg + option add *Menu.selectColor $text_fg + + ttk::style configure TButton -font TkDefaultFont -anchor center -width -11 -padding [list [spx 9] [spx 3] [spx 9] [spx 3]] + ttk::style configure TLabel -font TkDefaultFont + ttk::style configure TCheckbutton -font TkDefaultFont -padding [list [spx 5] [spx 3] [spx 5] [spx 3]] + ttk::style configure TCombobox -font TkTextFont -padding [list [spx 6] [spx 3] [spx 6] [spx 3]] + ttk::style configure TEntry -font TkTextFont -padding [list [spx 6] [spx 3] [spx 6] [spx 3]] + ttk::style configure TSpinbox -font TkTextFont -padding [list [spx 6] [spx 3] [spx 6] [spx 3]] + ttk::style configure TLabelframe -background [currentThemeColour bg(NORMAL)] -labeloutside false -padding [spx 6] + ttk::style configure TLabelframe.Label -font TkHeadingFont + ttk::style configure TMenubutton -font TkDefaultFont -width -11 -padding [list [spx 8] [spx 3] [spx 8] [spx 3]] + + ## + ## Notebook widget properties: + ## tab-pos: Which side of the notebook holds the tabs + ## tab-border: Width of the border around the tab labels + ## tab-hborder: Width of the horizontal border of tab labels + ## tab-vborder: Width of the vertical border of tab labels + ## homogeneous: Whether tabs should have homogeneous sizes + ## tab-overlap: Size of tab overlap area + ## tab-curvature: Size of tab curvature + ## arrow-spacing: Scroll arrow spacing + ## + set tab_overlap [widgetStyleProperty GtkNotebook tab-overlap integer] + set tab_curvature [widgetStyleProperty GtkNotebook tab-curvature integer] + set homogeneous [widgetProperty GtkNotebook homogeneous boolean] + set tab_pos [gtkEnum GtkPositionType \ + [widgetProperty GtkNotebook tab-pos integer]] + set tab_base_overlap 0 + switch -exact $tab_pos { + GTK_POS_TOP {set tabposition nw} + GTK_POS_BOTTOM {set tabposition sw} + GTK_POS_LEFT {set tabposition nw} + GTK_POS_RIGHT {set tabposition ne} + default {set tabposition nw} + } + ttk::style configure TNotebook -tabmargins \ + [list $tab_overlap 0 $tab_overlap $tab_base_overlap] \ + -tabposition $tabposition + ttk::style configure TNotebook.Tab -font TkDefaultFont -padding [list [spx 10] [spx 3] [spx 10] [spx 3]] + ttk::style map TNotebook.Tab -expand [list selected \ + [list $tab_overlap 0 $tab_overlap $tab_base_overlap]] + + ttk::style configure TRadiobutton -font TkDefaultFont -padding [list [spx 5] [spx 3] [spx 5] [spx 3]] + ttk::style configure Toolbutton -font TkDefaultFont -anchor center -padding [list [spx 6] [spx 3] [spx 6] [spx 3]] + + ttk::style configure TPaned -background [currentThemeColour bg(NORMAL)] + ttk::style configure Horizontal.Sash -background [currentThemeColour \ + bg(NORMAL)] + ttk::style configure Vertical.Sash -background [currentThemeColour \ + bg(NORMAL)] + };# ttk::style theme settings gtkTtk + + # puts "\nPixel Metric Information:" + # foreach pm {PM_TabBarTabOverlap PM_TabBarTabHSpace + # PM_TabBarTabVSpace PM_TabBarBaseHeight + # PM_TabBarBaseOverlap PM_TabBarTabShiftHorizontal + # PM_TabBarTabShiftVertical PM_TabBarScrollButtonWidth + # PM_DefaultFrameWidth} { + # puts "$pm: [getPixelMetric -$pm]" + # } +};# updateStyles + + ## updateColourPalette: + # This procedure will be called from gtkTtk core each time a message is + # received from KDE to change the palette used. + proc updateColourPalette {} { + return + # puts >>updateColourPalette + foreach filename [kdeLocate_kdeglobals] { + if {[file exists $filename]} { + set file [open $filename] + while {[gets $file line] != -1} { + set line [string trim $line] + switch -glob $line { + contrast=* { + if {![info exists options(-contrast)]} { + set options(-contrast) [string range $line 9 end] + } + } + background=* { + if {![info exists options(-background)]} { + set options(-background) [kdeGetColourHex $line] + } + } + foreground=* { + if {![info exists options(-foreground)]} { + set options(-foreground) [kdeGetColourHex $line] + } + } + buttonBackground=* { + if {![info exists options(-buttonBackground)]} { + set options(-buttonBackground) [kdeGetColourHex $line] + } + } + buttonForeground=* { + if {![info exists options(-buttonForeground)]} { + set options(-buttonForeground) [kdeGetColourHex $line] + } + } + selectBackground=* { + if {![info exists options(-selectBackground)]} { + set options(-selectBackground) [kdeGetColourHex $line] + } + } + selectForeground=* { + if {![info exists options(-selectForeground)]} { + set options(-selectForeground) [kdeGetColourHex $line] + } + } + windowBackground=* { + if {![info exists options(-windowBackground)]} { + set options(-windowBackground) [kdeGetColourHex $line] + } + } + windowForeground=* { + if {![info exists options(-windowForeground)]} { + set options(-windowForeground) [kdeGetColourHex $line] + } + } + linkColor=* { + if {![info exists options(-linkColor)]} { + set options(-linkColor) [kdeGetColourHex $line] + } + } + visitedLinkColor=* { + if {![info exists options(-visitedLinkColor)]} { + set options(-visitedLinkColor) [kdeGetColourHex $line] + } + } + } + } + close $file + } + } + if {[info exists options]} { + eval setPalette [array get options] + } + };# updateColourPalette + + ## kdeStyleChangeNotification: + # This procedure will be called from gtkTtk core each time a message is + # received from KDE to change the style used. + proc kdeStyleChangeNotification {} { + return + # puts >>kdeStyleChangeNotification + ## This method will be called each time a ClientMessage is received from + ## KDE KIPC... + ## Our Job is: + ## a) To get the current style from KDE, and + ## b) Apply it. + foreach filename [kdeLocate_kdeglobals] { + if {[file exists $filename]} { + set file [open $filename] + while {[gets $file line] != -1} { + set line [string trim $line] + if {[string match widgetStyle*=* $line]} { + # We have found the style! + set index [string first = $line]; incr index + set style [string range $line $index end] + if {[string length $style]} { + close $file + applyStyle $style + return + } + } + } + close $file + } + } + };# kdeStyleChangeNotification + + ## applyStyle: + # This procedure can be used to apply any available GTK+ style. + # Ths "style" parameter must be a string from the style names returned by + # ttk::theme::gtkTtk::availableStyles. + proc applyStyle {style} { + variable StyleToRc + variable System + if {![info exists StyleToRc($style)]} { + error "unknown GTK style: \"$style\"" + } + ## + ## In order to force a style update, we need to create an rc file, and force + ## GTK to load it... + ## + set rc [file normalize $System(TEMP)/gtkrc.gtkTtk-[pid]] + set fd [open $rc w] + puts $fd {# -- THEME AUTO-WRITTEN DO NOT EDIT} + puts $fd "include \"$StyleToRc($style)\"" + puts $fd "include \"$System(HOME)/.gtkrc.mine\"" + puts $fd {# -- THEME AUTO-WRITTEN DO NOT EDIT} + close $fd + ## + ## Set it as the default file... + ## + set default_files [gtkDirectory default_files] + gtkDirectory default_files [list $rc] + gtk_method gtk_rc_reparse_all_for_settings + gtk_method gtk_rc_reset_styles + #gtkDirectory default_files $default_files + puts $StyleToRc($style) + updateColourPalette + updateStyles + updateLayouts + event generate {} <> + file delete -force $rc + };# applyStyle + + ## kdePaletteChangeNotification: + # This procedure will be called from gtkTtk core each time a message is + # received from KDE to change the palette used. + proc kdePaletteChangeNotification {} { + return + # puts >>kdePaletteChangeNotification + kdeStyleChangeNotification + };# kdePaletteChangeNotification + + proc kdeGetColourHex {line} { + set index [string first = $line]; incr index + set value [string range $line $index end] + foreach {r g b} [split $value ,] {break} + return [format #%02X%02X%02X $r $g $b] + };# kdeGetColourHex + + ## createThemeConfigurationPanel: + # This method will create a configuration panel for the gtkTtk theme in the + # provided frame widget. + proc createThemeConfigurationPanel {dlgFrame} { + ## The first element in our panel, is a combobox, with all the available + ## GTK+ styles. + ttk::labelframe $dlgFrame.style_selection -text "GTK+ Style:" + ttk::combobox $dlgFrame.style_selection.style -state readonly + $dlgFrame.style_selection.style set [currentThemeName] + bind $dlgFrame.style_selection.style <> \ + {%W set [ttk::theme::gtkTtk::currentThemeName]} + bind $dlgFrame.style_selection.style \ + {%W configure -values [ttk::theme::gtkTtk::availableStyles]} + ttk::button $dlgFrame.style_selection.apply -text Apply -command \ + "ttk::theme::gtkTtk::applyStyle \[$dlgFrame.style_selection.style get\]" + grid $dlgFrame.style_selection.style $dlgFrame.style_selection.apply \ + -padx 2 -sticky snew + grid columnconfigure $dlgFrame.style_selection 0 -weight 1 + pack $dlgFrame.style_selection -fill x -expand 0 -padx 2 -pady 2 + ## The second element of our panel, is a preview area. Since tile does not + ## allow us to use a different theme for some widgets, we start a new wish + ## session through a pipe, and we embed its window in our dialog. Then, we + ## instrument this second wish through the pipe... + ttk::labelframe $dlgFrame.preview -text "Preview:" + variable PreviewInterp + if {[string length $PreviewInterp]} { + frame $dlgFrame.preview.container + pack [label $dlgFrame.preview.container.lbl \ + -text {Preview Unavailable!}] -fill both -expand 1 + } else { + frame $dlgFrame.preview.container -container 1 -height 250 -width 400 + ## Create a slave interpreter, and load gtkTtk. Widgets in this interp + ## may be of a different widget style! + set PreviewInterp [interp create] + interp eval $PreviewInterp {package require Tk} + interp eval $PreviewInterp " + wm withdraw . + set auto_path \{$::auto_path\} + if {[catch {package require Ttk}]} { + package require tile + } + ttk::setTheme gtkTtk + # package require ttk::theme::gtkTtk + ttk::theme::gtkTtk::applyStyle \{[currentThemeName]\} + toplevel .widgets -height 250 -width 400 \ + -use [winfo id $dlgFrame.preview.container] + ttk::theme::gtkTtk::selectStyleDlg_previewWidgets .widgets + " + bind $dlgFrame.preview.container \ + "ttk::theme::gtkTtk::destroyThemeConfigurationPanel" + bind $dlgFrame.style_selection.style <> \ + {ttk::theme::gtkTtk::updateThemeConfigurationPanel [%W get]} + } + pack $dlgFrame.preview.container -padx 0 -pady 0 -fill both -expand 1 + pack $dlgFrame.preview -fill both -expand 1 -padx 2 -pady 2 + };# createThemeConfigurationPanel + + proc destroyThemeConfigurationPanel {} { + variable PreviewInterp + interp delete $PreviewInterp + set PreviewInterp {} + };# destroyThemeConfigurationPanel + + proc updateThemeConfigurationPanel {style} { + variable PreviewInterp + interp eval $PreviewInterp "ttk::theme::gtkTtk::applyStyle \{$style\}" + };# updateThemeConfigurationPanel + + proc selectStyleDlg_previewWidgets {{win {}}} { + ## Create a notebook widget... + ttk::notebook $win.nb -padding 6 + set tab1 [ttk::frame $win.nb.tab1] + $win.nb add $tab1 -text "Tab 1" -underline 4 -sticky news + set tab2 [ttk::frame $win.nb.tab2] + $win.nb add $tab2 -text "Tab 2" -underline 4 -sticky news + set tab3 [ttk::frame $win.nb.tab3] + $win.nb add $tab3 -text "Tab 3" -underline 4 -sticky news + set tab4 [ttk::frame $win.nb.tab4] + $win.nb add $tab4 -text "Tab 4" -underline 4 -sticky news + ## Fill tab1... + ##################### + ttk::panedwindow $tab1.panedwindow -orient horizontal + ## Add a set of radiobuttons to the left... + ttk::labelframe $tab1.panedwindow.buttons -text " Button Group " + ttk::radiobutton $tab1.panedwindow.buttons.b1 -text "Radio button" \ + -variable ttk::theme::gtkTtk::temp(selectionVariable) -value 1 + ttk::radiobutton $tab1.panedwindow.buttons.b2 -text "Radio button" \ + -variable ttk::theme::gtkTtk::temp(selectionVariable) -value 2 + ttk::radiobutton $tab1.panedwindow.buttons.b3 -text "Radio button" \ + -variable ttk::theme::gtkTtk::temp(selectionVariable) -value 3 + ttk::separator $tab1.panedwindow.buttons.sep -orient horizontal + ttk::checkbutton $tab1.panedwindow.buttons.b4 -text "Checkbox" + $tab1.panedwindow.buttons.b4 state selected + set ttk::theme::gtkTtk::temp(selectionVariable) 1 + grid $tab1.panedwindow.buttons.b1 -sticky snew -padx 2 -pady 2 + grid $tab1.panedwindow.buttons.b2 -sticky snew -padx 2 -pady 2 + grid $tab1.panedwindow.buttons.b3 -sticky snew -padx 2 -pady 2 + grid $tab1.panedwindow.buttons.sep -sticky snew -padx 2 -pady 2 + grid $tab1.panedwindow.buttons.b4 -sticky snew -padx 2 -pady 2 + grid columnconfigure $tab1.panedwindow.buttons 0 -weight 1 + $tab1.panedwindow add $tab1.panedwindow.buttons + ## Add a set of other widgets (like progress, combo, scale, etc). + ttk::frame $tab1.panedwindow.widgets + ttk::progressbar $tab1.panedwindow.widgets.progress -orient horizontal \ + -maximum 100 -variable ttk::theme::gtkTtk::temp(progress) + grid $tab1.panedwindow.widgets.progress -sticky snew -padx 2 -pady 2 + ttk::scale $tab1.panedwindow.widgets.scale -orient horizontal -from 0 \ + -to 100 -variable ttk::theme::gtkTtk::temp(progress) + set ttk::theme::gtkTtk::temp(progress) 70 + grid $tab1.panedwindow.widgets.scale -sticky snew -padx 2 -pady 2 + ttk::entry $tab1.panedwindow.widgets.entry -textvariable \ + ttk::theme::gtkTtk::temp(entry) + set ttk::theme::gtkTtk::temp(entry) {Entry Widget} + grid $tab1.panedwindow.widgets.entry -sticky snew -padx 2 -pady 2 + ttk::button $tab1.panedwindow.widgets.button -text Button + grid $tab1.panedwindow.widgets.button -sticky snew -padx 2 -pady 2 + ttk::combobox $tab1.panedwindow.widgets.combo -values \ + {{Selection 1} {Selection 2} {Selection 3} {Selection 4}} + $tab1.panedwindow.widgets.combo set {Selection 1} + grid $tab1.panedwindow.widgets.combo -sticky snew -padx 2 -pady 2 + grid columnconfigure $tab1.panedwindow.widgets 0 -weight 1 + $tab1.panedwindow add $tab1.panedwindow.widgets + + grid $tab1.panedwindow -padx 2 -pady 2 -sticky snew + ttk::sizegrip $tab1.sg + ttk::scrollbar $tab1.hsb -orient horizontal + grid $tab1.hsb $tab1.sg -padx 2 -pady 2 -sticky snew + ttk::scrollbar $tab1.vsb -orient vertical + grid $tab1.vsb -row 0 -column 1 -padx 2 -pady 2 -sticky snew + grid columnconfigure $tab1 0 -weight 1 + grid rowconfigure $tab1 0 -weight 1 + + ## Fill tab2... + ##################### + ttk::panedwindow $tab2.panedwindow -orient vertical + ttk::label $tab2.panedwindow.label -text {Label Widget} + $tab2.panedwindow add $tab2.panedwindow.label + ttk::treeview $tab2.panedwindow.tree -height 4 + $tab2.panedwindow add $tab2.panedwindow.tree + grid $tab2.panedwindow -padx 2 -pady 2 -sticky snew + grid columnconfigure $tab2 0 -weight 1 + grid rowconfigure $tab2 0 -weight 1 + + pack $win.nb -fill both -expand 1 + };# selectStyleDlg_previewWidgets + + proc availableStyles {} { + return [lsort -dictionary [availableStyles_AsReturned]] + };# availableStyles + + ## Test the theme configuration panel... + if {0 && ![info exists ::testConfigurationPanel]} { + toplevel .themeConfPanel + wm withdraw .themeConfPanel + wm title .themeConfPanel "GtkTtk Configuration Panel..." + frame .themeConfPanel.page + createThemeConfigurationPanel .themeConfPanel.page + update + pack .themeConfPanel.page -fill both -expand 1 + wm deiconify .themeConfPanel + } + + proc getStyleColourInformation {} { + foreach colour {fg_color bg_color base_color text_color + selected_bg_color selected_fg_color + tooltip_bg_color tooltip_fg_color} { + catch {set C($colour) [currentThemeColour $colour]} e + } + foreach prefix {fg bg base text} { + foreach state {NORMAL PRELIGHT ACTIVE SELECTED INSENSITIVE} { + set colour ${prefix}($state) + catch {set C($colour) [currentThemeColour $colour]} e + } + } + return [array get C] + };# getStyleColourInformation + + variable prevClassicPalette + if {![info exists prevClassicPalette]} { + array set prevClassicPalette {} + } + variable prevClassicGeom + if {![info exists prevClassicGeom]} { + array set prevClassicGeom {} + } + + proc getDpiAndScale {} { + set home [expr {[info exists ::env(HOME)] ? $::env(HOME) : [file normalize ~]}] + set xres [file join $home .Xresources] + if {![file readable $xres] && [file readable /etc/skel/.Xresources]} { + set xres /etc/skel/.Xresources + } + set xft_dpi "" + set base_sz "" + set theme_scale "" + if {[file readable $xres]} { + set fd [open $xres r] + set data [read $fd] + close $fd + foreach line [split $data "\n"] { + set line [string trim $line] + if {$line eq "" || [string match "!*" $line] || [string match "#*" $line]} { + continue + } + if {[regexp {^Xft\.dpi\s*:\s*([0-9]+(?:\.[0-9]+)?)} $line -> v]} { + set xft_dpi $v + } elseif {[regexp {^theme\.baseFontSize\s*:\s*([0-9]+)} $line -> v]} { + set base_sz $v + } elseif {[regexp {^theme\.scale\s*:\s*([0-9]+(?:\.[0-9]+)?)} $line -> v]} { + set theme_scale $v + } + } + } + if {$xft_dpi eq "" || $xft_dpi <= 0} { + set sw [winfo screenwidth .] + set mm [winfo screenmmwidth .] + if {$mm > 0 && $sw > 0} { + set dpi [expr {double($sw) * 25.4 / double($mm)}] + } else { + set dpi 96.0 + } + } else { + set dpi [expr {double($xft_dpi)}] + } + if {$dpi < 48.0} { set dpi 48.0 } + if {$dpi > 384.0} { set dpi 384.0 } + catch {tk scaling [expr {$dpi / 72.0}]} + + set scale "" + if {[info exists ::env(ANODE_SCALE)] && [string is double -strict $::env(ANODE_SCALE)] && $::env(ANODE_SCALE) > 0} { + set scale [expr {double($::env(ANODE_SCALE))}] + } elseif {[info exists ::env(GTKTTK_SCALE)] && [string is double -strict $::env(GTKTTK_SCALE)] && $::env(GTKTTK_SCALE) > 0} { + set scale [expr {double($::env(GTKTTK_SCALE))}] + } elseif {[string is double -strict $theme_scale] && $theme_scale > 0} { + set scale [expr {double($theme_scale)}] + } elseif {[string is double -strict $xft_dpi] && $xft_dpi > 0} { + set scale [expr {double($xft_dpi) / 96.0}] + } elseif {[info exists ::env(QT_SCALE_FACTOR)] && [string is double -strict $::env(QT_SCALE_FACTOR)] && $::env(QT_SCALE_FACTOR) > 0} { + set scale [expr {double($::env(QT_SCALE_FACTOR))}] + } elseif {[info exists ::env(GDK_SCALE)] && [string is double -strict $::env(GDK_SCALE)] && $::env(GDK_SCALE) > 0} { + set scale [expr {double($::env(GDK_SCALE))}] + if {[info exists ::env(GDK_DPI_SCALE)] && [string is double -strict $::env(GDK_DPI_SCALE)] && $::env(GDK_DPI_SCALE) > 0} { + set scale [expr {$scale * double($::env(GDK_DPI_SCALE))}] + } + } else { + set scale [expr {$dpi / 96.0}] + } + if {$scale < 0.5} { set scale 0.5 } + if {$scale > 4.0} { set scale 4.0 } + return [list $dpi $scale $base_sz] + };# getDpiAndScale + + proc spx {px} { + if {$px <= 0} { return 0 } + lassign [getDpiAndScale] dpi scale base_sz + set v [expr {int(round(double($px) * $scale))}] + return [expr {$v < 1 ? 1 : $v}] + };# spx + + proc syncTkClassicPaletteAndFonts {} { + variable prevClassicPalette + variable prevClassicGeom + variable scaledNamedFonts + + lassign [getDpiAndScale] dpi scale base_sz + + array set nextPal [list \ + base_bg [currentThemeColour bg(NORMAL)] \ + base_fg [currentThemeColour fg(NORMAL)] \ + active_bg [currentThemeColour bg(PRELIGHT)] \ + active_fg [currentThemeColour fg(PRELIGHT)] \ + select_bg [currentThemeColour bg(SELECTED)] \ + select_fg [currentThemeColour fg(SELECTED)] \ + entry_bg [currentThemeColour base(NORMAL)] \ + entry_fg [currentThemeColour text(NORMAL)] \ + dis_fg [currentThemeColour fg(INSENSITIVE)] \ + ] + set base_bg $nextPal(base_bg) + set base_fg $nextPal(base_fg) + set active_bg $nextPal(active_bg) + set active_fg $nextPal(active_fg) + set select_bg $nextPal(select_bg) + set select_fg $nextPal(select_fg) + set entry_bg $nextPal(entry_bg) + set entry_fg $nextPal(entry_fg) + set dis_fg $nextPal(dis_fg) + + array set nextGeom [list \ + btn_padx [spx 10] \ + btn_pady [spx 4] \ + chk_padx [spx 6] \ + chk_pady [spx 4] \ + rad_padx [spx 6] \ + rad_pady [spx 4] \ + mb_padx [spx 8] \ + mb_pady [spx 4] \ + sb_width [spx 15] \ + sc_width [spx 14] \ + sc_len [spx 24] \ + bw_px [spx 1] \ + ] + + set queue [list .] + while {[llength $queue] > 0} { + set w [lindex $queue 0] + set queue [lrange $queue 1 end] + if {![winfo exists $w]} { + continue + } + foreach child [winfo children $w] { + lappend queue $child + } + if {![catch {$w cget -style}]} { + continue + } + set cls [winfo class $w] + if {$cls in {Entry Text Listbox Canvas Spinbox}} { + set w_bg_role entry_bg + set w_fg_role entry_fg + } else { + set w_bg_role base_bg + set w_fg_role base_fg + } + foreach {opt role} [list \ + -background $w_bg_role \ + -foreground $w_fg_role \ + -activebackground active_bg \ + -activeforeground active_fg \ + -selectbackground select_bg \ + -selectforeground select_fg \ + -disabledforeground dis_fg \ + -highlightbackground base_bg \ + -highlightcolor select_bg \ + -insertbackground $w_fg_role \ + -troughcolor active_bg] { + if {![info exists nextPal($role)] || $nextPal($role) eq ""} { + continue + } + if {[catch {$w configure $opt} cfg] == 0 && [llength $cfg] == 5} { + set def_val [lindex $cfg 3] + set cur_val [lindex $cfg 4] + set matched 0 + if {$cur_val eq $def_val} { + set matched 1 + } elseif {[catch {winfo rgb . $cur_val} cur_rgb] == 0 && \ + [catch {winfo rgb . $def_val} def_rgb] == 0 && \ + $cur_rgb eq $def_rgb} { + set matched 1 + } elseif {[info exists prevClassicPalette($role)] && $prevClassicPalette($role) ne ""} { + set prev_val $prevClassicPalette($role) + if {$cur_val eq $prev_val} { + set matched 1 + } elseif {[catch {winfo rgb . $cur_val} cur_rgb] == 0 && \ + [catch {winfo rgb . $prev_val} prev_rgb] == 0 && \ + $cur_rgb eq $prev_rgb} { + set matched 1 + } + } + if {$matched} { + catch {$w configure $opt $nextPal($role)} + } + } + } + + set gpairs {} + switch -exact $cls { + Button { set gpairs [list -padx btn_padx -pady btn_pady] } + Checkbutton { set gpairs [list -padx chk_padx -pady chk_pady] } + Radiobutton { set gpairs [list -padx rad_padx -pady rad_pady] } + Menubutton { set gpairs [list -padx mb_padx -pady mb_pady] } + Scrollbar { set gpairs [list -width sb_width] } + Scale { set gpairs [list -width sc_width -sliderlength sc_len] } + } + foreach {opt grole} $gpairs { + if {[catch {$w configure $opt} cfg] == 0 && [llength $cfg] == 5} { + set def_val [lindex $cfg 3] + set cur_val [lindex $cfg 4] + set matched 0 + if {$cur_val eq $def_val} { + set matched 1 + } elseif {[catch {winfo pixels $w $cur_val} cur_px] == 0 && \ + [catch {winfo pixels $w $def_val} def_px] == 0 && \ + $cur_px == $def_px} { + set matched 1 + } elseif {[info exists prevClassicGeom($grole)] && $prevClassicGeom($grole) ne ""} { + set pval $prevClassicGeom($grole) + if {$cur_val eq $pval} { + set matched 1 + } elseif {[catch {winfo pixels $w $cur_val} cur_px] == 0 && \ + [catch {winfo pixels $w $pval} prev_px] == 0 && \ + $cur_px == $prev_px} { + set matched 1 + } + } + if {$matched} { + catch {$w configure $opt $nextGeom($grole)} + } + } + } + } + array set prevClassicPalette [array get nextPal] + array set prevClassicGeom [array get nextGeom] + + foreach {pat val} [list \ + *borderWidth $nextGeom(bw_px) \ + *Button.padX $nextGeom(btn_padx) \ + *Button.padY $nextGeom(btn_pady) \ + *Checkbutton.padX $nextGeom(chk_padx) \ + *Checkbutton.padY $nextGeom(chk_pady) \ + *Radiobutton.padX $nextGeom(rad_padx) \ + *Radiobutton.padY $nextGeom(rad_pady) \ + *Menubutton.padX $nextGeom(mb_padx) \ + *Menubutton.padY $nextGeom(mb_pady) \ + *Scrollbar.width $nextGeom(sb_width) \ + *Scale.width $nextGeom(sc_width) \ + *Scale.sliderLength $nextGeom(sc_len) \ + *background $base_bg \ + *foreground $base_fg \ + *activeBackground $active_bg \ + *activeForeground $active_fg \ + *selectBackground $select_bg \ + *selectForeground $select_fg \ + *disabledForeground $dis_fg \ + *highlightBackground $base_bg \ + *highlightColor $select_bg \ + *troughColor $active_bg \ + *insertBackground $entry_fg \ + *Entry.background $entry_bg \ + *Entry.foreground $entry_fg \ + *Text.background $entry_bg \ + *Text.foreground $entry_fg \ + *Listbox.background $entry_bg \ + *Listbox.foreground $entry_fg \ + *Canvas.background $entry_bg \ + *Menu.background $base_bg \ + *Menu.foreground $base_fg \ + *Menu.activeBackground $select_bg \ + *Menu.activeForeground $select_fg \ + *Menu.selectColor $entry_fg \ + *Font TkDefaultFont \ + *font TkDefaultFont \ + *Entry.font TkTextFont \ + *Spinbox.font TkTextFont \ + *Text.font TkFixedFont \ + *Listbox.font TkDefaultFont \ + *TCombobox*Listbox.font TkTextFont \ + *Menu.font TkMenuFont] { + catch {option add $pat $val widgetDefault} + } + + set fam "Fira Code" + catch { + set cur_fam [font configure TkDefaultFont -family] + if {$cur_fam ne ""} { set fam $cur_fam } + } + set rc_pt 10 + if {![catch {set font_spec [settingsProperty gtk-font-name string]}] && $font_spec ne ""} { + set parts [split [string trim $font_spec]] + if {[llength $parts] >= 2 && [string is double -strict [lindex $parts end]]} { + set rc_pt [lindex $parts end] + set fam [join [lrange $parts 0 end-1] " "] + } elseif {[llength $parts] >= 1} { + set fam [join $parts " "] + } + } + if {[string is integer -strict $base_sz] && $base_sz >= 8} { + set px_main [expr {int($base_sz)}] + } elseif {[string is double -strict $rc_pt] && $rc_pt > 0} { + set px_main [expr {int(round(double($rc_pt) * ($dpi / 72.0)))}] + } else { + set px_main [expr {int(round(15.0 * $scale))}] + } + if {$px_main < 8} { set px_main 8 } + set px_head [expr {int(round($px_main * 1.15))}] + set px_small [expr {int(round($px_main * 0.85))}] + if {$px_small < 8} { set px_small 8 } + + foreach tkfont {TkDefaultFont TkTextFont TkFixedFont TkMenuFont TkIconFont} { + catch {font configure $tkfont -family $fam -size [expr {-$px_main}]} + } + foreach tkfont {TkHeadingFont TkCaptionFont} { + catch {font configure $tkfont -family $fam -size [expr {-$px_head}] -weight bold} + } + foreach tkfont {TkSmallCaptionFont TkTooltipFont} { + catch {font configure $tkfont -family $fam -size [expr {-$px_small}]} + } + + scaleExistingAppFonts + };# syncTkClassicPaletteAndFonts + + proc ptToScaledPx {pt factor} { + set px [expr {int(round(double($pt) * $factor))}] + return [expr {$px < 8 ? 8 : $px}] + };# ptToScaledPx + + proc scaleExistingAppFonts {} { + variable scaledNamedFonts + lassign [getDpiAndScale] dpi scale base_sz + if {abs($scale - 1.0) < 0.05} { return } + + set builtins { + TkDefaultFont TkTextFont TkFixedFont TkMenuFont TkHeadingFont + TkCaptionFont TkSmallCaptionFont TkIconFont TkTooltipFont + } + set factor [expr {($dpi / 72.0)}] + + foreach fn [font names] { + if {$fn in $builtins} { continue } + set sz "" + if {[catch {set sz [font configure $fn -size]}]} { continue } + if {[string is integer -strict $sz] && $sz > 0 && $sz <= 32} { + set scaledNamedFonts($fn) $sz + catch {font configure $fn -size [expr {-[ptToScaledPx $sz $factor]}]} + } + } + + set knownFonts [font names] + set queue [list .] + while {[llength $queue] > 0} { + set w [lindex $queue 0] + set queue [lrange $queue 1 end] + if {![winfo exists $w]} { continue } + foreach child [winfo children $w] { + lappend queue $child + } + if {[catch {set wf [$w cget -font]}]} { continue } + if {$wf eq "" || ($wf in $knownFonts)} { continue } + if {[regexp {(?:^|\s|-size\s+)-[0-9]+} $wf]} { continue } + + set new_wf "" + if {![catch {set n [llength $wf]}]} { + if {$n >= 2 && [expr {$n % 2 == 0}] && [string match -* [lindex $wf 0]]} { + set idx [lsearch -exact $wf -size] + if {$idx >= 0 && ($idx + 1) < $n} { + set pt [lindex $wf [expr {$idx + 1}]] + if {[string is double -strict $pt] && $pt > 0 && $pt <= 32} { + set px [ptToScaledPx $pt $factor] + set new_wf [lreplace $wf [expr {$idx + 1}] [expr {$idx + 1}] [expr {-$px}]] + } + } + } elseif {$n >= 2 && [string is double -strict [lindex $wf 1]]} { + set pt [lindex $wf 1] + if {$pt > 0 && $pt <= 32} { + set px [ptToScaledPx $pt $factor] + set new_wf [lreplace $wf 1 1 [expr {-$px}]] + } + } + } + if {$new_wf ne ""} { + catch {$w configure -font $new_wf} + } + } + };# scaleExistingAppFonts + + proc syncGtkRcSettings {} { + set home [expr {[info exists ::env(HOME)] ? $::env(HOME) : [file normalize ~]}] + set rcfile [file join $home .gtkrc-2.0] + if {![file readable $rcfile] && [file readable /etc/skel/.gtkrc-2.0]} { + set rcfile /etc/skel/.gtkrc-2.0 + } + if {[file readable $rcfile]} { + set fd [open $rcfile r] + set data [read $fd] + close $fd + set tname "" + set fname "" + foreach line [split $data "\n"] { + set line [string trim $line] + if {[regexp {^gtk-theme-name\s*=\s*"?([^"]+)"?} $line -> m]} { + set tname [string trim $m] + } elseif {[regexp {^gtk-font-name\s*=\s*"?([^"]+)"?} $line -> m]} { + set fname [string trim $m] + } + } + gtkDirectory default_files [list $rcfile] + if {$tname ne ""} { + set themeRc [file join $home .themes $tname gtk-2.0 gtkrc] + if {![file readable $themeRc] && [file readable [file join /etc/skel .themes $tname gtk-2.0 gtkrc]]} { + set themeRc [file join /etc/skel .themes $tname gtk-2.0 gtkrc] + } + if {[file readable $themeRc]} { + gtkDirectory default_files [list $themeRc $rcfile] + } + catch {setSettingsString gtk-theme-name $tname} + variable theme $tname + } + if {$fname ne ""} { + catch {setSettingsString gtk-font-name $fname} + } + catch {gtk_method gtk_rc_reparse_all_for_settings} + catch {gtk_method gtk_rc_reset_styles} + } + };# syncGtkRcSettings + + proc reloadCurrentGtkTheme {} { + getSystemInfo + availableStyles_AsReturned + syncGtkRcSettings + if {[ttk::style theme use] eq "gtkTtk"} { + updateLayouts + updateStyles + event generate . <> + } + };# reloadCurrentGtkTheme + + ## Update layouts on load... + proc init {} { + getSystemInfo + availableStyles_AsReturned + syncGtkRcSettings + updateLayouts + updateStyles + catch {after idle ::ttk::theme::gtkTtk::scaleExistingAppFonts} + };# init +} diff --git a/src/gtkTtk/library/pkgIndex.tcl b/src/gtkTtk/library/pkgIndex.tcl new file mode 100644 index 0000000..8b13ada --- /dev/null +++ b/src/gtkTtk/library/pkgIndex.tcl @@ -0,0 +1,3 @@ +package ifneeded ttk::theme::gtkTtk 0.9 [list load [file join $dir libgtkTtk0.9[info sharedlibextension]] gtkTtk] +package ifneeded ttk::theme::gtk 0.9 [list load [file join $dir libgtkTtk0.9[info sharedlibextension]] gtkTtk] +package ifneeded gtkTtk 0.9 [list load [file join $dir libgtkTtk0.9[info sharedlibextension]] gtkTtk] diff --git a/src/libgemui/gemui.c b/src/libgemui/gemui.c new file mode 100644 index 0000000..f034943 --- /dev/null +++ b/src/libgemui/gemui.c @@ -0,0 +1,1341 @@ +#define _POSIX_C_SOURCE 200809L +#include "gemui.h" +#include "anode_plat.h" +#include "anode_scale.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL 0 +#endif + +typedef struct { + int fd; + gemui_fd_cb cb; + void *ud; +} gemui_fd_slot_t; + +struct gemui_app { + Display *dpy; + int screen; + Window root; + Window win; + Pixmap backbuf; + cairo_surface_t *img_surf; + cairo_t *img_cr; + cairo_surface_t *xlib_surf; + PangoLayout *pango_layout; + GC gc; + int bw; + int bh; + int w; + int h; + Atom wm_delete; + Atom net_wm_name; + Atom utf8_string; + Atom net_wm_state; + Atom net_wm_state_fs; + XIM xim; + XIC xic; + bool fullscreen_override; + bool mapped; + bool need_redraw; + bool running; + int exit_code; + gemui_theme_t theme; + gemui_handlers_t handlers; + void *userdata; + gemui_hit_t hits[GEMUI_MAX_HITS]; + int num_hits; + gemui_fd_slot_t fds[GEMUI_MAX_FDS]; + int num_fds; + int timer_ms; + uint64_t next_timer_ms; + gemui_timer_cb timer_cb; + void *timer_ud; + char toast_msg[256]; + uint64_t toast_until_ms; + bool ptr_down; + Window prev_focus_win; + int prev_focus_revert; +}; + +static int g_sig_pipe[2] = {-1, -1}; +static PangoLayout *g_active_layout = NULL; + +static void gemui_sigusr1_handler(int sig) { + (void)sig; + if (g_sig_pipe[1] >= 0) { + int saved = errno; + char b = 'T'; + ssize_t unused = write(g_sig_pipe[1], &b, 1); + (void)unused; + errno = saved; + } +} + +static uint64_t gemui_now_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); +} + +static void gemui_init_sigpipe(void) { + if (g_sig_pipe[0] >= 0) { + return; + } + if (pipe(g_sig_pipe) == 0) { + for (int i = 0; i < 2; i++) { + int fl = fcntl(g_sig_pipe[i], F_GETFL, 0); + if (fl >= 0) { + fcntl(g_sig_pipe[i], F_SETFL, fl | O_NONBLOCK); + } + int fdfl = fcntl(g_sig_pipe[i], F_GETFD, 0); + if (fdfl >= 0) { + fcntl(g_sig_pipe[i], F_SETFD, fdfl | FD_CLOEXEC); + } + } + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = gemui_sigusr1_handler; + sigemptyset(&sa.sa_mask); + sa.sa_flags = SA_RESTART; + sigaction(SIGUSR1, &sa, NULL); + } +} + +static int hex_val(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; +} + +bool gemui_color_parse(const char *hex, gemui_color_t *out) { + if (!hex || !out) return false; + while (*hex == ' ' || *hex == '\t') hex++; + if (*hex == '#') hex++; + size_t n = strlen(hex); + if (n < 6) return false; + int vals[6]; + for (int i = 0; i < 6; i++) { + vals[i] = hex_val(hex[i]); + if (vals[i] < 0) return false; + } + uint8_t r = (uint8_t)((vals[0] << 4) | vals[1]); + uint8_t g = (uint8_t)((vals[2] << 4) | vals[3]); + uint8_t b = (uint8_t)((vals[4] << 4) | vals[5]); + out->r = r / 255.0; + out->g = g / 255.0; + out->b = b / 255.0; + out->a = 1.0; + out->argb = 0xff000000U | ((uint32_t)r << 16) | ((uint32_t)g << 8) | (uint32_t)b; + return true; +} + +void gemui_theme_defaults(gemui_theme_t *t) { + memset(t, 0, sizeof(*t)); + snprintf(t->name, sizeof(t->name), "AnodeDefault"); + 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); +} + +static void gemui_apply_xrm_db(XrmDatabase db, gemui_theme_t *t) { + if (!db) return; + char *type = NULL; + XrmValue val; + + struct { + const char *key; + gemui_color_t *dst; + } colors[] = { + { "theme.bgMain", &t->bg_main }, + { "theme.bgBar", &t->bg_bar }, + { "theme.bgHeader", &t->bg_header }, + { "theme.bgFooter", &t->bg_footer }, + { "theme.bgOverlay", &t->bg_overlay }, + { "theme.bgAltEven", &t->bg_alt_even }, + { "theme.bgAltOdd", &t->bg_alt_odd }, + { "theme.bgInput", &t->bg_input }, + { "theme.bgInputFocus", &t->bg_input_focus }, + { "theme.bgButton", &t->bg_button }, + { "theme.bgSearch", &t->bg_search }, + { "theme.bgBubbleIn", &t->bg_bubble_in }, + { "theme.bgBubbleOut", &t->bg_bubble_out }, + { "theme.bgToast", &t->bg_toast }, + { "theme.fgMain", &t->fg_main }, + { "theme.fgBright", &t->fg_bright }, + { "theme.fgMuted", &t->fg_muted }, + { "theme.selBg", &t->sel_bg }, + { "theme.selFg", &t->sel_fg }, + { "theme.accent", &t->accent }, + { "theme.accentAlt", &t->accent_alt }, + { "theme.highlight", &t->highlight }, + { "theme.border", &t->border }, + { "theme.divider", &t->divider }, + { "theme.success", &t->success }, + { "theme.info", &t->info }, + { "theme.warning", &t->warning }, + { "theme.danger", &t->danger }, + { "theme.dangerBg", &t->danger_bg }, + }; + + for (size_t i = 0; i < sizeof(colors) / sizeof(colors[0]); i++) { + if (XrmGetResource(db, colors[i].key, "Theme.Color", &type, &val) && val.addr) { + gemui_color_parse(val.addr, colors[i].dst); + } + } + if (XrmGetResource(db, "theme.name", "Theme.Name", &type, &val) && val.addr) { + snprintf(t->name, sizeof(t->name), "%s", val.addr); + } + if (XrmGetResource(db, "theme.fontFace", "Theme.FontFace", &type, &val) && val.addr) { + snprintf(t->font_face, sizeof(t->font_face), "%s", val.addr); + } + if (XrmGetResource(db, "theme.iconFontFace", "Theme.IconFontFace", &type, &val) && val.addr) { + snprintf(t->icon_font_face, sizeof(t->icon_font_face), "%s", val.addr); + } + if (XrmGetResource(db, "theme.baseFontSize", "Theme.BaseFontSize", &type, &val) && val.addr) { + int sz = atoi(val.addr); + if (sz >= 8 && sz <= 96) t->base_font_size = sz; + } + if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &val) && val.addr) { + int d = atoi(val.addr); + if (d >= 48 && d <= 384) t->dpi = d; + } + if (XrmGetResource(db, "theme.scale", "Theme.Scale", &type, &val) && val.addr) { + double s = strtod(val.addr, NULL); + if (s > 0.0) t->scale = anode_clamp_scale(s); + } + if (XrmGetResource(db, "theme.touchMode", "Theme.TouchMode", &type, &val) && val.addr) { + t->touch_mode = anode_parse_bool_str(val.addr, t->touch_mode ? 1 : 0) != 0; + } +} + +bool gemui_theme_load_file(const char *path, gemui_theme_t *out) { + if (!path || !out) return false; + XrmInitialize(); + gemui_theme_defaults(out); + XrmDatabase db = XrmGetFileDatabase(path); + if (!db) return false; + gemui_apply_xrm_db(db, out); + XrmDestroyDatabase(db); + return true; +} + +void gemui_theme_reload(gemui_app_t *app) { + if (!app) return; + XrmInitialize(); + gemui_theme_defaults(&app->theme); + + XrmDatabase db = anode_open_xres_db(app->dpy); + bool from_xres = (db != NULL); + if (!db) { + char xth_path[512]; + xth_path[0] = '\0'; + anode_default_xth_path(xth_path, sizeof(xth_path)); + if (xth_path[0]) { + db = XrmGetFileDatabase(xth_path); + } + } + + double dpi_d = 96.0, scale_d = 1.0; + int touch_i = 0; + anode_read_xres_scale_from_db(db, app->dpy, &dpi_d, &scale_d, &touch_i); + + bool has_explicit_base_sz = false; + if (db) { + gemui_apply_xrm_db(db, &app->theme); + char *type = NULL; + XrmValue val; + if (from_xres && + XrmGetResource(db, "theme.baseFontSize", "Theme.BaseFontSize", &type, &val) && + val.addr && val.addr[0]) { + has_explicit_base_sz = true; + } + XrmDestroyDatabase(db); + } + + app->theme.dpi = (int)llround(dpi_d); + app->theme.scale = scale_d; + app->theme.touch_mode = (touch_i != 0); + if (!has_explicit_base_sz) { + int logical_base = app->theme.base_font_size; + if (logical_base < 8 || logical_base > 28) logical_base = 15; + app->theme.base_font_size = anode_scale_px(logical_base, scale_d); + } +} + +static void gemui_ensure_backbuf(gemui_app_t *app) { + if (app->w <= 0 || app->h <= 0) return; + if (app->backbuf && app->img_cr && app->xlib_surf && + app->bw == app->w && app->bh == app->h) { + return; + } + if (app->pango_layout) { + g_object_unref(app->pango_layout); + app->pango_layout = NULL; + } + if (app->img_cr) { + cairo_destroy(app->img_cr); + app->img_cr = NULL; + } + if (app->img_surf) { + cairo_surface_destroy(app->img_surf); + app->img_surf = NULL; + } + if (app->xlib_surf) { + cairo_surface_destroy(app->xlib_surf); + app->xlib_surf = NULL; + } + if (app->backbuf) { + XFreePixmap(app->dpy, app->backbuf); + app->backbuf = 0; + } + app->backbuf = XCreatePixmap(app->dpy, app->win, (unsigned int)app->w, + (unsigned int)app->h, + (unsigned int)DefaultDepth(app->dpy, app->screen)); + app->xlib_surf = cairo_xlib_surface_create(app->dpy, app->backbuf, + DefaultVisual(app->dpy, app->screen), + app->w, app->h); + app->img_surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, app->w, app->h); + app->img_cr = cairo_create(app->img_surf); + app->pango_layout = pango_cairo_create_layout(app->img_cr); + app->bw = app->w; + app->bh = app->h; + if (app->backbuf) { + XSetWindowBackgroundPixmap(app->dpy, app->win, app->backbuf); + } +} + +static int gemui_ignore_xerror(Display *dpy, XErrorEvent *ev) { + (void)dpy; + (void)ev; + return 0; +} + +static void gemui_save_prev_focus(gemui_app_t *app) { + if (!app || app->prev_focus_win != None) return; + Window cur = None; + int rev = RevertToPointerRoot; + XGetInputFocus(app->dpy, &cur, &rev); + if (cur != None && cur != app->win) { + app->prev_focus_win = cur; + app->prev_focus_revert = rev; + } +} + +static void gemui_restore_prev_focus(gemui_app_t *app) { + if (!app || app->prev_focus_win == None || app->prev_focus_win == app->win) return; + XSync(app->dpy, False); + int (*old_handler)(Display *, XErrorEvent *) = XSetErrorHandler(gemui_ignore_xerror); + XSetInputFocus(app->dpy, app->prev_focus_win, app->prev_focus_revert, CurrentTime); + XSync(app->dpy, False); + XSetErrorHandler(old_handler); + app->prev_focus_win = None; +} + +gemui_app_t *gemui_create(const char *res_name, const char *title, + int w, int h, bool fullscreen_override) { + setlocale(LC_CTYPE, ""); + XSetLocaleModifiers(""); + gemui_init_sigpipe(); + Display *dpy = XOpenDisplay(NULL); + if (!dpy) { + fprintf(stderr, "gemui: cannot open X11 display\n"); + return NULL; + } + + gemui_app_t *app = calloc(1, sizeof(*app)); + if (!app) { + XCloseDisplay(dpy); + return NULL; + } + + app->dpy = dpy; + app->screen = DefaultScreen(dpy); + app->root = RootWindow(dpy, app->screen); + app->fullscreen_override = fullscreen_override; + + gemui_theme_reload(app); + + int sw = DisplayWidth(dpy, app->screen); + int sh = DisplayHeight(dpy, app->screen); + int mx = 0, my = 0, mw = sw, mh = sh; + + /* Pick monitor under pointer via Xinerama if active */ + { + int xn = 0; + XineramaScreenInfo *xi = XineramaIsActive(dpy) ? XineramaQueryScreens(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(dpy, app->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; + } + } + } + mx = xi[chosen].x_org; + my = xi[chosen].y_org; + mw = xi[chosen].width; + mh = xi[chosen].height; + XFree(xi); + } + } + + /* Respect _NET_WORKAREA if published by DWM/EWMH */ + if (!fullscreen_override) { + Atom workarea_atom = XInternAtom(dpy, "_NET_WORKAREA", False); + Atom da = None; + int di = 0; + unsigned long n = 0, dl = 0; + unsigned char *prop = NULL; + if (XGetWindowProperty(dpy, app->root, workarea_atom, 0L, 4L, False, XA_CARDINAL, + &da, &di, &n, &dl, &prop) == Success && prop) { + if (di == 32 && n >= 4) { + unsigned long *wa = (unsigned long *)prop; + int wx0 = (int)wa[0], wy0 = (int)wa[1], ww0 = (int)wa[2], wh0 = (int)wa[3]; + if (ww0 > 64 && wh0 > 64 && + wx0 < mx + mw && wx0 + ww0 > mx && + wy0 < my + mh && wy0 + wh0 > my) { + int x1 = (wx0 > mx) ? wx0 : mx; + int y1 = (wy0 > my) ? wy0 : my; + int x2 = (wx0 + ww0 < mx + mw) ? (wx0 + ww0) : (mx + mw); + int y2 = (wy0 + wh0 < my + mh) ? (wy0 + wh0) : (my + mh); + if (x2 - x1 > 64 && y2 - y1 > 64) { + mx = x1; my = y1; mw = x2 - x1; mh = y2 - y1; + } + } + } + XFree(prop); + } + } + + if (fullscreen_override || 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 (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; + } + app->w = w; + app->h = h; + + int wx = fullscreen_override ? 0 : mx + (mw - w) / 2; + int wy = fullscreen_override ? 0 : my + (mh - h) / 2; + if (wx < 0) wx = 0; + if (wy < 0) wy = 0; + + XSetWindowAttributes swa; + memset(&swa, 0, sizeof(swa)); + swa.background_pixmap = None; + swa.event_mask = ExposureMask | KeyPressMask | ButtonPressMask | + ButtonReleaseMask | PointerMotionMask | + StructureNotifyMask | FocusChangeMask; + if (fullscreen_override) { + swa.override_redirect = True; + } + + unsigned long mask = CWBackPixmap | CWEventMask | (fullscreen_override ? CWOverrideRedirect : 0); + app->win = XCreateWindow(dpy, app->root, wx, wy, (unsigned int)w, (unsigned int)h, 0, + CopyFromParent, InputOutput, CopyFromParent, mask, &swa); + { + XSizeHints *shints = XAllocSizeHints(); + if (shints) { + shints->flags = PPosition | PSize; + shints->x = wx; + shints->y = wy; + shints->width = w; + shints->height = h; + XSetWMNormalHints(dpy, app->win, shints); + XFree(shints); + } + } + { + Cursor cur = XCreateFontCursor(dpy, XC_left_ptr); + if (cur != None) { + XDefineCursor(dpy, app->win, cur); + XFreeCursor(dpy, cur); + } + } + app->gc = XCreateGC(dpy, app->win, 0, NULL); + + XClassHint *ch = XAllocClassHint(); + if (ch) { + ch->res_name = (char *)(res_name ? res_name : "anode-app"); + ch->res_class = (char *)(res_name ? res_name : "anode-app"); + XSetClassHint(dpy, app->win, ch); + XFree(ch); + } + + XSelectInput(dpy, app->root, PropertyChangeMask); + + 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); + XSetWMProtocols(dpy, app->win, &app->wm_delete, 1); + + if (fullscreen_override) { + XChangeProperty(dpy, app->win, app->net_wm_state, XA_ATOM, 32, + PropModeReplace, (unsigned char *)&app->net_wm_state_fs, 1); + } + + gemui_set_title(app, title ? title : "ANODE"); + + app->xim = XOpenIM(dpy, NULL, NULL, NULL); + if (app->xim) { + app->xic = XCreateIC(app->xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, + XNClientWindow, app->win, XNFocusWindow, app->win, NULL); + } + + if (fullscreen_override) { + XMapRaised(dpy, app->win); + app->mapped = true; + XMoveResizeWindow(dpy, app->win, mx, my, (unsigned int)mw, (unsigned int)mh); + gemui_save_prev_focus(app); + XSetInputFocus(dpy, app->win, RevertToPointerRoot, CurrentTime); + } + XFlush(dpy); + app->need_redraw = true; + return app; +} + +void gemui_destroy(gemui_app_t *app) { + if (!app) return; + gemui_restore_prev_focus(app); + if (app->xic) XDestroyIC(app->xic); + if (app->xim) XCloseIM(app->xim); + if (app->pango_layout) g_object_unref(app->pango_layout); + if (app->img_cr) cairo_destroy(app->img_cr); + if (app->img_surf) cairo_surface_destroy(app->img_surf); + if (app->xlib_surf) cairo_surface_destroy(app->xlib_surf); + if (app->backbuf) XFreePixmap(app->dpy, app->backbuf); + if (app->gc) XFreeGC(app->dpy, app->gc); + if (app->win) XDestroyWindow(app->dpy, app->win); + if (app->dpy) XCloseDisplay(app->dpy); + free(app); +} + +void gemui_set_handlers(gemui_app_t *app, const gemui_handlers_t *h, void *userdata) { + if (!app) return; + if (h) app->handlers = *h; + app->userdata = userdata; +} + +void gemui_set_title(gemui_app_t *app, const char *title) { + if (!app || !title) return; + XStoreName(app->dpy, app->win, title); + XChangeProperty(app->dpy, app->win, app->net_wm_name, app->utf8_string, 8, + PropModeReplace, (const unsigned char *)title, (int)strlen(title)); +} + +Display *gemui_display(const gemui_app_t *app) { return app ? app->dpy : NULL; } +Window gemui_window(const gemui_app_t *app) { return app ? app->win : 0; } +const gemui_theme_t *gemui_theme(const gemui_app_t *app) { return app ? &app->theme : NULL; } +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; } + +double gemui_scale(const gemui_app_t *app) { + return app ? app->theme.scale : 1.0; +} + +bool gemui_touch_mode(const gemui_app_t *app) { + return app ? app->theme.touch_mode : false; +} + +int gemui_scale_px(const gemui_app_t *app, int logical_px) { + double s = app ? app->theme.scale : 1.0; + return anode_scale_px(logical_px, s); +} + +int gemui_touch_row_px(const gemui_app_t *app, int logical_px) { + double s = app ? app->theme.scale : 1.0; + if (app && app->theme.touch_mode) { + s *= 1.18; + } + return anode_scale_px(logical_px, s); +} + +int gemui_add_fd(gemui_app_t *app, int fd, gemui_fd_cb cb, void *userdata) { + if (!app || fd < 0 || app->num_fds >= GEMUI_MAX_FDS) return -1; + for (int i = 0; i < app->num_fds; i++) { + if (app->fds[i].fd == fd) { + app->fds[i].cb = cb; + app->fds[i].ud = userdata; + return 0; + } + } + app->fds[app->num_fds].fd = fd; + app->fds[app->num_fds].cb = cb; + app->fds[app->num_fds].ud = userdata; + app->num_fds++; + return 0; +} + +void gemui_del_fd(gemui_app_t *app, int fd) { + if (!app) return; + for (int i = 0; i < app->num_fds; i++) { + if (app->fds[i].fd == fd) { + app->fds[i] = app->fds[app->num_fds - 1]; + app->num_fds--; + return; + } + } +} + +void gemui_set_timer_ms(gemui_app_t *app, int interval_ms, gemui_timer_cb cb, void *userdata) { + if (!app) return; + app->timer_ms = interval_ms; + app->timer_cb = cb; + app->timer_ud = userdata; + app->next_timer_ms = (interval_ms > 0) ? (gemui_now_ms() + (uint64_t)interval_ms) : 0; +} + +void gemui_request_redraw(gemui_app_t *app) { + if (app) app->need_redraw = true; +} + +void gemui_show_toast(gemui_app_t *app, const char *msg, int duration_ms) { + if (!app) return; + if (!msg || !msg[0]) { + app->toast_msg[0] = '\0'; + app->toast_until_ms = 0; + } else { + snprintf(app->toast_msg, sizeof(app->toast_msg), "%s", msg); + app->toast_until_ms = gemui_now_ms() + (uint64_t)(duration_ms > 0 ? duration_ms : 2200); + } + app->need_redraw = true; +} + +void gemui_quit(gemui_app_t *app, int code) { + if (!app) return; + app->exit_code = code; + app->running = false; +} + +bool gemui_grab_input(gemui_app_t *app) { + if (!app) return false; + if (!app->mapped) { + gemui_flush_draw(app); + } + bool ok_kbd = XGrabKeyboard(app->dpy, app->win, True, GrabModeAsync, + GrabModeAsync, CurrentTime) == GrabSuccess; + XGrabPointer(app->dpy, app->win, True, + ButtonPressMask | ButtonReleaseMask | PointerMotionMask, + GrabModeAsync, GrabModeAsync, app->win, None, CurrentTime); + gemui_save_prev_focus(app); + if (app->mapped) { + XSetInputFocus(app->dpy, app->win, RevertToPointerRoot, CurrentTime); + } + XFlush(app->dpy); + return ok_kbd; +} + +void gemui_ungrab_input(gemui_app_t *app) { + if (!app) return; + XUngrabKeyboard(app->dpy, CurrentTime); + XUngrabPointer(app->dpy, CurrentTime); + gemui_restore_prev_focus(app); + XFlush(app->dpy); +} + +void gemui_hits_clear(gemui_app_t *app) { + if (app) app->num_hits = 0; +} + +void gemui_hit_add(gemui_app_t *app, gemui_rect_t r, int id, int val) { + if (!app || app->num_hits >= GEMUI_MAX_HITS) return; + app->hits[app->num_hits].r = r; + app->hits[app->num_hits].id = id; + app->hits[app->num_hits].val = val; + app->num_hits++; +} + +const gemui_hit_t *gemui_hit_test(const gemui_app_t *app, int x, int y) { + if (!app) return NULL; + for (int i = app->num_hits - 1; i >= 0; i--) { + gemui_rect_t r = app->hits[i].r; + if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) { + return &app->hits[i]; + } + } + return NULL; +} + +static void gemui_render_frame(gemui_app_t *app) { + if (!app || !app->need_redraw || app->w <= 0 || app->h <= 0) return; + gemui_ensure_backbuf(app); + if (!app->backbuf || !app->img_cr || !app->xlib_surf) return; + + cairo_t *cr = app->img_cr; + g_active_layout = app->pango_layout; + gemui_hits_clear(app); + gemui_fill_rect(cr, (gemui_rect_t){0, 0, app->w, app->h}, app->theme.bg_main); + if (app->handlers.on_draw) { + app->handlers.on_draw(app, cr, app->w, app->h, app->userdata); + } + gemui_draw_toast(app, cr); + g_active_layout = NULL; + cairo_surface_flush(app->img_surf); + + cairo_t *xcr = cairo_create(app->xlib_surf); + cairo_set_operator(xcr, CAIRO_OPERATOR_SOURCE); + cairo_set_source_surface(xcr, app->img_surf, 0, 0); + cairo_paint(xcr); + cairo_destroy(xcr); + cairo_surface_flush(app->xlib_surf); + + if (!app->mapped) { + XSetWindowBackgroundPixmap(app->dpy, app->win, app->backbuf); + XMapRaised(app->dpy, app->win); + app->mapped = true; + } + XCopyArea(app->dpy, app->backbuf, app->win, app->gc, 0, 0, + (unsigned int)app->w, (unsigned int)app->h, 0, 0); + XFlush(app->dpy); + app->need_redraw = false; +} + +void gemui_flush_draw(gemui_app_t *app) { + if (!app) return; + app->need_redraw = true; + gemui_render_frame(app); +} + +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; + + switch (ev.type) { + case Expose: + if (ev.xexpose.count == 0) app->need_redraw = true; + break; + case ConfigureNotify: + if (ev.xconfigure.width != app->w || ev.xconfigure.height != app->h) { + app->w = ev.xconfigure.width; + app->h = ev.xconfigure.height; + if (app->handlers.on_resize) { + app->handlers.on_resize(app, app->w, app->h, app->userdata); + } + app->need_redraw = true; + } + break; + case ClientMessage: + if ((Atom)ev.xclient.data.l[0] == app->wm_delete) { + gemui_quit(app, 0); + } + break; + case KeyPress: { + char buf[64] = {0}; + KeySym ks = NoSymbol; + Status st = 0; + int len = 0; + if (app->xic) { + len = Xutf8LookupString(app->xic, &ev.xkey, buf, (int)sizeof(buf) - 1, &ks, &st); + } else { + len = XLookupString(&ev.xkey, buf, (int)sizeof(buf) - 1, &ks, NULL); + } + if (len < 0) len = 0; + buf[len] = '\0'; + /* Ignore bare control characters like Ctrl+C/Backspace inside utf8 text buffer */ + if (len > 0 && ((unsigned char)buf[0] < 0x20 || buf[0] == 0x7f)) { + buf[0] = '\0'; + } + if (app->handlers.on_key) { + app->handlers.on_key(app, ks, ev.xkey.state, buf, app->userdata); + } + break; + } + case ButtonPress: + if (ev.xbutton.button == Button4) { + if (app->handlers.on_ptr) { + app->handlers.on_ptr(app, GEMUI_PTR_SCROLL_UP, ev.xbutton.x, ev.xbutton.y, + ev.xbutton.button, app->userdata); + } + } else if (ev.xbutton.button == Button5) { + if (app->handlers.on_ptr) { + app->handlers.on_ptr(app, GEMUI_PTR_SCROLL_DOWN, ev.xbutton.x, ev.xbutton.y, + ev.xbutton.button, app->userdata); + } + } else { + app->ptr_down = true; + if (app->handlers.on_ptr) { + app->handlers.on_ptr(app, GEMUI_PTR_DOWN, ev.xbutton.x, ev.xbutton.y, + ev.xbutton.button, app->userdata); + } + } + break; + case MotionNotify: + while (XPending(app->dpy) > 0) { + XEvent pev; + XPeekEvent(app->dpy, &pev); + if (pev.type != MotionNotify || pev.xmotion.window != ev.xmotion.window) break; + XNextEvent(app->dpy, &ev); + } + if (app->ptr_down && app->handlers.on_ptr) { + app->handlers.on_ptr(app, GEMUI_PTR_MOVE, ev.xmotion.x, ev.xmotion.y, + 0, app->userdata); + } + break; + case ButtonRelease: + if (ev.xbutton.button != Button4 && ev.xbutton.button != Button5) { + app->ptr_down = false; + if (app->handlers.on_ptr) { + app->handlers.on_ptr(app, GEMUI_PTR_UP, ev.xbutton.x, ev.xbutton.y, + ev.xbutton.button, app->userdata); + } + } + break; + case PropertyNotify: + if (ev.xproperty.window == app->root && + ev.xproperty.atom == XA_RESOURCE_MANAGER && + ev.xproperty.state != PropertyDelete) { + gemui_theme_reload(app); + if (app->handlers.on_theme) { + app->handlers.on_theme(app, app->userdata); + } + app->need_redraw = true; + } + break; + default: + break; + } + } +} + +int gemui_run(gemui_app_t *app) { + if (!app) return 1; + app->running = true; + int xfd = ConnectionNumber(app->dpy); + + while (app->running) { + gemui_handle_x_events(app); + if (!app->running) break; + + uint64_t now = gemui_now_ms(); + if (app->toast_until_ms && now >= app->toast_until_ms) { + app->toast_msg[0] = '\0'; + app->toast_until_ms = 0; + app->need_redraw = true; + } + if (app->timer_ms > 0 && app->timer_cb && now >= app->next_timer_ms) { + app->next_timer_ms = now + (uint64_t)app->timer_ms; + app->timer_cb(app, app->timer_ud); + } + + if (app->need_redraw) { + gemui_render_frame(app); + } + + int timeout_ms = -1; + now = gemui_now_ms(); + if (app->timer_ms > 0 && app->timer_cb) { + int rem = (app->next_timer_ms > now) ? (int)(app->next_timer_ms - now) : 0; + timeout_ms = rem; + } + if (app->toast_until_ms > 0) { + int rem = (app->toast_until_ms > now) ? (int)(app->toast_until_ms - now) : 0; + if (timeout_ms < 0 || rem < timeout_ms) timeout_ms = rem; + } + + struct pollfd pfds[2 + GEMUI_MAX_FDS]; + nfds_t nfds = 0; + pfds[nfds].fd = xfd; + pfds[nfds].events = POLLIN; + pfds[nfds].revents = 0; + nfds++; + + int sig_idx = -1; + if (g_sig_pipe[0] >= 0) { + sig_idx = (int)nfds; + pfds[nfds].fd = g_sig_pipe[0]; + pfds[nfds].events = POLLIN; + pfds[nfds].revents = 0; + nfds++; + } + + int extra_start = (int)nfds; + for (int i = 0; i < app->num_fds; i++) { + pfds[nfds].fd = app->fds[i].fd; + pfds[nfds].events = POLLIN; + pfds[nfds].revents = 0; + nfds++; + } + + if (XPending(app->dpy) > 0) continue; + + int rc = poll(pfds, nfds, timeout_ms); + if (rc < 0 && errno == EINTR) continue; + + if (sig_idx >= 0 && (pfds[sig_idx].revents & POLLIN)) { + char drain[32]; + while (read(g_sig_pipe[0], drain, sizeof(drain)) > 0) {} + gemui_theme_reload(app); + if (app->handlers.on_theme) { + app->handlers.on_theme(app, app->userdata); + } + app->need_redraw = true; + } + + for (int i = 0; i < app->num_fds; i++) { + int idx = extra_start + i; + if (idx < (int)nfds && (pfds[idx].revents & (POLLIN | POLLHUP | POLLERR))) { + if (app->fds[i].cb) { + app->fds[i].cb(app, app->fds[i].fd, app->fds[i].ud); + } + } + } + } + return app->exit_code; +} + +void gemui_set_source(cairo_t *cr, gemui_color_t c) { + cairo_set_source_rgba(cr, c.r, c.g, c.b, c.a); +} + +void gemui_rounded_rect(cairo_t *cr, gemui_rect_t r, double rad) { + if (rad <= 0.0) { + cairo_rectangle(cr, r.x, r.y, r.w, r.h); + return; + } + if (rad > r.w / 2.0) rad = r.w / 2.0; + if (rad > r.h / 2.0) rad = r.h / 2.0; + const double pi = 3.14159265358979323846; + cairo_new_sub_path(cr); + cairo_arc(cr, r.x + r.w - rad, r.y + rad, rad, -pi / 2.0, 0.0); + cairo_arc(cr, r.x + r.w - rad, r.y + r.h - rad, rad, 0.0, pi / 2.0); + cairo_arc(cr, r.x + rad, r.y + r.h - rad, rad, pi / 2.0, pi); + cairo_arc(cr, r.x + rad, r.y + rad, rad, pi, 3.0 * pi / 2.0); + cairo_close_path(cr); +} + +void gemui_fill_rect(cairo_t *cr, gemui_rect_t r, gemui_color_t c) { + gemui_set_source(cr, c); + cairo_rectangle(cr, r.x, r.y, r.w, r.h); + cairo_fill(cr); +} + +void gemui_fill_round(cairo_t *cr, gemui_rect_t r, double radius, gemui_color_t c) { + gemui_set_source(cr, c); + gemui_rounded_rect(cr, r, radius); + cairo_fill(cr); +} + +void gemui_stroke_round(cairo_t *cr, gemui_rect_t r, double radius, double lw, gemui_color_t c) { + gemui_set_source(cr, c); + cairo_set_line_width(cr, lw); + gemui_rounded_rect(cr, r, radius); + cairo_stroke(cr); +} + +static int gemui_draw_pango(cairo_t *cr, const char *face, int px_size, + gemui_rect_t r, const char *text, bool bold, + int align, gemui_color_t c) { + if (!text || !text[0] || r.w <= 4 || r.h <= 4) return 0; + PangoLayout *layout = g_active_layout ? g_active_layout : pango_cairo_create_layout(cr); + char desc_str[160]; + snprintf(desc_str, sizeof(desc_str), "%s%s %dpx", + face && face[0] ? face : "Fira Code", + bold ? " Bold" : "", + px_size > 8 ? px_size : 14); + PangoFontDescription *desc = pango_font_description_from_string(desc_str); + pango_layout_set_attributes(layout, NULL); + 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_single_paragraph_mode(layout, True); + if (align == GEMUI_ALIGN_CENTER) { + pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER); + } else if (align == GEMUI_ALIGN_RIGHT) { + pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT); + } else { + pango_layout_set_alignment(layout, PANGO_ALIGN_LEFT); + } + pango_layout_set_text(layout, text, -1); + + int tw = 0, th = 0; + pango_layout_get_pixel_size(layout, &tw, &th); + int dy = r.y + (r.h - th) / 2; + gemui_set_source(cr, c); + cairo_move_to(cr, r.x, dy); + pango_cairo_show_layout(cr, layout); + + pango_font_description_free(desc); + if (!g_active_layout) g_object_unref(layout); + return tw; +} + +int gemui_draw_text(cairo_t *cr, const gemui_theme_t *t, gemui_rect_t r, + const char *text, int pt_delta, bool bold, int align, gemui_color_t c) { + double sc = (t && t->scale > 0.0) ? t->scale : 1.0; + int base_px = (t && t->base_font_size > 0) ? t->base_font_size : anode_scale_px(15, sc); + int delta_px = (int)llround((double)pt_delta * sc); + int px = base_px + delta_px; + if (px < 8) px = 8; + char fam[200]; + snprintf(fam, sizeof(fam), "%s, %s", + (t && t->font_face[0]) ? t->font_face : "Fira Code", + (t && t->icon_font_face[0]) ? t->icon_font_face : "DejaVuSansM Nerd Font"); + return gemui_draw_pango(cr, fam, px, r, text, bold, align, c); +} + +int gemui_draw_icon(cairo_t *cr, const gemui_theme_t *t, gemui_rect_t r, + const char *icon_utf8, int pt_delta, int align, gemui_color_t c) { + double sc = (t && t->scale > 0.0) ? t->scale : 1.0; + int base_px = (t && t->base_font_size > 0) ? t->base_font_size : anode_scale_px(15, sc); + int delta_px = (int)llround((double)pt_delta * sc); + int px = base_px + delta_px; + if (px < 8) px = 8; + const char *iface = (t && t->icon_font_face[0]) ? t->icon_font_face : "DejaVuSansM Nerd Font"; + return gemui_draw_pango(cr, iface, px, r, icon_utf8, false, align, c); +} + +void gemui_draw_header(gemui_app_t *app, cairo_t *cr, const char *icon, + const char *title, const char *right_badge) { + if (!app) return; + const gemui_theme_t *t = &app->theme; + int hh = gemui_scale_px(app, 42); + int div_h = gemui_scale_px(app, 1); + if (div_h < 1) div_h = 1; + gemui_fill_rect(cr, (gemui_rect_t){0, 0, app->w, hh}, t->bg_header); + gemui_fill_rect(cr, (gemui_rect_t){0, hh - div_h, app->w, div_h}, t->divider); + + int x = gemui_scale_px(app, 12); + int vpad = gemui_scale_px(app, 4); + int icon_w = gemui_scale_px(app, 28); + int badge_w = 0; + int badge_pad = gemui_scale_px(app, 10); + if (right_badge && right_badge[0]) { + badge_w = gemui_scale_px(app, 210); + if (badge_w > app->w / 3) badge_w = app->w / 3; + gemui_rect_t br = { + app->w - badge_w - badge_pad, + gemui_scale_px(app, 6), + badge_w, + hh - gemui_scale_px(app, 12) + }; + double rad = (double)gemui_scale_px(app, 6); + gemui_fill_round(cr, br, rad, t->bg_overlay); + gemui_stroke_round(cr, br, rad, t->scale >= 1.5 ? 1.5 : 1.0, t->border); + int b_inset = gemui_scale_px(app, 8); + gemui_draw_text(cr, t, (gemui_rect_t){br.x + b_inset, br.y, br.w - b_inset * 2, br.h}, + right_badge, -1, false, GEMUI_ALIGN_CENTER, t->fg_main); + } + + if (icon && icon[0]) { + gemui_draw_icon(cr, t, (gemui_rect_t){x, vpad, icon_w, hh - vpad * 2}, + icon, 3, GEMUI_ALIGN_CENTER, t->accent); + x += icon_w + gemui_scale_px(app, 6); + } + int title_w = app->w - x - (badge_w > 0 ? badge_w + badge_pad * 2 : x); + gemui_draw_text(cr, t, (gemui_rect_t){x, vpad, title_w, hh - vpad * 2}, + title ? title : "", 2, true, GEMUI_ALIGN_LEFT, t->fg_bright); +} + +void gemui_draw_button(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *label, int hit_id, int hit_val, + bool primary, bool active, bool focused) { + 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; + 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); + int pad = gemui_scale_px(app, 6); + + gemui_fill_round(cr, r, rad, bg); + gemui_stroke_round(cr, r, rad, lw, bd); + gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad, r.y + 1, r.w - pad * 2, r.h - 2}, + label ? label : "", 0, primary || active, GEMUI_ALIGN_CENTER, fg); + if (hit_id >= 0) { + gemui_hit_add(app, r, hit_id, hit_val); + } +} + +void gemui_draw_toggle(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *label, bool on, int hit_id, int hit_val, bool focused) { + if (!app) return; + const gemui_theme_t *t = &app->theme; + 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->highlight : t->border); + + int pill_w = gemui_scale_px(app, 48); + int pill_h = gemui_scale_px(app, 24); + if (pill_h > r.h - 4) pill_h = r.h - 4; + int pad_x = gemui_scale_px(app, 10); + int k_inset = gemui_scale_px(app, 2); + if (k_inset < 2) k_inset = 2; + int k_sz = pill_h - k_inset * 2; + + gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad_x, r.y, r.w - pill_w - pad_x * 3, r.h}, + label ? label : "", 0, false, GEMUI_ALIGN_LEFT, t->fg_main); + + gemui_rect_t pill = {r.x + r.w - pill_w - pad_x, r.y + (r.h - pill_h) / 2, pill_w, pill_h}; + gemui_fill_round(cr, pill, (double)pill_h / 2.0, on ? t->success : t->bg_overlay); + gemui_stroke_round(cr, pill, (double)pill_h / 2.0, lw, on ? t->success : t->border); + + gemui_rect_t knob = {on ? (pill.x + pill.w - k_sz - k_inset) : (pill.x + k_inset), + pill.y + k_inset, k_sz, k_sz}; + gemui_fill_round(cr, knob, (double)k_sz / 2.0, t->fg_bright); + if (hit_id >= 0) { + gemui_hit_add(app, r, hit_id, hit_val); + } +} + +void gemui_draw_slider(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *label, double norm_val, const char *val_text, + int hit_id, int hit_val, bool focused) { + if (!app) return; + const gemui_theme_t *t = &app->theme; + if (norm_val < 0.0) norm_val = 0.0; + if (norm_val > 1.0) norm_val = 1.0; + + 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); + int pad_x = gemui_scale_px(app, 10); + int top_y = r.y + gemui_scale_px(app, 4); + int txt_h = gemui_scale_px(app, 22); + + gemui_fill_round(cr, r, rad, t->bg_alt_even); + gemui_stroke_round(cr, r, rad, lw, focused ? t->highlight : t->border); + + gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad_x, top_y, r.w / 2, txt_h}, + label ? label : "", -1, true, GEMUI_ALIGN_LEFT, t->fg_bright); + if (val_text && val_text[0]) { + gemui_draw_text(cr, t, (gemui_rect_t){r.x + r.w / 2, top_y, r.w / 2 - pad_x, txt_h}, + val_text, -1, false, GEMUI_ALIGN_RIGHT, t->accent); + } + + int track_h = gemui_scale_px(app, 8); + int knob_d = gemui_scale_px(app, 16); + int track_y = r.y + r.h - gemui_scale_px(app, 14); + gemui_rect_t track = {r.x + pad_x, track_y, r.w - pad_x * 2, track_h}; + gemui_fill_round(cr, track, (double)track_h / 2.0, t->bg_overlay); + int fw = (int)(track.w * norm_val); + if (fw > 0) { + gemui_fill_round(cr, (gemui_rect_t){track.x, track.y, fw, track.h}, + (double)track_h / 2.0, t->accent); + } + int kx = track.x + fw - knob_d / 2; + if (kx < track.x) kx = track.x; + if (kx > track.x + track.w - knob_d) kx = track.x + track.w - knob_d; + gemui_rect_t knob = {kx, track.y + (track.h - knob_d) / 2, knob_d, knob_d}; + gemui_fill_round(cr, knob, (double)knob_d / 2.0, t->fg_bright); + if (hit_id >= 0) { + gemui_hit_add(app, r, hit_id, hit_val); + } +} + +void gemui_draw_input(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *placeholder, const char *text, bool mask_bullets, + bool focused, int hit_id, int hit_val) { + if (!app) return; + const gemui_theme_t *t = &app->theme; + 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); + int pad = gemui_scale_px(app, 8); + gemui_fill_round(cr, r, rad, focused ? t->bg_input_focus : t->bg_input); + gemui_stroke_round(cr, r, rad, lw, focused ? t->accent : t->border); + + char display[512]; + bool empty = (!text || !text[0]); + if (empty) { + snprintf(display, sizeof(display), "%s", placeholder ? placeholder : ""); + } else if (mask_bullets) { + size_t len = strlen(text); + if (len > 48) len = 48; + for (size_t i = 0; i < len; i++) display[i] = '*'; + if (focused && len + 1 < sizeof(display)) display[len++] = '_'; + display[len] = '\0'; + } else { + snprintf(display, sizeof(display), "%s%s", text, focused ? "_" : ""); + } + if (empty && focused && mask_bullets) { + snprintf(display, sizeof(display), "%s", placeholder ? placeholder : "_"); + } + + gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad, r.y + 1, r.w - pad * 2, r.h - 2}, + display, 0, false, GEMUI_ALIGN_LEFT, empty ? t->fg_muted : t->fg_bright); + if (hit_id >= 0) { + gemui_hit_add(app, r, hit_id, hit_val); + } +} + +void gemui_draw_toast(gemui_app_t *app, cairo_t *cr) { + if (!app || !app->toast_msg[0]) return; + const gemui_theme_t *t = &app->theme; + int tw = gemui_scale_px(app, 420); + int max_w = app->w - gemui_scale_px(app, 40); + if (tw > max_w) tw = max_w; + int th = gemui_scale_px(app, 36); + int ty = app->h - th - gemui_scale_px(app, 18); + gemui_rect_t r = {(app->w - tw) / 2, ty, tw, th}; + double rad = (double)gemui_scale_px(app, 6); + gemui_fill_round(cr, r, rad, t->bg_toast); + gemui_stroke_round(cr, r, rad, t->scale >= 1.5 ? 2.0 : 1.5, t->accent); + int pad = gemui_scale_px(app, 10); + gemui_draw_text(cr, t, (gemui_rect_t){r.x + pad, r.y + 2, r.w - pad * 2, r.h - 4}, + app->toast_msg, -1, true, GEMUI_ALIGN_CENTER, t->fg_bright); +} + +int gemui_unix_cmd(const char *sock_path, const char *cmd, char *resp, size_t resp_sz) { + if (!sock_path || !cmd) return -1; + int fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) return -1; + + struct timeval tv = {1, 0}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", sock_path); + + if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + close(fd); + return -1; + } + size_t len = strlen(cmd); + if (send(fd, cmd, len, MSG_NOSIGNAL) < 0 || + ((len == 0 || cmd[len - 1] != '\n') ? send(fd, "\n", 1, MSG_NOSIGNAL) < 0 : 0)) { + close(fd); + return -1; + } + shutdown(fd, SHUT_WR); + if (resp && resp_sz > 0) { + size_t off = 0; + while (off + 1 < resp_sz) { + ssize_t n = recv(fd, resp + off, resp_sz - 1 - off, 0); + if (n <= 0) break; + off += (size_t)n; + } + resp[off] = '\0'; + } else { + char sink[64]; + while (recv(fd, sink, sizeof(sink), 0) > 0) {} + } + close(fd); + return 0; +} + +int gemui_read_file_line(const char *path, char *buf, size_t sz) { + if (!path || !buf || sz == 0) return -1; + FILE *f = fopen(path, "r"); + if (!f) return -1; + if (!fgets(buf, (int)sz, f)) { + fclose(f); + return -1; + } + fclose(f); + size_t n = strlen(buf); + while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) { + buf[--n] = '\0'; + } + return 0; +} + +int gemui_run_cmd_timeout(const char *const argv[], char *out, size_t out_sz, int timeout_ms) { + return anode_run_cmd_timeout(argv, out, out_sz, timeout_ms); +} + +int gemui_run_cmd_capture(const char *const argv[], char *out, size_t out_sz) { + return anode_run_cmd_timeout(argv, out, out_sz, 2500); +} + +int gemui_spawn_detached(const char *const argv[]) { + return anode_spawn_detached(argv); +} + +void gemui_utf8_pop_char(char *buf) { + if (!buf) return; + size_t len = strlen(buf); + while (len > 0) { + len--; + unsigned char ch = (unsigned char)buf[len]; + buf[len] = '\0'; + if ((ch & 0xc0) != 0x80) break; + } +} diff --git a/src/libgemui/gemui.h b/src/libgemui/gemui.h new file mode 100644 index 0000000..c254ae8 --- /dev/null +++ b/src/libgemui/gemui.h @@ -0,0 +1,175 @@ +/* + * ANODE UI Toolkit (libgemui) + * Pure C11 X11 + Cairo + Pango/HarfBuzz UI library with live .Xresources theming and fractional DPI scaling. + */ +#ifndef GEMUI_H +#define GEMUI_H + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define GEMUI_ALIGN_LEFT 0 +#define GEMUI_ALIGN_CENTER 1 +#define GEMUI_ALIGN_RIGHT 2 + +#define GEMUI_PTR_DOWN 0 +#define GEMUI_PTR_MOVE 1 +#define GEMUI_PTR_UP 2 +#define GEMUI_PTR_SCROLL_UP 3 +#define GEMUI_PTR_SCROLL_DOWN 4 + +#define GEMUI_MAX_HITS 192 +#define GEMUI_MAX_FDS 16 + +typedef struct { + double r; + double g; + double b; + double a; + uint32_t argb; +} gemui_color_t; + +typedef struct { + int x; + int y; + int w; + int h; +} gemui_rect_t; + +typedef struct { + gemui_rect_t r; + int id; + int val; +} gemui_hit_t; + +typedef struct { + char name[64]; + char font_face[96]; + char icon_font_face[96]; + int base_font_size; + int dpi; + double scale; + bool touch_mode; + gemui_color_t bg_main; + gemui_color_t bg_bar; + gemui_color_t bg_header; + gemui_color_t bg_footer; + gemui_color_t bg_overlay; + gemui_color_t bg_alt_even; + gemui_color_t bg_alt_odd; + gemui_color_t bg_input; + gemui_color_t bg_input_focus; + gemui_color_t bg_button; + gemui_color_t bg_search; + gemui_color_t bg_bubble_in; + gemui_color_t bg_bubble_out; + gemui_color_t bg_toast; + gemui_color_t fg_main; + gemui_color_t fg_bright; + gemui_color_t fg_muted; + gemui_color_t sel_bg; + gemui_color_t sel_fg; + gemui_color_t accent; + gemui_color_t accent_alt; + gemui_color_t highlight; + gemui_color_t border; + gemui_color_t divider; + gemui_color_t success; + gemui_color_t info; + gemui_color_t warning; + gemui_color_t danger; + gemui_color_t danger_bg; +} gemui_theme_t; + +typedef struct gemui_app gemui_app_t; + +typedef void (*gemui_fd_cb)(gemui_app_t *app, int fd, void *ud); +typedef void (*gemui_timer_cb)(gemui_app_t *app, void *ud); + +typedef struct { + void (*on_draw)(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud); + void (*on_key)(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud); + void (*on_ptr)(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud); + void (*on_theme)(gemui_app_t *app, void *ud); + void (*on_resize)(gemui_app_t *app, int w, int h, void *ud); +} gemui_handlers_t; + +bool gemui_color_parse(const char *hex, gemui_color_t *out); +void gemui_theme_defaults(gemui_theme_t *t); +bool gemui_theme_load_file(const char *path, gemui_theme_t *out); +void gemui_theme_reload(gemui_app_t *app); + +gemui_app_t *gemui_create(const char *res_name, const char *title, + int w, int h, bool fullscreen_override); +void gemui_destroy(gemui_app_t *app); +void gemui_set_handlers(gemui_app_t *app, const gemui_handlers_t *h, void *userdata); +void gemui_set_title(gemui_app_t *app, const char *title); +Display *gemui_display(const gemui_app_t *app); +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); +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); +int gemui_touch_row_px(const gemui_app_t *app, int logical_px); + +int gemui_add_fd(gemui_app_t *app, int fd, gemui_fd_cb cb, void *userdata); +void gemui_del_fd(gemui_app_t *app, int fd); +void gemui_set_timer_ms(gemui_app_t *app, int interval_ms, gemui_timer_cb cb, void *userdata); +void gemui_request_redraw(gemui_app_t *app); +void gemui_flush_draw(gemui_app_t *app); +void gemui_show_toast(gemui_app_t *app, const char *msg, int duration_ms); +int gemui_run(gemui_app_t *app); +void gemui_quit(gemui_app_t *app, int code); +bool gemui_grab_input(gemui_app_t *app); +void gemui_ungrab_input(gemui_app_t *app); + +void gemui_hits_clear(gemui_app_t *app); +void gemui_hit_add(gemui_app_t *app, gemui_rect_t r, int id, int val); +const gemui_hit_t *gemui_hit_test(const gemui_app_t *app, int x, int y); + +void gemui_set_source(cairo_t *cr, gemui_color_t c); +void gemui_rounded_rect(cairo_t *cr, gemui_rect_t r, double radius); +void gemui_fill_rect(cairo_t *cr, gemui_rect_t r, gemui_color_t c); +void gemui_fill_round(cairo_t *cr, gemui_rect_t r, double radius, gemui_color_t c); +void gemui_stroke_round(cairo_t *cr, gemui_rect_t r, double radius, double lw, gemui_color_t c); +int gemui_draw_text(cairo_t *cr, const gemui_theme_t *t, gemui_rect_t r, + const char *text, int pt_delta, bool bold, int align, gemui_color_t c); +int gemui_draw_icon(cairo_t *cr, const gemui_theme_t *t, gemui_rect_t r, + const char *icon_utf8, int pt_delta, int align, gemui_color_t c); +void gemui_draw_header(gemui_app_t *app, cairo_t *cr, const char *icon, + const char *title, const char *right_badge); +void gemui_draw_button(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *label, int hit_id, int hit_val, + bool primary, bool active, bool focused); +void gemui_draw_toggle(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *label, bool on, int hit_id, int hit_val, bool focused); +void gemui_draw_slider(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *label, double norm_val, const char *val_text, + int hit_id, int hit_val, bool focused); +void gemui_draw_input(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, + const char *placeholder, const char *text, bool mask_bullets, + bool focused, int hit_id, int hit_val); +void gemui_draw_toast(gemui_app_t *app, cairo_t *cr); + +int gemui_unix_cmd(const char *sock_path, const char *cmd, char *resp, size_t resp_sz); +int gemui_read_file_line(const char *path, char *buf, size_t sz); +int gemui_run_cmd_timeout(const char *const argv[], char *out, size_t out_sz, int timeout_ms); +int gemui_run_cmd_capture(const char *const argv[], char *out, size_t out_sz); +int gemui_spawn_detached(const char *const argv[]); +void gemui_utf8_pop_char(char *buf); + +#ifdef __cplusplus +} +#endif + +#endif /* GEMUI_H */ diff --git a/src/libgemui/gemui.pc.in b/src/libgemui/gemui.pc.in new file mode 100644 index 0000000..a37a2c1 --- /dev/null +++ b/src/libgemui/gemui.pc.in @@ -0,0 +1,11 @@ +prefix=@PREFIX@ +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include + +Name: gemui +Description: ANODE GemUI X11 + Cairo + Pango/HarfBuzz UI toolkit +Version: @VERSION@ +Requires.private: x11 xext xft xinerama xrandr cairo pangocairo pango harfbuzz fontconfig freetype2 +Libs: -L${libdir} -Wl,-rpath,${libdir} -lgemui -lm +Cflags: -I${includedir} diff --git a/src/st/arg.h b/src/st/arg.h new file mode 100644 index 0000000..a22e019 --- /dev/null +++ b/src/st/arg.h @@ -0,0 +1,50 @@ +/* + * Copy me if you can. + * by 20h + */ + +#ifndef ARG_H__ +#define ARG_H__ + +extern char *argv0; + +/* use main(int argc, char *argv[]) */ +#define ARGBEGIN for (argv0 = *argv, argv++, argc--;\ + argv[0] && argv[0][0] == '-'\ + && argv[0][1];\ + argc--, argv++) {\ + char argc_;\ + char **argv_;\ + int brk_;\ + if (argv[0][1] == '-' && argv[0][2] == '\0') {\ + argv++;\ + argc--;\ + break;\ + }\ + int i_;\ + for (i_ = 1, brk_ = 0, argv_ = argv;\ + argv[0][i_] && !brk_;\ + i_++) {\ + if (argv_ != argv)\ + break;\ + argc_ = argv[0][i_];\ + switch (argc_) + +#define ARGEND }\ + } + +#define ARGC() argc_ + +#define EARGF(x) ((argv[0][i_+1] == '\0' && argv[1] == NULL)?\ + ((x), abort(), (char *)0) :\ + (brk_ = 1, (argv[0][i_+1] != '\0')?\ + (&argv[0][i_+1]) :\ + (argc--, argv++, argv[0]))) + +#define ARGF() ((argv[0][i_+1] == '\0' && argv[1] == NULL)?\ + (char *)0 :\ + (brk_ = 1, (argv[0][i_+1] != '\0')?\ + (&argv[0][i_+1]) :\ + (argc--, argv++, argv[0]))) + +#endif diff --git a/src/st/config.def.h b/src/st/config.def.h new file mode 100644 index 0000000..9189fdb --- /dev/null +++ b/src/st/config.def.h @@ -0,0 +1,522 @@ +/* See LICENSE file for copyright and license details. */ + +/* + * appearance + * + * font: see http://freedesktop.org/software/fontconfig/fontconfig-user.html + */ +static char *font = "Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true"; +static int borderpx = 2; + +/* + * What program is execed by st depends of these precedence rules: + * 1: program passed with -e + * 2: scroll and/or utmp + * 3: SHELL environment variable + * 4: value of shell in /etc/passwd + * 5: value of shell in config.h + */ +static char *shell = "/bin/sh"; +char *utmp = NULL; +/* scroll program: to enable use a string like "scroll" */ +char *scroll = NULL; +char *stty_args = "stty raw pass8 nl -echo -iexten -cstopb 38400"; + +/* identification sequence returned in DA and DECID */ +char *vtiden = "\033[?6c"; + +/* Kerning / character bounding-box multipliers */ +static float cwscale = 1.0; +static float chscale = 1.0; + +/* + * word delimiter string + * + * More advanced example: L" `'\"()[]{}" + */ +wchar_t *worddelimiters = L" "; + +/* selection timeouts (in milliseconds) */ +static unsigned int doubleclicktimeout = 1000; +static unsigned int tripleclicktimeout = 2000; + +/* alt screens */ +int allowaltscreen = 1; + +/* allow certain non-interactive (insecure) window operations such as: + setting the clipboard text */ +int allowwindowops = 0; + +/* + * draw latency range in ms - from new content/keypress/etc until drawing. + * within this range, st draws when content stops arriving (idle). mostly it's + * near minlatency, but it waits longer for slow updates to avoid partial draw. + * low minlatency will tear/flicker more, as it can "detect" idle too early. + */ +static double minlatency = 8; +static double maxlatency = 33; + +/* + * blinking timeout (set to 0 to disable blinking) for the terminal blinking + * attribute. + */ +static unsigned int blinktimeout = 800; + +/* + * thickness of underline and bar cursors + */ +static unsigned int cursorthickness = 2; + +/* + * bell volume. It must be a value between -100 and 100. Use 0 for disabling + * it + */ +static int bellvolume = 0; + +/* default TERM value */ +char *termname = "st-256color"; + +/* + * spaces per tab + * + * When you are changing this value, don't forget to adapt the »it« value in + * the st.info and appropriately install the st.info in the environment where + * you use this st version. + * + * it#$tabspaces, + * + * Secondly make sure your kernel is not expanding tabs. When running `stty + * -a` »tab0« should appear. You can tell the terminal to not expand tabs by + * running following command: + * + * stty tabs + */ +unsigned int tabspaces = 8; + +/* Terminal colors (16 first used in escape sequence) */ +static const char *colorname[] = { + /* 8 normal colors */ + "black", + "red3", + "green3", + "yellow3", + "blue2", + "magenta3", + "cyan3", + "gray90", + + /* 8 bright colors */ + "gray50", + "red", + "green", + "yellow", + "#5c5cff", + "magenta", + "cyan", + "white", + + [255] = 0, + + /* more colors can be added after 255 to use with DefaultXX */ + "#161616", + "#dddddd", + "#f4d03f", + "#555555", +}; + + +/* + * Default colors (colorname index) + * foreground, background, cursor, reverse cursor + */ +unsigned int defaultfg = 257; +unsigned int defaultbg = 256; +static unsigned int defaultcs = 258; +static unsigned int defaultrcs = 259; + +/* + * Default shape of cursor + * 2: Block ("█") + * 4: Underline ("_") + * 6: Bar ("|") + * 7: Snowman ("☃") + */ +static unsigned int cursorshape = 2; + +/* + * Default columns and rows numbers + */ + +static unsigned int cols = 80; +static unsigned int rows = 24; + +/* + * Default colour and shape of the mouse cursor + */ +static unsigned int mouseshape = XC_xterm; +static unsigned int mousefg = 7; +static unsigned int mousebg = 0; + +/* + * Color used to display font attributes when fontconfig selected a font which + * doesn't match the ones requested. + */ +static unsigned int defaultattr = 11; + +/* + * Force mouse select/shortcuts while mask is active (when MODE_MOUSE is set). + * Note that if you want to use ShiftMask with selmasks, set this to an other + * modifier, set to 0 to not use it. + */ +static uint forcemousemod = ShiftMask; + +/* + * Xresources preferences to load at startup + */ +ResourcePref resources[] = { + { "font", STRING, &font }, + { "color0", STRING, &colorname[0] }, + { "color1", STRING, &colorname[1] }, + { "color2", STRING, &colorname[2] }, + { "color3", STRING, &colorname[3] }, + { "color4", STRING, &colorname[4] }, + { "color5", STRING, &colorname[5] }, + { "color6", STRING, &colorname[6] }, + { "color7", STRING, &colorname[7] }, + { "color8", STRING, &colorname[8] }, + { "color9", STRING, &colorname[9] }, + { "color10", STRING, &colorname[10] }, + { "color11", STRING, &colorname[11] }, + { "color12", STRING, &colorname[12] }, + { "color13", STRING, &colorname[13] }, + { "color14", STRING, &colorname[14] }, + { "color15", STRING, &colorname[15] }, + { "background", STRING, &colorname[256] }, + { "foreground", STRING, &colorname[257] }, + { "cursorColor", STRING, &colorname[258] }, + { "termname", STRING, &termname }, + { "shell", STRING, &shell }, + { "blinktimeout", INTEGER, &blinktimeout }, + { "bellvolume", INTEGER, &bellvolume }, + { "tabspaces", INTEGER, &tabspaces }, + { "borderpx", INTEGER, &borderpx }, + { "cwscale", FLOAT, &cwscale }, + { "chscale", FLOAT, &chscale }, +}; + +/* + * Internal mouse shortcuts. + * Beware that overloading Button1 will disable the selection. + */ +static MouseShortcut mshortcuts[] = { + /* mask button function argument release */ + { XK_ANY_MOD, Button2, selpaste, {.i = 0}, 1 }, + { ShiftMask, Button4, kscrollup, {.i = 3} }, + { XK_ANY_MOD, Button4, wheelscrollup, {.i = 3} }, + { ShiftMask, Button5, kscrolldown, {.i = 3} }, + { XK_ANY_MOD, Button5, wheelscrolldown, {.i = 3} }, +}; + +/* Internal keyboard shortcuts. */ +#define MODKEY Mod1Mask +#define TERMMOD (ControlMask|ShiftMask) + +static Shortcut shortcuts[] = { + /* mask keysym function argument */ + { XK_ANY_MOD, XK_Break, sendbreak, {.i = 0} }, + { ControlMask, XK_Print, toggleprinter, {.i = 0} }, + { ShiftMask, XK_Print, printscreen, {.i = 0} }, + { XK_ANY_MOD, XK_Print, printsel, {.i = 0} }, + { TERMMOD, XK_Prior, zoom, {.f = +1} }, + { TERMMOD, XK_Next, zoom, {.f = -1} }, + { TERMMOD, XK_Home, zoomreset, {.f = 0} }, + { TERMMOD, XK_0, zoomreset, {.f = 0} }, + { TERMMOD, XK_parenright, zoomreset, {.f = 0} }, + { TERMMOD, XK_equal, zoom, {.f = +1} }, + { TERMMOD, XK_minus, zoom, {.f = -1} }, + { TERMMOD, XK_C, clipcopy, {.i = 0} }, + { TERMMOD, XK_V, clippaste, {.i = 0} }, + { TERMMOD, XK_Y, selpaste, {.i = 0} }, + { ShiftMask, XK_Insert, selpaste, {.i = 0} }, + { TERMMOD, XK_Num_Lock, numlock, {.i = 0} }, + + { TERMMOD, XK_S, toggleselectionmode, {.i = 0} }, + + { ShiftMask, XK_Prior, kscrollup, {.i = -1} }, + { ShiftMask, XK_Next, kscrolldown, {.i = -1} }, + { TERMMOD, XK_B, kscrollup, {.i = -1} }, + { TERMMOD, XK_F, kscrolldown, {.i = -1} }, + { TERMMOD, XK_X, invert, { } }, + { TERMMOD, XK_plus, zoom, {.f = +1} }, + { TERMMOD, XK_underscore, zoom, {.f = -1} }, +}; + +/* + * Special keys (change & recompile st.info accordingly) + * + * Mask value: + * * Use XK_ANY_MOD to match the key no matter modifiers state + * * Use XK_NO_MOD to match the key alone (no modifiers) + * appkey value: + * * 0: no value + * * > 0: keypad application mode enabled + * * = 2: term.numlock = 1 + * * < 0: keypad application mode disabled + * appcursor value: + * * 0: no value + * * > 0: cursor application mode enabled + * * < 0: cursor application mode disabled + * + * Be careful with the order of the definitions because st searches in + * this table sequentially, so any XK_ANY_MOD must be in the last + * position for a key. + */ + +/* + * If you want keys other than the X11 function keys (0xFD00 - 0xFFFF) + * to be mapped below, add them to this array. + */ +static KeySym mappedkeys[] = { -1 }; + +/* + * State bits to ignore when matching key or button events. By default, + * numlock (Mod2Mask), AltGr/Fn (Mod5Mask), and keyboard layout (XK_SWITCH_MOD) are ignored. + */ +static uint ignoremod = Mod2Mask|Mod5Mask|XK_SWITCH_MOD; + +/* + * This is the huge key array which defines all compatibility to the Linux + * world. Please decide about changes wisely. + */ +static Key key[] = { + /* keysym mask string appkey appcursor */ + { XK_KP_Home, ShiftMask, "\033[2J", 0, -1}, + { XK_KP_Home, ShiftMask, "\033[1;2H", 0, +1}, + { XK_KP_Home, XK_ANY_MOD, "\033[H", 0, -1}, + { XK_KP_Home, XK_ANY_MOD, "\033[1~", 0, +1}, + { XK_KP_Up, XK_ANY_MOD, "\033Ox", +1, 0}, + { XK_KP_Up, XK_ANY_MOD, "\033[A", 0, -1}, + { XK_KP_Up, XK_ANY_MOD, "\033OA", 0, +1}, + { XK_KP_Down, XK_ANY_MOD, "\033Or", +1, 0}, + { XK_KP_Down, XK_ANY_MOD, "\033[B", 0, -1}, + { XK_KP_Down, XK_ANY_MOD, "\033OB", 0, +1}, + { XK_KP_Left, XK_ANY_MOD, "\033Ot", +1, 0}, + { XK_KP_Left, XK_ANY_MOD, "\033[D", 0, -1}, + { XK_KP_Left, XK_ANY_MOD, "\033OD", 0, +1}, + { XK_KP_Right, XK_ANY_MOD, "\033Ov", +1, 0}, + { XK_KP_Right, XK_ANY_MOD, "\033[C", 0, -1}, + { XK_KP_Right, XK_ANY_MOD, "\033OC", 0, +1}, + { XK_KP_Prior, ShiftMask, "\033[5;2~", 0, 0}, + { XK_KP_Prior, XK_ANY_MOD, "\033[5~", 0, 0}, + { XK_KP_Begin, XK_ANY_MOD, "\033[E", 0, 0}, + { XK_KP_End, ControlMask, "\033[J", -1, 0}, + { XK_KP_End, ControlMask, "\033[1;5F", +1, 0}, + { XK_KP_End, ShiftMask, "\033[K", -1, 0}, + { XK_KP_End, ShiftMask, "\033[1;2F", +1, 0}, + { XK_KP_End, XK_ANY_MOD, "\033[4~", 0, 0}, + { XK_KP_Next, ShiftMask, "\033[6;2~", 0, 0}, + { XK_KP_Next, XK_ANY_MOD, "\033[6~", 0, 0}, + { XK_KP_Insert, ShiftMask, "\033[2;2~", +1, 0}, + { XK_KP_Insert, ShiftMask, "\033[4l", -1, 0}, + { XK_KP_Insert, ControlMask, "\033[L", -1, 0}, + { XK_KP_Insert, ControlMask, "\033[2;5~", +1, 0}, + { XK_KP_Insert, XK_ANY_MOD, "\033[4h", -1, 0}, + { XK_KP_Insert, XK_ANY_MOD, "\033[2~", +1, 0}, + { XK_KP_Delete, ControlMask, "\033[M", -1, 0}, + { XK_KP_Delete, ControlMask, "\033[3;5~", +1, 0}, + { XK_KP_Delete, ShiftMask, "\033[2K", -1, 0}, + { XK_KP_Delete, ShiftMask, "\033[3;2~", +1, 0}, + { XK_KP_Delete, XK_ANY_MOD, "\033[P", -1, 0}, + { XK_KP_Delete, XK_ANY_MOD, "\033[3~", +1, 0}, + { XK_KP_Multiply, XK_ANY_MOD, "\033Oj", +2, 0}, + { XK_KP_Add, XK_ANY_MOD, "\033Ok", +2, 0}, + { XK_KP_Enter, XK_ANY_MOD, "\033OM", +2, 0}, + { XK_KP_Enter, XK_ANY_MOD, "\r", -1, 0}, + { XK_KP_Subtract, XK_ANY_MOD, "\033Om", +2, 0}, + { XK_KP_Decimal, XK_ANY_MOD, "\033On", +2, 0}, + { XK_KP_Divide, XK_ANY_MOD, "\033Oo", +2, 0}, + { XK_KP_0, XK_ANY_MOD, "\033Op", +2, 0}, + { XK_KP_1, XK_ANY_MOD, "\033Oq", +2, 0}, + { XK_KP_2, XK_ANY_MOD, "\033Or", +2, 0}, + { XK_KP_3, XK_ANY_MOD, "\033Os", +2, 0}, + { XK_KP_4, XK_ANY_MOD, "\033Ot", +2, 0}, + { XK_KP_5, XK_ANY_MOD, "\033Ou", +2, 0}, + { XK_KP_6, XK_ANY_MOD, "\033Ov", +2, 0}, + { XK_KP_7, XK_ANY_MOD, "\033Ow", +2, 0}, + { XK_KP_8, XK_ANY_MOD, "\033Ox", +2, 0}, + { XK_KP_9, XK_ANY_MOD, "\033Oy", +2, 0}, + { XK_Up, ShiftMask, "\033[1;2A", 0, 0}, + { XK_Up, Mod1Mask, "\033[1;3A", 0, 0}, + { XK_Up, ShiftMask|Mod1Mask,"\033[1;4A", 0, 0}, + { XK_Up, ControlMask, "\033[1;5A", 0, 0}, + { XK_Up, ShiftMask|ControlMask,"\033[1;6A", 0, 0}, + { XK_Up, ControlMask|Mod1Mask,"\033[1;7A", 0, 0}, + { XK_Up,ShiftMask|ControlMask|Mod1Mask,"\033[1;8A", 0, 0}, + { XK_Up, XK_ANY_MOD, "\033[A", 0, -1}, + { XK_Up, XK_ANY_MOD, "\033OA", 0, +1}, + { XK_Down, ShiftMask, "\033[1;2B", 0, 0}, + { XK_Down, Mod1Mask, "\033[1;3B", 0, 0}, + { XK_Down, ShiftMask|Mod1Mask,"\033[1;4B", 0, 0}, + { XK_Down, ControlMask, "\033[1;5B", 0, 0}, + { XK_Down, ShiftMask|ControlMask,"\033[1;6B", 0, 0}, + { XK_Down, ControlMask|Mod1Mask,"\033[1;7B", 0, 0}, + { XK_Down,ShiftMask|ControlMask|Mod1Mask,"\033[1;8B",0, 0}, + { XK_Down, XK_ANY_MOD, "\033[B", 0, -1}, + { XK_Down, XK_ANY_MOD, "\033OB", 0, +1}, + { XK_Left, ShiftMask, "\033[1;2D", 0, 0}, + { XK_Left, Mod1Mask, "\033[1;3D", 0, 0}, + { XK_Left, ShiftMask|Mod1Mask,"\033[1;4D", 0, 0}, + { XK_Left, ControlMask, "\033[1;5D", 0, 0}, + { XK_Left, ShiftMask|ControlMask,"\033[1;6D", 0, 0}, + { XK_Left, ControlMask|Mod1Mask,"\033[1;7D", 0, 0}, + { XK_Left,ShiftMask|ControlMask|Mod1Mask,"\033[1;8D",0, 0}, + { XK_Left, XK_ANY_MOD, "\033[D", 0, -1}, + { XK_Left, XK_ANY_MOD, "\033OD", 0, +1}, + { XK_Right, ShiftMask, "\033[1;2C", 0, 0}, + { XK_Right, Mod1Mask, "\033[1;3C", 0, 0}, + { XK_Right, ShiftMask|Mod1Mask,"\033[1;4C", 0, 0}, + { XK_Right, ControlMask, "\033[1;5C", 0, 0}, + { XK_Right, ShiftMask|ControlMask,"\033[1;6C", 0, 0}, + { XK_Right, ControlMask|Mod1Mask,"\033[1;7C", 0, 0}, + { XK_Right,ShiftMask|ControlMask|Mod1Mask,"\033[1;8C",0, 0}, + { XK_Right, XK_ANY_MOD, "\033[C", 0, -1}, + { XK_Right, XK_ANY_MOD, "\033OC", 0, +1}, + { XK_ISO_Left_Tab, ShiftMask, "\033[Z", 0, 0}, + { XK_Return, Mod1Mask, "\033\r", 0, 0}, + { XK_Return, XK_ANY_MOD, "\r", 0, 0}, + { XK_Insert, ShiftMask, "\033[4l", -1, 0}, + { XK_Insert, ShiftMask, "\033[2;2~", +1, 0}, + { XK_Insert, ControlMask, "\033[L", -1, 0}, + { XK_Insert, ControlMask, "\033[2;5~", +1, 0}, + { XK_Insert, XK_ANY_MOD, "\033[4h", -1, 0}, + { XK_Insert, XK_ANY_MOD, "\033[2~", +1, 0}, + { XK_Delete, ControlMask, "\033[M", -1, 0}, + { XK_Delete, ControlMask, "\033[3;5~", +1, 0}, + { XK_Delete, ShiftMask, "\033[2K", -1, 0}, + { XK_Delete, ShiftMask, "\033[3;2~", +1, 0}, + { XK_Delete, XK_ANY_MOD, "\033[P", -1, 0}, + { XK_Delete, XK_ANY_MOD, "\033[3~", +1, 0}, + { XK_BackSpace, XK_NO_MOD, "\177", 0, 0}, + { XK_BackSpace, Mod1Mask, "\033\177", 0, 0}, + { XK_Home, ShiftMask, "\033[2J", 0, -1}, + { XK_Home, ShiftMask, "\033[1;2H", 0, +1}, + { XK_Home, XK_ANY_MOD, "\033[H", 0, -1}, + { XK_Home, XK_ANY_MOD, "\033[1~", 0, +1}, + { XK_End, ControlMask, "\033[J", -1, 0}, + { XK_End, ControlMask, "\033[1;5F", +1, 0}, + { XK_End, ShiftMask, "\033[K", -1, 0}, + { XK_End, ShiftMask, "\033[1;2F", +1, 0}, + { XK_End, XK_ANY_MOD, "\033[4~", 0, 0}, + { XK_Prior, ControlMask, "\033[5;5~", 0, 0}, + { XK_Prior, ShiftMask, "\033[5;2~", 0, 0}, + { XK_Prior, XK_ANY_MOD, "\033[5~", 0, 0}, + { XK_Next, ControlMask, "\033[6;5~", 0, 0}, + { XK_Next, ShiftMask, "\033[6;2~", 0, 0}, + { XK_Next, XK_ANY_MOD, "\033[6~", 0, 0}, + { XK_F1, XK_NO_MOD, "\033OP" , 0, 0}, + { XK_F1, /* F13 */ ShiftMask, "\033[1;2P", 0, 0}, + { XK_F1, /* F25 */ ControlMask, "\033[1;5P", 0, 0}, + { XK_F1, /* F37 */ Mod4Mask, "\033[1;6P", 0, 0}, + { XK_F1, /* F49 */ Mod1Mask, "\033[1;3P", 0, 0}, + { XK_F1, /* F61 */ Mod3Mask, "\033[1;4P", 0, 0}, + { XK_F2, XK_NO_MOD, "\033OQ" , 0, 0}, + { XK_F2, /* F14 */ ShiftMask, "\033[1;2Q", 0, 0}, + { XK_F2, /* F26 */ ControlMask, "\033[1;5Q", 0, 0}, + { XK_F2, /* F38 */ Mod4Mask, "\033[1;6Q", 0, 0}, + { XK_F2, /* F50 */ Mod1Mask, "\033[1;3Q", 0, 0}, + { XK_F2, /* F62 */ Mod3Mask, "\033[1;4Q", 0, 0}, + { XK_F3, XK_NO_MOD, "\033OR" , 0, 0}, + { XK_F3, /* F15 */ ShiftMask, "\033[1;2R", 0, 0}, + { XK_F3, /* F27 */ ControlMask, "\033[1;5R", 0, 0}, + { XK_F3, /* F39 */ Mod4Mask, "\033[1;6R", 0, 0}, + { XK_F3, /* F51 */ Mod1Mask, "\033[1;3R", 0, 0}, + { XK_F3, /* F63 */ Mod3Mask, "\033[1;4R", 0, 0}, + { XK_F4, XK_NO_MOD, "\033OS" , 0, 0}, + { XK_F4, /* F16 */ ShiftMask, "\033[1;2S", 0, 0}, + { XK_F4, /* F28 */ ControlMask, "\033[1;5S", 0, 0}, + { XK_F4, /* F40 */ Mod4Mask, "\033[1;6S", 0, 0}, + { XK_F4, /* F52 */ Mod1Mask, "\033[1;3S", 0, 0}, + { XK_F5, XK_NO_MOD, "\033[15~", 0, 0}, + { XK_F5, /* F17 */ ShiftMask, "\033[15;2~", 0, 0}, + { XK_F5, /* F29 */ ControlMask, "\033[15;5~", 0, 0}, + { XK_F5, /* F41 */ Mod4Mask, "\033[15;6~", 0, 0}, + { XK_F5, /* F53 */ Mod1Mask, "\033[15;3~", 0, 0}, + { XK_F6, XK_NO_MOD, "\033[17~", 0, 0}, + { XK_F6, /* F18 */ ShiftMask, "\033[17;2~", 0, 0}, + { XK_F6, /* F30 */ ControlMask, "\033[17;5~", 0, 0}, + { XK_F6, /* F42 */ Mod4Mask, "\033[17;6~", 0, 0}, + { XK_F6, /* F54 */ Mod1Mask, "\033[17;3~", 0, 0}, + { XK_F7, XK_NO_MOD, "\033[18~", 0, 0}, + { XK_F7, /* F19 */ ShiftMask, "\033[18;2~", 0, 0}, + { XK_F7, /* F31 */ ControlMask, "\033[18;5~", 0, 0}, + { XK_F7, /* F43 */ Mod4Mask, "\033[18;6~", 0, 0}, + { XK_F7, /* F55 */ Mod1Mask, "\033[18;3~", 0, 0}, + { XK_F8, XK_NO_MOD, "\033[19~", 0, 0}, + { XK_F8, /* F20 */ ShiftMask, "\033[19;2~", 0, 0}, + { XK_F8, /* F32 */ ControlMask, "\033[19;5~", 0, 0}, + { XK_F8, /* F44 */ Mod4Mask, "\033[19;6~", 0, 0}, + { XK_F8, /* F56 */ Mod1Mask, "\033[19;3~", 0, 0}, + { XK_F9, XK_NO_MOD, "\033[20~", 0, 0}, + { XK_F9, /* F21 */ ShiftMask, "\033[20;2~", 0, 0}, + { XK_F9, /* F33 */ ControlMask, "\033[20;5~", 0, 0}, + { XK_F9, /* F45 */ Mod4Mask, "\033[20;6~", 0, 0}, + { XK_F9, /* F57 */ Mod1Mask, "\033[20;3~", 0, 0}, + { XK_F10, XK_NO_MOD, "\033[21~", 0, 0}, + { XK_F10, /* F22 */ ShiftMask, "\033[21;2~", 0, 0}, + { XK_F10, /* F34 */ ControlMask, "\033[21;5~", 0, 0}, + { XK_F10, /* F46 */ Mod4Mask, "\033[21;6~", 0, 0}, + { XK_F10, /* F58 */ Mod1Mask, "\033[21;3~", 0, 0}, + { XK_F11, XK_NO_MOD, "\033[23~", 0, 0}, + { XK_F11, /* F23 */ ShiftMask, "\033[23;2~", 0, 0}, + { XK_F11, /* F35 */ ControlMask, "\033[23;5~", 0, 0}, + { XK_F11, /* F47 */ Mod4Mask, "\033[23;6~", 0, 0}, + { XK_F11, /* F59 */ Mod1Mask, "\033[23;3~", 0, 0}, + { XK_F12, XK_NO_MOD, "\033[24~", 0, 0}, + { XK_F12, /* F24 */ ShiftMask, "\033[24;2~", 0, 0}, + { XK_F12, /* F36 */ ControlMask, "\033[24;5~", 0, 0}, + { XK_F12, /* F48 */ Mod4Mask, "\033[24;6~", 0, 0}, + { XK_F12, /* F60 */ Mod1Mask, "\033[24;3~", 0, 0}, + { XK_F13, XK_NO_MOD, "\033[1;2P", 0, 0}, + { XK_F14, XK_NO_MOD, "\033[1;2Q", 0, 0}, + { XK_F15, XK_NO_MOD, "\033[1;2R", 0, 0}, + { XK_F16, XK_NO_MOD, "\033[1;2S", 0, 0}, + { XK_F17, XK_NO_MOD, "\033[15;2~", 0, 0}, + { XK_F18, XK_NO_MOD, "\033[17;2~", 0, 0}, + { XK_F19, XK_NO_MOD, "\033[18;2~", 0, 0}, + { XK_F20, XK_NO_MOD, "\033[19;2~", 0, 0}, + { XK_F21, XK_NO_MOD, "\033[20;2~", 0, 0}, + { XK_F22, XK_NO_MOD, "\033[21;2~", 0, 0}, + { XK_F23, XK_NO_MOD, "\033[23;2~", 0, 0}, + { XK_F24, XK_NO_MOD, "\033[24;2~", 0, 0}, + { XK_F25, XK_NO_MOD, "\033[1;5P", 0, 0}, + { XK_F26, XK_NO_MOD, "\033[1;5Q", 0, 0}, + { XK_F27, XK_NO_MOD, "\033[1;5R", 0, 0}, + { XK_F28, XK_NO_MOD, "\033[1;5S", 0, 0}, + { XK_F29, XK_NO_MOD, "\033[15;5~", 0, 0}, + { XK_F30, XK_NO_MOD, "\033[17;5~", 0, 0}, + { XK_F31, XK_NO_MOD, "\033[18;5~", 0, 0}, + { XK_F32, XK_NO_MOD, "\033[19;5~", 0, 0}, + { XK_F33, XK_NO_MOD, "\033[20;5~", 0, 0}, + { XK_F34, XK_NO_MOD, "\033[21;5~", 0, 0}, + { XK_F35, XK_NO_MOD, "\033[23;5~", 0, 0}, +}; + +/* + * Selection types' masks. + * Use the same masks as usual. + * Button1Mask is always unset, to make masks match between ButtonPress. + * ButtonRelease and MotionNotify. + * If no match is found, regular selection is used. + */ +static uint selmasks[] = { + [SEL_RECTANGULAR] = Mod1Mask, +}; + +/* + * Printable characters in ASCII, used to estimate the advance width + * of single wide characters. + */ +static char ascii_printable[] = + " !\"#$%&'()*+,-./0123456789:;<=>?" + "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" + "`abcdefghijklmnopqrstuvwxyz{|}~"; diff --git a/src/st/config.h b/src/st/config.h new file mode 100644 index 0000000..9189fdb --- /dev/null +++ b/src/st/config.h @@ -0,0 +1,522 @@ +/* See LICENSE file for copyright and license details. */ + +/* + * appearance + * + * font: see http://freedesktop.org/software/fontconfig/fontconfig-user.html + */ +static char *font = "Fira Code:pixelsize=15:style=Regular:antialias=true:autohint=true"; +static int borderpx = 2; + +/* + * What program is execed by st depends of these precedence rules: + * 1: program passed with -e + * 2: scroll and/or utmp + * 3: SHELL environment variable + * 4: value of shell in /etc/passwd + * 5: value of shell in config.h + */ +static char *shell = "/bin/sh"; +char *utmp = NULL; +/* scroll program: to enable use a string like "scroll" */ +char *scroll = NULL; +char *stty_args = "stty raw pass8 nl -echo -iexten -cstopb 38400"; + +/* identification sequence returned in DA and DECID */ +char *vtiden = "\033[?6c"; + +/* Kerning / character bounding-box multipliers */ +static float cwscale = 1.0; +static float chscale = 1.0; + +/* + * word delimiter string + * + * More advanced example: L" `'\"()[]{}" + */ +wchar_t *worddelimiters = L" "; + +/* selection timeouts (in milliseconds) */ +static unsigned int doubleclicktimeout = 1000; +static unsigned int tripleclicktimeout = 2000; + +/* alt screens */ +int allowaltscreen = 1; + +/* allow certain non-interactive (insecure) window operations such as: + setting the clipboard text */ +int allowwindowops = 0; + +/* + * draw latency range in ms - from new content/keypress/etc until drawing. + * within this range, st draws when content stops arriving (idle). mostly it's + * near minlatency, but it waits longer for slow updates to avoid partial draw. + * low minlatency will tear/flicker more, as it can "detect" idle too early. + */ +static double minlatency = 8; +static double maxlatency = 33; + +/* + * blinking timeout (set to 0 to disable blinking) for the terminal blinking + * attribute. + */ +static unsigned int blinktimeout = 800; + +/* + * thickness of underline and bar cursors + */ +static unsigned int cursorthickness = 2; + +/* + * bell volume. It must be a value between -100 and 100. Use 0 for disabling + * it + */ +static int bellvolume = 0; + +/* default TERM value */ +char *termname = "st-256color"; + +/* + * spaces per tab + * + * When you are changing this value, don't forget to adapt the »it« value in + * the st.info and appropriately install the st.info in the environment where + * you use this st version. + * + * it#$tabspaces, + * + * Secondly make sure your kernel is not expanding tabs. When running `stty + * -a` »tab0« should appear. You can tell the terminal to not expand tabs by + * running following command: + * + * stty tabs + */ +unsigned int tabspaces = 8; + +/* Terminal colors (16 first used in escape sequence) */ +static const char *colorname[] = { + /* 8 normal colors */ + "black", + "red3", + "green3", + "yellow3", + "blue2", + "magenta3", + "cyan3", + "gray90", + + /* 8 bright colors */ + "gray50", + "red", + "green", + "yellow", + "#5c5cff", + "magenta", + "cyan", + "white", + + [255] = 0, + + /* more colors can be added after 255 to use with DefaultXX */ + "#161616", + "#dddddd", + "#f4d03f", + "#555555", +}; + + +/* + * Default colors (colorname index) + * foreground, background, cursor, reverse cursor + */ +unsigned int defaultfg = 257; +unsigned int defaultbg = 256; +static unsigned int defaultcs = 258; +static unsigned int defaultrcs = 259; + +/* + * Default shape of cursor + * 2: Block ("█") + * 4: Underline ("_") + * 6: Bar ("|") + * 7: Snowman ("☃") + */ +static unsigned int cursorshape = 2; + +/* + * Default columns and rows numbers + */ + +static unsigned int cols = 80; +static unsigned int rows = 24; + +/* + * Default colour and shape of the mouse cursor + */ +static unsigned int mouseshape = XC_xterm; +static unsigned int mousefg = 7; +static unsigned int mousebg = 0; + +/* + * Color used to display font attributes when fontconfig selected a font which + * doesn't match the ones requested. + */ +static unsigned int defaultattr = 11; + +/* + * Force mouse select/shortcuts while mask is active (when MODE_MOUSE is set). + * Note that if you want to use ShiftMask with selmasks, set this to an other + * modifier, set to 0 to not use it. + */ +static uint forcemousemod = ShiftMask; + +/* + * Xresources preferences to load at startup + */ +ResourcePref resources[] = { + { "font", STRING, &font }, + { "color0", STRING, &colorname[0] }, + { "color1", STRING, &colorname[1] }, + { "color2", STRING, &colorname[2] }, + { "color3", STRING, &colorname[3] }, + { "color4", STRING, &colorname[4] }, + { "color5", STRING, &colorname[5] }, + { "color6", STRING, &colorname[6] }, + { "color7", STRING, &colorname[7] }, + { "color8", STRING, &colorname[8] }, + { "color9", STRING, &colorname[9] }, + { "color10", STRING, &colorname[10] }, + { "color11", STRING, &colorname[11] }, + { "color12", STRING, &colorname[12] }, + { "color13", STRING, &colorname[13] }, + { "color14", STRING, &colorname[14] }, + { "color15", STRING, &colorname[15] }, + { "background", STRING, &colorname[256] }, + { "foreground", STRING, &colorname[257] }, + { "cursorColor", STRING, &colorname[258] }, + { "termname", STRING, &termname }, + { "shell", STRING, &shell }, + { "blinktimeout", INTEGER, &blinktimeout }, + { "bellvolume", INTEGER, &bellvolume }, + { "tabspaces", INTEGER, &tabspaces }, + { "borderpx", INTEGER, &borderpx }, + { "cwscale", FLOAT, &cwscale }, + { "chscale", FLOAT, &chscale }, +}; + +/* + * Internal mouse shortcuts. + * Beware that overloading Button1 will disable the selection. + */ +static MouseShortcut mshortcuts[] = { + /* mask button function argument release */ + { XK_ANY_MOD, Button2, selpaste, {.i = 0}, 1 }, + { ShiftMask, Button4, kscrollup, {.i = 3} }, + { XK_ANY_MOD, Button4, wheelscrollup, {.i = 3} }, + { ShiftMask, Button5, kscrolldown, {.i = 3} }, + { XK_ANY_MOD, Button5, wheelscrolldown, {.i = 3} }, +}; + +/* Internal keyboard shortcuts. */ +#define MODKEY Mod1Mask +#define TERMMOD (ControlMask|ShiftMask) + +static Shortcut shortcuts[] = { + /* mask keysym function argument */ + { XK_ANY_MOD, XK_Break, sendbreak, {.i = 0} }, + { ControlMask, XK_Print, toggleprinter, {.i = 0} }, + { ShiftMask, XK_Print, printscreen, {.i = 0} }, + { XK_ANY_MOD, XK_Print, printsel, {.i = 0} }, + { TERMMOD, XK_Prior, zoom, {.f = +1} }, + { TERMMOD, XK_Next, zoom, {.f = -1} }, + { TERMMOD, XK_Home, zoomreset, {.f = 0} }, + { TERMMOD, XK_0, zoomreset, {.f = 0} }, + { TERMMOD, XK_parenright, zoomreset, {.f = 0} }, + { TERMMOD, XK_equal, zoom, {.f = +1} }, + { TERMMOD, XK_minus, zoom, {.f = -1} }, + { TERMMOD, XK_C, clipcopy, {.i = 0} }, + { TERMMOD, XK_V, clippaste, {.i = 0} }, + { TERMMOD, XK_Y, selpaste, {.i = 0} }, + { ShiftMask, XK_Insert, selpaste, {.i = 0} }, + { TERMMOD, XK_Num_Lock, numlock, {.i = 0} }, + + { TERMMOD, XK_S, toggleselectionmode, {.i = 0} }, + + { ShiftMask, XK_Prior, kscrollup, {.i = -1} }, + { ShiftMask, XK_Next, kscrolldown, {.i = -1} }, + { TERMMOD, XK_B, kscrollup, {.i = -1} }, + { TERMMOD, XK_F, kscrolldown, {.i = -1} }, + { TERMMOD, XK_X, invert, { } }, + { TERMMOD, XK_plus, zoom, {.f = +1} }, + { TERMMOD, XK_underscore, zoom, {.f = -1} }, +}; + +/* + * Special keys (change & recompile st.info accordingly) + * + * Mask value: + * * Use XK_ANY_MOD to match the key no matter modifiers state + * * Use XK_NO_MOD to match the key alone (no modifiers) + * appkey value: + * * 0: no value + * * > 0: keypad application mode enabled + * * = 2: term.numlock = 1 + * * < 0: keypad application mode disabled + * appcursor value: + * * 0: no value + * * > 0: cursor application mode enabled + * * < 0: cursor application mode disabled + * + * Be careful with the order of the definitions because st searches in + * this table sequentially, so any XK_ANY_MOD must be in the last + * position for a key. + */ + +/* + * If you want keys other than the X11 function keys (0xFD00 - 0xFFFF) + * to be mapped below, add them to this array. + */ +static KeySym mappedkeys[] = { -1 }; + +/* + * State bits to ignore when matching key or button events. By default, + * numlock (Mod2Mask), AltGr/Fn (Mod5Mask), and keyboard layout (XK_SWITCH_MOD) are ignored. + */ +static uint ignoremod = Mod2Mask|Mod5Mask|XK_SWITCH_MOD; + +/* + * This is the huge key array which defines all compatibility to the Linux + * world. Please decide about changes wisely. + */ +static Key key[] = { + /* keysym mask string appkey appcursor */ + { XK_KP_Home, ShiftMask, "\033[2J", 0, -1}, + { XK_KP_Home, ShiftMask, "\033[1;2H", 0, +1}, + { XK_KP_Home, XK_ANY_MOD, "\033[H", 0, -1}, + { XK_KP_Home, XK_ANY_MOD, "\033[1~", 0, +1}, + { XK_KP_Up, XK_ANY_MOD, "\033Ox", +1, 0}, + { XK_KP_Up, XK_ANY_MOD, "\033[A", 0, -1}, + { XK_KP_Up, XK_ANY_MOD, "\033OA", 0, +1}, + { XK_KP_Down, XK_ANY_MOD, "\033Or", +1, 0}, + { XK_KP_Down, XK_ANY_MOD, "\033[B", 0, -1}, + { XK_KP_Down, XK_ANY_MOD, "\033OB", 0, +1}, + { XK_KP_Left, XK_ANY_MOD, "\033Ot", +1, 0}, + { XK_KP_Left, XK_ANY_MOD, "\033[D", 0, -1}, + { XK_KP_Left, XK_ANY_MOD, "\033OD", 0, +1}, + { XK_KP_Right, XK_ANY_MOD, "\033Ov", +1, 0}, + { XK_KP_Right, XK_ANY_MOD, "\033[C", 0, -1}, + { XK_KP_Right, XK_ANY_MOD, "\033OC", 0, +1}, + { XK_KP_Prior, ShiftMask, "\033[5;2~", 0, 0}, + { XK_KP_Prior, XK_ANY_MOD, "\033[5~", 0, 0}, + { XK_KP_Begin, XK_ANY_MOD, "\033[E", 0, 0}, + { XK_KP_End, ControlMask, "\033[J", -1, 0}, + { XK_KP_End, ControlMask, "\033[1;5F", +1, 0}, + { XK_KP_End, ShiftMask, "\033[K", -1, 0}, + { XK_KP_End, ShiftMask, "\033[1;2F", +1, 0}, + { XK_KP_End, XK_ANY_MOD, "\033[4~", 0, 0}, + { XK_KP_Next, ShiftMask, "\033[6;2~", 0, 0}, + { XK_KP_Next, XK_ANY_MOD, "\033[6~", 0, 0}, + { XK_KP_Insert, ShiftMask, "\033[2;2~", +1, 0}, + { XK_KP_Insert, ShiftMask, "\033[4l", -1, 0}, + { XK_KP_Insert, ControlMask, "\033[L", -1, 0}, + { XK_KP_Insert, ControlMask, "\033[2;5~", +1, 0}, + { XK_KP_Insert, XK_ANY_MOD, "\033[4h", -1, 0}, + { XK_KP_Insert, XK_ANY_MOD, "\033[2~", +1, 0}, + { XK_KP_Delete, ControlMask, "\033[M", -1, 0}, + { XK_KP_Delete, ControlMask, "\033[3;5~", +1, 0}, + { XK_KP_Delete, ShiftMask, "\033[2K", -1, 0}, + { XK_KP_Delete, ShiftMask, "\033[3;2~", +1, 0}, + { XK_KP_Delete, XK_ANY_MOD, "\033[P", -1, 0}, + { XK_KP_Delete, XK_ANY_MOD, "\033[3~", +1, 0}, + { XK_KP_Multiply, XK_ANY_MOD, "\033Oj", +2, 0}, + { XK_KP_Add, XK_ANY_MOD, "\033Ok", +2, 0}, + { XK_KP_Enter, XK_ANY_MOD, "\033OM", +2, 0}, + { XK_KP_Enter, XK_ANY_MOD, "\r", -1, 0}, + { XK_KP_Subtract, XK_ANY_MOD, "\033Om", +2, 0}, + { XK_KP_Decimal, XK_ANY_MOD, "\033On", +2, 0}, + { XK_KP_Divide, XK_ANY_MOD, "\033Oo", +2, 0}, + { XK_KP_0, XK_ANY_MOD, "\033Op", +2, 0}, + { XK_KP_1, XK_ANY_MOD, "\033Oq", +2, 0}, + { XK_KP_2, XK_ANY_MOD, "\033Or", +2, 0}, + { XK_KP_3, XK_ANY_MOD, "\033Os", +2, 0}, + { XK_KP_4, XK_ANY_MOD, "\033Ot", +2, 0}, + { XK_KP_5, XK_ANY_MOD, "\033Ou", +2, 0}, + { XK_KP_6, XK_ANY_MOD, "\033Ov", +2, 0}, + { XK_KP_7, XK_ANY_MOD, "\033Ow", +2, 0}, + { XK_KP_8, XK_ANY_MOD, "\033Ox", +2, 0}, + { XK_KP_9, XK_ANY_MOD, "\033Oy", +2, 0}, + { XK_Up, ShiftMask, "\033[1;2A", 0, 0}, + { XK_Up, Mod1Mask, "\033[1;3A", 0, 0}, + { XK_Up, ShiftMask|Mod1Mask,"\033[1;4A", 0, 0}, + { XK_Up, ControlMask, "\033[1;5A", 0, 0}, + { XK_Up, ShiftMask|ControlMask,"\033[1;6A", 0, 0}, + { XK_Up, ControlMask|Mod1Mask,"\033[1;7A", 0, 0}, + { XK_Up,ShiftMask|ControlMask|Mod1Mask,"\033[1;8A", 0, 0}, + { XK_Up, XK_ANY_MOD, "\033[A", 0, -1}, + { XK_Up, XK_ANY_MOD, "\033OA", 0, +1}, + { XK_Down, ShiftMask, "\033[1;2B", 0, 0}, + { XK_Down, Mod1Mask, "\033[1;3B", 0, 0}, + { XK_Down, ShiftMask|Mod1Mask,"\033[1;4B", 0, 0}, + { XK_Down, ControlMask, "\033[1;5B", 0, 0}, + { XK_Down, ShiftMask|ControlMask,"\033[1;6B", 0, 0}, + { XK_Down, ControlMask|Mod1Mask,"\033[1;7B", 0, 0}, + { XK_Down,ShiftMask|ControlMask|Mod1Mask,"\033[1;8B",0, 0}, + { XK_Down, XK_ANY_MOD, "\033[B", 0, -1}, + { XK_Down, XK_ANY_MOD, "\033OB", 0, +1}, + { XK_Left, ShiftMask, "\033[1;2D", 0, 0}, + { XK_Left, Mod1Mask, "\033[1;3D", 0, 0}, + { XK_Left, ShiftMask|Mod1Mask,"\033[1;4D", 0, 0}, + { XK_Left, ControlMask, "\033[1;5D", 0, 0}, + { XK_Left, ShiftMask|ControlMask,"\033[1;6D", 0, 0}, + { XK_Left, ControlMask|Mod1Mask,"\033[1;7D", 0, 0}, + { XK_Left,ShiftMask|ControlMask|Mod1Mask,"\033[1;8D",0, 0}, + { XK_Left, XK_ANY_MOD, "\033[D", 0, -1}, + { XK_Left, XK_ANY_MOD, "\033OD", 0, +1}, + { XK_Right, ShiftMask, "\033[1;2C", 0, 0}, + { XK_Right, Mod1Mask, "\033[1;3C", 0, 0}, + { XK_Right, ShiftMask|Mod1Mask,"\033[1;4C", 0, 0}, + { XK_Right, ControlMask, "\033[1;5C", 0, 0}, + { XK_Right, ShiftMask|ControlMask,"\033[1;6C", 0, 0}, + { XK_Right, ControlMask|Mod1Mask,"\033[1;7C", 0, 0}, + { XK_Right,ShiftMask|ControlMask|Mod1Mask,"\033[1;8C",0, 0}, + { XK_Right, XK_ANY_MOD, "\033[C", 0, -1}, + { XK_Right, XK_ANY_MOD, "\033OC", 0, +1}, + { XK_ISO_Left_Tab, ShiftMask, "\033[Z", 0, 0}, + { XK_Return, Mod1Mask, "\033\r", 0, 0}, + { XK_Return, XK_ANY_MOD, "\r", 0, 0}, + { XK_Insert, ShiftMask, "\033[4l", -1, 0}, + { XK_Insert, ShiftMask, "\033[2;2~", +1, 0}, + { XK_Insert, ControlMask, "\033[L", -1, 0}, + { XK_Insert, ControlMask, "\033[2;5~", +1, 0}, + { XK_Insert, XK_ANY_MOD, "\033[4h", -1, 0}, + { XK_Insert, XK_ANY_MOD, "\033[2~", +1, 0}, + { XK_Delete, ControlMask, "\033[M", -1, 0}, + { XK_Delete, ControlMask, "\033[3;5~", +1, 0}, + { XK_Delete, ShiftMask, "\033[2K", -1, 0}, + { XK_Delete, ShiftMask, "\033[3;2~", +1, 0}, + { XK_Delete, XK_ANY_MOD, "\033[P", -1, 0}, + { XK_Delete, XK_ANY_MOD, "\033[3~", +1, 0}, + { XK_BackSpace, XK_NO_MOD, "\177", 0, 0}, + { XK_BackSpace, Mod1Mask, "\033\177", 0, 0}, + { XK_Home, ShiftMask, "\033[2J", 0, -1}, + { XK_Home, ShiftMask, "\033[1;2H", 0, +1}, + { XK_Home, XK_ANY_MOD, "\033[H", 0, -1}, + { XK_Home, XK_ANY_MOD, "\033[1~", 0, +1}, + { XK_End, ControlMask, "\033[J", -1, 0}, + { XK_End, ControlMask, "\033[1;5F", +1, 0}, + { XK_End, ShiftMask, "\033[K", -1, 0}, + { XK_End, ShiftMask, "\033[1;2F", +1, 0}, + { XK_End, XK_ANY_MOD, "\033[4~", 0, 0}, + { XK_Prior, ControlMask, "\033[5;5~", 0, 0}, + { XK_Prior, ShiftMask, "\033[5;2~", 0, 0}, + { XK_Prior, XK_ANY_MOD, "\033[5~", 0, 0}, + { XK_Next, ControlMask, "\033[6;5~", 0, 0}, + { XK_Next, ShiftMask, "\033[6;2~", 0, 0}, + { XK_Next, XK_ANY_MOD, "\033[6~", 0, 0}, + { XK_F1, XK_NO_MOD, "\033OP" , 0, 0}, + { XK_F1, /* F13 */ ShiftMask, "\033[1;2P", 0, 0}, + { XK_F1, /* F25 */ ControlMask, "\033[1;5P", 0, 0}, + { XK_F1, /* F37 */ Mod4Mask, "\033[1;6P", 0, 0}, + { XK_F1, /* F49 */ Mod1Mask, "\033[1;3P", 0, 0}, + { XK_F1, /* F61 */ Mod3Mask, "\033[1;4P", 0, 0}, + { XK_F2, XK_NO_MOD, "\033OQ" , 0, 0}, + { XK_F2, /* F14 */ ShiftMask, "\033[1;2Q", 0, 0}, + { XK_F2, /* F26 */ ControlMask, "\033[1;5Q", 0, 0}, + { XK_F2, /* F38 */ Mod4Mask, "\033[1;6Q", 0, 0}, + { XK_F2, /* F50 */ Mod1Mask, "\033[1;3Q", 0, 0}, + { XK_F2, /* F62 */ Mod3Mask, "\033[1;4Q", 0, 0}, + { XK_F3, XK_NO_MOD, "\033OR" , 0, 0}, + { XK_F3, /* F15 */ ShiftMask, "\033[1;2R", 0, 0}, + { XK_F3, /* F27 */ ControlMask, "\033[1;5R", 0, 0}, + { XK_F3, /* F39 */ Mod4Mask, "\033[1;6R", 0, 0}, + { XK_F3, /* F51 */ Mod1Mask, "\033[1;3R", 0, 0}, + { XK_F3, /* F63 */ Mod3Mask, "\033[1;4R", 0, 0}, + { XK_F4, XK_NO_MOD, "\033OS" , 0, 0}, + { XK_F4, /* F16 */ ShiftMask, "\033[1;2S", 0, 0}, + { XK_F4, /* F28 */ ControlMask, "\033[1;5S", 0, 0}, + { XK_F4, /* F40 */ Mod4Mask, "\033[1;6S", 0, 0}, + { XK_F4, /* F52 */ Mod1Mask, "\033[1;3S", 0, 0}, + { XK_F5, XK_NO_MOD, "\033[15~", 0, 0}, + { XK_F5, /* F17 */ ShiftMask, "\033[15;2~", 0, 0}, + { XK_F5, /* F29 */ ControlMask, "\033[15;5~", 0, 0}, + { XK_F5, /* F41 */ Mod4Mask, "\033[15;6~", 0, 0}, + { XK_F5, /* F53 */ Mod1Mask, "\033[15;3~", 0, 0}, + { XK_F6, XK_NO_MOD, "\033[17~", 0, 0}, + { XK_F6, /* F18 */ ShiftMask, "\033[17;2~", 0, 0}, + { XK_F6, /* F30 */ ControlMask, "\033[17;5~", 0, 0}, + { XK_F6, /* F42 */ Mod4Mask, "\033[17;6~", 0, 0}, + { XK_F6, /* F54 */ Mod1Mask, "\033[17;3~", 0, 0}, + { XK_F7, XK_NO_MOD, "\033[18~", 0, 0}, + { XK_F7, /* F19 */ ShiftMask, "\033[18;2~", 0, 0}, + { XK_F7, /* F31 */ ControlMask, "\033[18;5~", 0, 0}, + { XK_F7, /* F43 */ Mod4Mask, "\033[18;6~", 0, 0}, + { XK_F7, /* F55 */ Mod1Mask, "\033[18;3~", 0, 0}, + { XK_F8, XK_NO_MOD, "\033[19~", 0, 0}, + { XK_F8, /* F20 */ ShiftMask, "\033[19;2~", 0, 0}, + { XK_F8, /* F32 */ ControlMask, "\033[19;5~", 0, 0}, + { XK_F8, /* F44 */ Mod4Mask, "\033[19;6~", 0, 0}, + { XK_F8, /* F56 */ Mod1Mask, "\033[19;3~", 0, 0}, + { XK_F9, XK_NO_MOD, "\033[20~", 0, 0}, + { XK_F9, /* F21 */ ShiftMask, "\033[20;2~", 0, 0}, + { XK_F9, /* F33 */ ControlMask, "\033[20;5~", 0, 0}, + { XK_F9, /* F45 */ Mod4Mask, "\033[20;6~", 0, 0}, + { XK_F9, /* F57 */ Mod1Mask, "\033[20;3~", 0, 0}, + { XK_F10, XK_NO_MOD, "\033[21~", 0, 0}, + { XK_F10, /* F22 */ ShiftMask, "\033[21;2~", 0, 0}, + { XK_F10, /* F34 */ ControlMask, "\033[21;5~", 0, 0}, + { XK_F10, /* F46 */ Mod4Mask, "\033[21;6~", 0, 0}, + { XK_F10, /* F58 */ Mod1Mask, "\033[21;3~", 0, 0}, + { XK_F11, XK_NO_MOD, "\033[23~", 0, 0}, + { XK_F11, /* F23 */ ShiftMask, "\033[23;2~", 0, 0}, + { XK_F11, /* F35 */ ControlMask, "\033[23;5~", 0, 0}, + { XK_F11, /* F47 */ Mod4Mask, "\033[23;6~", 0, 0}, + { XK_F11, /* F59 */ Mod1Mask, "\033[23;3~", 0, 0}, + { XK_F12, XK_NO_MOD, "\033[24~", 0, 0}, + { XK_F12, /* F24 */ ShiftMask, "\033[24;2~", 0, 0}, + { XK_F12, /* F36 */ ControlMask, "\033[24;5~", 0, 0}, + { XK_F12, /* F48 */ Mod4Mask, "\033[24;6~", 0, 0}, + { XK_F12, /* F60 */ Mod1Mask, "\033[24;3~", 0, 0}, + { XK_F13, XK_NO_MOD, "\033[1;2P", 0, 0}, + { XK_F14, XK_NO_MOD, "\033[1;2Q", 0, 0}, + { XK_F15, XK_NO_MOD, "\033[1;2R", 0, 0}, + { XK_F16, XK_NO_MOD, "\033[1;2S", 0, 0}, + { XK_F17, XK_NO_MOD, "\033[15;2~", 0, 0}, + { XK_F18, XK_NO_MOD, "\033[17;2~", 0, 0}, + { XK_F19, XK_NO_MOD, "\033[18;2~", 0, 0}, + { XK_F20, XK_NO_MOD, "\033[19;2~", 0, 0}, + { XK_F21, XK_NO_MOD, "\033[20;2~", 0, 0}, + { XK_F22, XK_NO_MOD, "\033[21;2~", 0, 0}, + { XK_F23, XK_NO_MOD, "\033[23;2~", 0, 0}, + { XK_F24, XK_NO_MOD, "\033[24;2~", 0, 0}, + { XK_F25, XK_NO_MOD, "\033[1;5P", 0, 0}, + { XK_F26, XK_NO_MOD, "\033[1;5Q", 0, 0}, + { XK_F27, XK_NO_MOD, "\033[1;5R", 0, 0}, + { XK_F28, XK_NO_MOD, "\033[1;5S", 0, 0}, + { XK_F29, XK_NO_MOD, "\033[15;5~", 0, 0}, + { XK_F30, XK_NO_MOD, "\033[17;5~", 0, 0}, + { XK_F31, XK_NO_MOD, "\033[18;5~", 0, 0}, + { XK_F32, XK_NO_MOD, "\033[19;5~", 0, 0}, + { XK_F33, XK_NO_MOD, "\033[20;5~", 0, 0}, + { XK_F34, XK_NO_MOD, "\033[21;5~", 0, 0}, + { XK_F35, XK_NO_MOD, "\033[23;5~", 0, 0}, +}; + +/* + * Selection types' masks. + * Use the same masks as usual. + * Button1Mask is always unset, to make masks match between ButtonPress. + * ButtonRelease and MotionNotify. + * If no match is found, regular selection is used. + */ +static uint selmasks[] = { + [SEL_RECTANGULAR] = Mod1Mask, +}; + +/* + * Printable characters in ASCII, used to estimate the advance width + * of single wide characters. + */ +static char ascii_printable[] = + " !\"#$%&'()*+,-./0123456789:;<=>?" + "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_" + "`abcdefghijklmnopqrstuvwxyz{|}~"; diff --git a/src/st/hb.c b/src/st/hb.c new file mode 100644 index 0000000..445ccda --- /dev/null +++ b/src/st/hb.c @@ -0,0 +1,140 @@ +#include +#include +#include +#include +#include +#include + +#include "st.h" +#include "hb.h" + +#define FEATURE(c1,c2,c3,c4) { .tag = HB_TAG(c1,c2,c3,c4), .value = 1, .start = HB_FEATURE_GLOBAL_START, .end = HB_FEATURE_GLOBAL_END } + +typedef struct { + XftFont *match; + hb_font_t *font; +} HbFontMatch; + +static int hbfontslen = 0; +static HbFontMatch *hbfontcache = NULL; +static hb_buffer_t *hbbuffer = NULL; + +static hb_feature_t features[] = { + FEATURE('l','i','g','a'), + FEATURE('c','a','l','t'), + FEATURE('c','l','i','g'), + FEATURE('d','l','i','g'), +}; + +void +hbunloadfonts(void) +{ + for (int i = 0; i < hbfontslen; i++) { + hb_font_destroy(hbfontcache[i].font); + XftUnlockFace(hbfontcache[i].match); + } + if (hbfontcache != NULL) { + free(hbfontcache); + hbfontcache = NULL; + } + hbfontslen = 0; +} + +static hb_font_t * +hbfindfont(XftFont *match) +{ + for (int i = 0; i < hbfontslen; i++) { + if (hbfontcache[i].match == match) + return hbfontcache[i].font; + } + + hbfontcache = xrealloc(hbfontcache, sizeof(HbFontMatch) * (hbfontslen + 1)); + FT_Face face = XftLockFace(match); + hb_font_t *font = hb_ft_font_create(face, NULL); + if (font == NULL) + die("Failed to load HarfBuzz font."); + + hbfontcache[hbfontslen].match = match; + hbfontcache[hbfontslen].font = font; + hbfontslen += 1; + + return font; +} + +static void +hbtransformsegment(XftFont *xfont, const Glyph *string, hb_codepoint_t *codepoints, int start, int length) +{ + hb_font_t *font = hbfindfont(xfont); + if (font == NULL) + return; + + if (hbbuffer == NULL) + hbbuffer = hb_buffer_create(); + hb_buffer_reset(hbbuffer); + hb_buffer_set_direction(hbbuffer, HB_DIRECTION_LTR); + hb_buffer_set_script(hbbuffer, HB_SCRIPT_LATIN); + + for (int i = start; i < (start + length); i++) { + Rune rune = string[i].u; + if (string[i].mode & ATTR_WDUMMY) + rune = 0x0020; + hb_buffer_add_codepoints(hbbuffer, &rune, 1, 0, 1); + } + + hb_shape(font, hbbuffer, features, sizeof(features) / sizeof(hb_feature_t)); + + unsigned int glyph_count = 0; + hb_glyph_info_t *info = hb_buffer_get_glyph_infos(hbbuffer, &glyph_count); + + if ((int)glyph_count == length) { + for (int i = 0; i < length; i++) + codepoints[start + i] = info[i].codepoint; + } else if (glyph_count > 0 && (int)glyph_count < length) { + for (int i = 0; i < length; i++) + codepoints[start + i] = 0; + for (unsigned int g = 0; g < glyph_count; g++) { + uint32_t c = info[g].cluster; + if ((int)c < length) + codepoints[start + c] = info[g].codepoint; + } + } +} + +void +hbtransform(XftGlyphFontSpec *specs, const Glyph *glyphs, size_t len, int x, int y) +{ + int start = 0, length = 1, gstart = 0; + hb_codepoint_t *codepoints = calloc(len, sizeof(hb_codepoint_t)); + if (!codepoints) + return; + + for (int idx = 1, specidx = 1; idx < (int)len; idx++) { + if (glyphs[idx].mode & ATTR_WDUMMY) { + length += 1; + continue; + } + + if (specs[specidx].font != specs[start].font || ATTRCMP(glyphs[gstart], glyphs[idx])) { + hbtransformsegment(specs[start].font, glyphs, codepoints, gstart, length); + length = 1; + start = specidx; + gstart = idx; + } else { + length += 1; + } + + specidx++; + } + + hbtransformsegment(specs[start].font, glyphs, codepoints, gstart, length); + + for (int i = 0, specidx = 0; i < (int)len; i++) { + if (glyphs[i].mode & ATTR_WDUMMY) + continue; + if (codepoints[i] != 0 && codepoints[i] != specs[specidx].glyph) + specs[specidx].glyph = codepoints[i]; + specidx++; + } + + free(codepoints); +} diff --git a/src/st/hb.h b/src/st/hb.h new file mode 100644 index 0000000..2c1d33f --- /dev/null +++ b/src/st/hb.h @@ -0,0 +1,6 @@ +#include +#include +#include + +void hbunloadfonts(void); +void hbtransform(XftGlyphFontSpec *, const Glyph *, size_t, int, int); diff --git a/src/st/st.1 b/src/st/st.1 new file mode 100644 index 0000000..39120b4 --- /dev/null +++ b/src/st/st.1 @@ -0,0 +1,177 @@ +.TH ST 1 st\-VERSION +.SH NAME +st \- simple terminal +.SH SYNOPSIS +.B st +.RB [ \-aiv ] +.RB [ \-c +.IR class ] +.RB [ \-f +.IR font ] +.RB [ \-g +.IR geometry ] +.RB [ \-n +.IR name ] +.RB [ \-o +.IR iofile ] +.RB [ \-T +.IR title ] +.RB [ \-t +.IR title ] +.RB [ \-l +.IR line ] +.RB [ \-w +.IR windowid ] +.RB [[ \-e ] +.IR command +.RI [ arguments ...]] +.PP +.B st +.RB [ \-aiv ] +.RB [ \-c +.IR class ] +.RB [ \-f +.IR font ] +.RB [ \-g +.IR geometry ] +.RB [ \-n +.IR name ] +.RB [ \-o +.IR iofile ] +.RB [ \-T +.IR title ] +.RB [ \-t +.IR title ] +.RB [ \-w +.IR windowid ] +.RB \-l +.IR line +.RI [ stty_args ...] +.SH DESCRIPTION +.B st +is a simple terminal emulator. +.SH OPTIONS +.TP +.B \-a +disable alternate screens in terminal +.TP +.BI \-c " class" +defines the window class (default $TERM). +.TP +.BI \-f " font" +defines the +.I font +to use when st is run. +.TP +.BI \-g " geometry" +defines the X11 geometry string. +The form is [=][{xX}][{+-}{+-}]. See +.BR XParseGeometry (3) +for further details. +.TP +.B \-i +will fixate the position given with the -g option. +.TP +.BI \-n " name" +defines the window instance name (default $TERM). +.TP +.BI \-o " iofile" +writes all the I/O to +.I iofile. +This feature is useful when recording st sessions. A value of "-" means +standard output. +.TP +.BI \-T " title" +defines the window title (default 'st'). +.TP +.BI \-t " title" +defines the window title (default 'st'). +.TP +.BI \-w " windowid" +embeds st within the window identified by +.I windowid +.TP +.BI \-l " line" +use a tty +.I line +instead of a pseudo terminal. +.I line +should be a (pseudo-)serial device (e.g. /dev/ttyS0 on Linux for serial port +0). +When this flag is given +remaining arguments are used as flags for +.BR stty(1). +By default st initializes the serial line to 8 bits, no parity, 1 stop bit +and a 38400 baud rate. The speed is set by appending it as last argument +(e.g. 'st -l /dev/ttyS0 115200'). Arguments before the last one are +.BR stty(1) +flags. If you want to set odd parity on 115200 baud use for example 'st -l +/dev/ttyS0 parenb parodd 115200'. Set the number of bits by using for +example 'st -l /dev/ttyS0 cs7 115200'. See +.BR stty(1) +for more arguments and cases. +.TP +.B \-v +prints version information to stderr, then exits. +.TP +.BI \-e " command " [ " arguments " "... ]" +st executes +.I command +instead of the shell. If this is used it +.B must be the last option +on the command line, as in xterm / rxvt. +This option is only intended for compatibility, +and all the remaining arguments are used as a command +even without it. +.SH SHORTCUTS +.TP +.B Break +Send a break in the serial line. +Break key is obtained in PC keyboards +pressing at the same time control and pause. +.TP +.B Ctrl-Print Screen +Toggle if st should print to the +.I iofile. +.TP +.B Shift-Print Screen +Print the full screen to the +.I iofile. +.TP +.B Print Screen +Print the selection to the +.I iofile. +.TP +.B Ctrl-Shift-Page Up +Increase font size. +.TP +.B Ctrl-Shift-Page Down +Decrease font size. +.TP +.B Ctrl-Shift-Home +Reset to default font size. +.TP +.B Ctrl-Shift-y +Paste from primary selection (middle mouse button). +.TP +.B Ctrl-Shift-c +Copy the selected text to the clipboard selection. +.TP +.B Ctrl-Shift-v +Paste from the clipboard selection. +.SH CUSTOMIZATION +.B st +can be customized by creating a custom config.h and (re)compiling the source +code. This keeps it fast, secure and simple. +.SH AUTHORS +See the LICENSE file for the authors. +.SH LICENSE +See the LICENSE file for the terms of redistribution. +.SH SEE ALSO +.BR tabbed (1), +.BR utmp (1), +.BR stty (1), +.BR scroll (1) +.SH BUGS +See the TODO file in the distribution. + diff --git a/src/st/st.c b/src/st/st.c new file mode 100644 index 0000000..afaa521 --- /dev/null +++ b/src/st/st.c @@ -0,0 +1,2738 @@ +/* See LICENSE for license details. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "st.h" +#include "win.h" + +#if defined(__linux) || defined(__linux__) + #include +#elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) + #include +#elif defined(__FreeBSD__) || defined(__DragonFly__) + #include +#endif + +/* Arbitrary sizes */ +#define UTF_INVALID 0xFFFD +#define UTF_SIZ 4 +#define ESC_BUF_SIZ (128*UTF_SIZ) +#define ESC_ARG_SIZ 16 +#define STR_BUF_SIZ ESC_BUF_SIZ +#define STR_ARG_SIZ ESC_ARG_SIZ +#define HISTSIZE 2000 + +/* macros */ +#define IS_SET(flag) ((term.mode & (flag)) != 0) +#define ISCONTROLC0(c) (BETWEEN(c, 0, 0x1f) || (c) == 0x7f) +#define ISCONTROLC1(c) (BETWEEN(c, 0x80, 0x9f)) +#define ISCONTROL(c) (ISCONTROLC0(c) || ISCONTROLC1(c)) +#define ISDELIM(u) (u && wcschr(worddelimiters, u)) +#define TLINE(y) ((y) < term.scr ? term.hist[((y) + term.histi - \ + term.scr + HISTSIZE + 1) % HISTSIZE] : \ + term.line[(y) - term.scr]) + +enum term_mode { + MODE_WRAP = 1 << 0, + MODE_INSERT = 1 << 1, + MODE_ALTSCREEN = 1 << 2, + MODE_CRLF = 1 << 3, + MODE_ECHO = 1 << 4, + MODE_PRINT = 1 << 5, + MODE_UTF8 = 1 << 6, +}; + +enum cursor_movement { + CURSOR_SAVE, + CURSOR_LOAD +}; + +enum cursor_state { + CURSOR_DEFAULT = 0, + CURSOR_WRAPNEXT = 1, + CURSOR_ORIGIN = 2 +}; + +enum charset { + CS_GRAPHIC0, + CS_GRAPHIC1, + CS_UK, + CS_USA, + CS_MULTI, + CS_GER, + CS_FIN +}; + +enum escape_state { + ESC_START = 1, + ESC_CSI = 2, + ESC_STR = 4, /* DCS, OSC, PM, APC */ + ESC_ALTCHARSET = 8, + ESC_STR_END = 16, /* a final string was encountered */ + ESC_TEST = 32, /* Enter in test mode */ + ESC_UTF8 = 64, +}; + +typedef struct { + Glyph attr; /* current char attributes */ + int x; + int y; + char state; +} TCursor; + +typedef struct { + int mode; + int type; + int snap; + /* + * Selection variables: + * nb – normalized coordinates of the beginning of the selection + * ne – normalized coordinates of the end of the selection + * ob – original coordinates of the beginning of the selection + * oe – original coordinates of the end of the selection + */ + struct { + int x, y; + } nb, ne, ob, oe; + + int alt; +} Selection; + +/* Internal representation of the screen */ +typedef struct { + int row; /* nb row */ + int col; /* nb col */ + Line *line; /* screen */ + Line *alt; /* alternate screen */ + Line hist[HISTSIZE]; /* history buffer */ + int histi; /* history index */ + int scr; /* scroll back */ + int *dirty; /* dirtyness of lines */ + TCursor c; /* cursor */ + int ocx; /* old cursor col */ + int ocy; /* old cursor row */ + int top; /* top scroll limit */ + int bot; /* bottom scroll limit */ + int mode; /* terminal mode flags */ + int esc; /* escape state flags */ + char trantbl[4]; /* charset table translation */ + int charset; /* current charset */ + int icharset; /* selected charset for sequence */ + int *tabs; + Rune lastc; /* last printed char outside of sequence, 0 if control */ +} Term; + +/* CSI Escape sequence structs */ +/* ESC '[' [[ [] [;]] []] */ +typedef struct { + char buf[ESC_BUF_SIZ]; /* raw string */ + size_t len; /* raw string length */ + char priv; + int arg[ESC_ARG_SIZ]; + int narg; /* nb of args */ + char mode[2]; +} CSIEscape; + +/* STR Escape sequence structs */ +/* ESC type [[ [] [;]] ] ESC '\' */ +typedef struct { + char type; /* ESC type ... */ + char *buf; /* allocated raw string */ + size_t siz; /* allocation size */ + size_t len; /* raw string length */ + char *args[STR_ARG_SIZ]; + int narg; /* nb of args */ +} STREscape; + +static void execsh(char *, char **); +static void stty(char **); +static void sigchld(int); +static void ttywriteraw(const char *, size_t); + +static void csidump(void); +static void csihandle(void); +static void csiparse(void); +static void csireset(void); +static int eschandle(uchar); +static void strdump(void); +static void strhandle(void); +static void strparse(void); +static void strreset(void); + +static void tprinter(char *, size_t); +static void tdumpsel(void); +static void tdumpline(int); +static void tdump(void); +static void tclearregion(int, int, int, int); +static void tcursor(int); +static void tdeletechar(int); +static void tdeleteline(int); +static void tinsertblank(int); +static void tinsertblankline(int); +static int tlinelen(int); +static void tmoveto(int, int); +static void tmoveato(int, int); +static void tnewline(int); +static void tputtab(int); +static void tputc(Rune); +static void treset(void); +static void tscrollup(int, int, int); +static void tscrolldown(int, int, int); +static void tsetattr(int *, int); +static void tsetchar(Rune, Glyph *, int, int); +static void tsetdirt(int, int); +static void tsetscroll(int, int); +static void tswapscreen(void); +static void tsetmode(int, int, int *, int); +static int twrite(const char *, int, int); +static void tfulldirt(void); +static void tcontrolcode(uchar ); +static void tdectest(char ); +static void tdefutf8(char); +static int32_t tdefcolor(int *, int *, int); +static void tdeftran(char); +static void tstrsequence(uchar); + +static void drawregion(int, int, int, int); + +static void selnormalize(void); +static void selscroll(int, int); +static void selsnap(int *, int *, int); + +static size_t utf8decode(const char *, Rune *, size_t); +static Rune utf8decodebyte(char, size_t *); +static char utf8encodebyte(Rune, size_t); +static size_t utf8validate(Rune *, size_t); + +static char *base64dec(const char *); +static char base64dec_getc(const char **); + +static ssize_t xwrite(int, const char *, size_t); + +/* Globals */ +static Term term; +static Selection sel; +static CSIEscape csiescseq; +static STREscape strescseq; +static int iofd = 1; +static int cmdfd; +static pid_t pid; + +static uchar utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0}; +static uchar utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8}; +static Rune utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000}; +static Rune utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF}; + +ssize_t +xwrite(int fd, const char *s, size_t len) +{ + size_t aux = len; + ssize_t r; + + while (len > 0) { + r = write(fd, s, len); + if (r < 0) + return r; + len -= r; + s += r; + } + + return aux; +} + +void * +xmalloc(size_t len) +{ + void *p; + + if (!(p = malloc(len))) + die("malloc: %s\n", strerror(errno)); + + return p; +} + +void * +xrealloc(void *p, size_t len) +{ + if ((p = realloc(p, len)) == NULL) + die("realloc: %s\n", strerror(errno)); + + return p; +} + +char * +xstrdup(char *s) +{ + if ((s = strdup(s)) == NULL) + die("strdup: %s\n", strerror(errno)); + + return s; +} + +size_t +utf8decode(const char *c, Rune *u, size_t clen) +{ + size_t i, j, len, type; + Rune udecoded; + + *u = UTF_INVALID; + if (!clen) + return 0; + udecoded = utf8decodebyte(c[0], &len); + if (!BETWEEN(len, 1, UTF_SIZ)) + return 1; + for (i = 1, j = 1; i < clen && j < len; ++i, ++j) { + udecoded = (udecoded << 6) | utf8decodebyte(c[i], &type); + if (type != 0) + return j; + } + if (j < len) + return 0; + *u = udecoded; + utf8validate(u, len); + + return len; +} + +Rune +utf8decodebyte(char c, size_t *i) +{ + for (*i = 0; *i < LEN(utfmask); ++(*i)) + if (((uchar)c & utfmask[*i]) == utfbyte[*i]) + return (uchar)c & ~utfmask[*i]; + + return 0; +} + +size_t +utf8encode(Rune u, char *c) +{ + size_t len, i; + + len = utf8validate(&u, 0); + if (len > UTF_SIZ) + return 0; + + for (i = len - 1; i != 0; --i) { + c[i] = utf8encodebyte(u, 0); + u >>= 6; + } + c[0] = utf8encodebyte(u, len); + + return len; +} + +char +utf8encodebyte(Rune u, size_t i) +{ + return utfbyte[i] | (u & ~utfmask[i]); +} + +size_t +utf8validate(Rune *u, size_t i) +{ + if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF)) + *u = UTF_INVALID; + for (i = 1; *u > utfmax[i]; ++i) + ; + + return i; +} + +static const char base64_digits[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, + 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, -1, 0, 0, 0, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, + 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; + +char +base64dec_getc(const char **src) +{ + while (**src && !isprint(**src)) + (*src)++; + return **src ? *((*src)++) : '='; /* emulate padding if string ends */ +} + +char * +base64dec(const char *src) +{ + size_t in_len = strlen(src); + char *result, *dst; + + if (in_len % 4) + in_len += 4 - (in_len % 4); + result = dst = xmalloc(in_len / 4 * 3 + 1); + while (*src) { + int a = base64_digits[(unsigned char) base64dec_getc(&src)]; + int b = base64_digits[(unsigned char) base64dec_getc(&src)]; + int c = base64_digits[(unsigned char) base64dec_getc(&src)]; + int d = base64_digits[(unsigned char) base64dec_getc(&src)]; + + /* invalid input. 'a' can be -1, e.g. if src is "\n" (c-str) */ + if (a == -1 || b == -1) + break; + + *dst++ = (a << 2) | ((b & 0x30) >> 4); + if (c == -1) + break; + *dst++ = ((b & 0x0f) << 4) | ((c & 0x3c) >> 2); + if (d == -1) + break; + *dst++ = ((c & 0x03) << 6) | d; + } + *dst = '\0'; + return result; +} + +void +selinit(void) +{ + sel.mode = SEL_IDLE; + sel.snap = 0; + sel.ob.x = -1; +} + +int +tlinelen(int y) +{ + int i = term.col; + + if (TLINE(y)[i - 1].mode & ATTR_WRAP) + return i; + + while (i > 0 && TLINE(y)[i - 1].u == ' ') + --i; + + return i; +} + +void +selstart(int col, int row, int snap) +{ + selclear(); + sel.mode = SEL_EMPTY; + sel.type = SEL_REGULAR; + sel.alt = IS_SET(MODE_ALTSCREEN); + sel.snap = snap; + sel.oe.x = sel.ob.x = col; + sel.oe.y = sel.ob.y = row; + selnormalize(); + + if (sel.snap != 0) + sel.mode = SEL_READY; + //tsetdirt(sel.nb.y, sel.ne.y); +} + +void +selextend(int col, int row, int type, int done) +{ + int oldey, oldex, oldsby, oldsey, oldtype; + + if (sel.mode == SEL_IDLE) + return; + if (done && sel.mode == SEL_EMPTY) { + selclear(); + return; + } + + oldey = sel.oe.y; + oldex = sel.oe.x; + oldsby = sel.nb.y; + oldsey = sel.ne.y; + oldtype = sel.type; + + sel.oe.x = col; + sel.oe.y = row; + selnormalize(); + sel.type = type; + + if (oldey != sel.oe.y || oldex != sel.oe.x || oldtype != sel.type || sel.mode == SEL_EMPTY) + tsetdirt(MIN(sel.nb.y, oldsby), MAX(sel.ne.y, oldsey)); + + sel.mode = done ? SEL_IDLE : SEL_READY; +} + +void +selnormalize(void) +{ + int i; + + if (sel.type == SEL_REGULAR && sel.ob.y != sel.oe.y) { + sel.nb.x = sel.ob.y < sel.oe.y ? sel.ob.x : sel.oe.x; + sel.ne.x = sel.ob.y < sel.oe.y ? sel.oe.x : sel.ob.x; + } else { + sel.nb.x = MIN(sel.ob.x, sel.oe.x); + sel.ne.x = MAX(sel.ob.x, sel.oe.x); + } + sel.nb.y = MIN(sel.ob.y, sel.oe.y); + sel.ne.y = MAX(sel.ob.y, sel.oe.y); + + // E.g. cancels out all selsnapping functionality since this + // the pinephone's touchscreen likes to send extra mouseup events + // causing everything to selsnap..? + // This is a temp workaround - selsnapping would be nice eventually.. + return; + + selsnap(&sel.nb.x, &sel.nb.y, -1); + selsnap(&sel.ne.x, &sel.ne.y, +1); + + /* expand selection over line breaks */ + if (sel.type == SEL_RECTANGULAR) + return; + i = tlinelen(sel.nb.y); + if (i < sel.nb.x) + sel.nb.x = i; + if (tlinelen(sel.ne.y) <= sel.ne.x) + sel.ne.x = term.col - 1; +} + +int +selected(int x, int y) +{ + if (sel.mode == SEL_EMPTY || sel.ob.x == -1 || + sel.alt != IS_SET(MODE_ALTSCREEN)) + return 0; + + if (sel.type == SEL_RECTANGULAR) + return BETWEEN(y, sel.nb.y, sel.ne.y) + && BETWEEN(x, sel.nb.x, sel.ne.x); + + return BETWEEN(y, sel.nb.y, sel.ne.y) + && (y != sel.nb.y || x >= sel.nb.x) + && (y != sel.ne.y || x <= sel.ne.x); +} + +void +selsnap(int *x, int *y, int direction) +{ + int newx, newy, xt, yt; + int delim, prevdelim; + Glyph *gp, *prevgp; + + switch (sel.snap) { + case SNAP_WORD: + /* + * Snap around if the word wraps around at the end or + * beginning of a line. + */ + prevgp = &TLINE(*y)[*x]; + prevdelim = ISDELIM(prevgp->u); + for (;;) { + newx = *x + direction; + newy = *y; + if (!BETWEEN(newx, 0, term.col - 1)) { + newy += direction; + newx = (newx + term.col) % term.col; + if (!BETWEEN(newy, 0, term.row - 1)) + break; + + if (direction > 0) + yt = *y, xt = *x; + else + yt = newy, xt = newx; + if (!(TLINE(yt)[xt].mode & ATTR_WRAP)) + break; + } + + if (newx >= tlinelen(newy)) + break; + + gp = &TLINE(newy)[newx]; + delim = ISDELIM(gp->u); + if (!(gp->mode & ATTR_WDUMMY) && (delim != prevdelim + || (delim && gp->u != prevgp->u))) + break; + + *x = newx; + *y = newy; + prevgp = gp; + prevdelim = delim; + } + break; + case SNAP_LINE: + /* + * Snap around if the the previous line or the current one + * has set ATTR_WRAP at its end. Then the whole next or + * previous line will be selected. + */ + *x = (direction < 0) ? 0 : term.col - 1; + if (direction < 0) { + for (; *y > 0; *y += direction) { + if (!(TLINE(*y-1)[term.col-1].mode + & ATTR_WRAP)) { + break; + } + } + } else if (direction > 0) { + for (; *y < term.row-1; *y += direction) { + if (!(TLINE(*y)[term.col-1].mode + & ATTR_WRAP)) { + break; + } + } + } + break; + } +} + +char * +getsel(void) +{ + char *str, *ptr; + int y, bufsize, lastx, linelen; + Glyph *gp, *last; + + if (sel.ob.x == -1) + return NULL; + + bufsize = (term.col+1) * (sel.ne.y-sel.nb.y+1) * UTF_SIZ; + ptr = str = xmalloc(bufsize); + + /* append every set & selected glyph to the selection */ + for (y = sel.nb.y; y <= sel.ne.y; y++) { + if ((linelen = tlinelen(y)) == 0) { + *ptr++ = '\n'; + continue; + } + + if (sel.type == SEL_RECTANGULAR) { + gp = &TLINE(y)[sel.nb.x]; + lastx = sel.ne.x; + } else { + gp = &TLINE(y)[sel.nb.y == y ? sel.nb.x : 0]; + lastx = (sel.ne.y == y) ? sel.ne.x : term.col-1; + } + last = &TLINE(y)[MIN(lastx, linelen-1)]; + while (last >= gp && last->u == ' ') + --last; + + for ( ; gp <= last; ++gp) { + if (gp->mode & ATTR_WDUMMY) + continue; + + ptr += utf8encode(gp->u, ptr); + } + + /* + * Copy and pasting of line endings is inconsistent + * in the inconsistent terminal and GUI world. + * The best solution seems like to produce '\n' when + * something is copied from st and convert '\n' to + * '\r', when something to be pasted is received by + * st. + * FIXME: Fix the computer world. + */ + if ((y < sel.ne.y || lastx >= linelen) && + (!(last->mode & ATTR_WRAP) || sel.type == SEL_RECTANGULAR)) + *ptr++ = '\n'; + } + *ptr = 0; + return str; +} + +void +selclear(void) +{ + if (sel.ob.x == -1) + return; + sel.mode = SEL_IDLE; + sel.ob.x = -1; + tsetdirt(sel.nb.y, sel.ne.y); +} + +void +die(const char *errstr, ...) +{ + va_list ap; + + va_start(ap, errstr); + vfprintf(stderr, errstr, ap); + va_end(ap); + exit(1); +} + +void +execsh(char *cmd, char **args) +{ + char *sh, *prog, *arg; + const struct passwd *pw; + + errno = 0; + if ((pw = getpwuid(getuid())) == NULL) { + if (errno) + die("getpwuid: %s\n", strerror(errno)); + else + die("who are you?\n"); + } + + if ((sh = getenv("SHELL")) == NULL) + sh = (pw->pw_shell[0]) ? pw->pw_shell : cmd; + + if (args) { + prog = args[0]; + arg = NULL; + } else if (scroll) { + prog = scroll; + arg = utmp ? utmp : sh; + } else if (utmp) { + prog = utmp; + arg = NULL; + } else { + prog = sh; + arg = NULL; + } + DEFAULT(args, ((char *[]) {prog, arg, NULL})); + + unsetenv("COLUMNS"); + unsetenv("LINES"); + unsetenv("TERMCAP"); + setenv("LOGNAME", pw->pw_name, 1); + setenv("USER", pw->pw_name, 1); + setenv("SHELL", sh, 1); + setenv("HOME", pw->pw_dir, 1); + setenv("TERM", termname, 1); + if (!getenv("LANG") && !getenv("LC_ALL") && !getenv("LC_CTYPE")) + setenv("LANG", "C.UTF-8", 0); + setenv("PAGER", "less -RXF", 0); + setenv("LESS", "-RXF", 0); + + signal(SIGCHLD, SIG_DFL); + signal(SIGHUP, SIG_DFL); + signal(SIGINT, SIG_DFL); + signal(SIGQUIT, SIG_DFL); + signal(SIGTERM, SIG_DFL); + signal(SIGALRM, SIG_DFL); + + execvp(prog, args); + _exit(1); +} + +void +sigchld(int a) +{ + int stat; + pid_t p; + + if ((p = waitpid(pid, &stat, WNOHANG)) < 0) + die("waiting for pid %hd failed: %s\n", pid, strerror(errno)); + + if (pid != p) + return; + + if (WIFEXITED(stat) && WEXITSTATUS(stat)) + die("child exited with status %d\n", WEXITSTATUS(stat)); + else if (WIFSIGNALED(stat)) + die("child terminated due to signal %d\n", WTERMSIG(stat)); + _exit(0); +} + +void +stty(char **args) +{ + char cmd[_POSIX_ARG_MAX], **p, *q, *s; + size_t n, siz; + + if ((n = strlen(stty_args)) > sizeof(cmd)-1) + die("incorrect stty parameters\n"); + memcpy(cmd, stty_args, n); + q = cmd + n; + siz = sizeof(cmd) - n; + for (p = args; p && (s = *p); ++p) { + if ((n = strlen(s)) > siz-1) + die("stty parameter length too long\n"); + *q++ = ' '; + memcpy(q, s, n); + q += n; + siz -= n + 1; + } + *q = '\0'; + if (system(cmd) != 0) + perror("Couldn't call stty"); +} + +int +ttynew(char *line, char *cmd, char *out, char **args) +{ + int m, s; + + if (out) { + term.mode |= MODE_PRINT; + iofd = (!strcmp(out, "-")) ? + 1 : open(out, O_WRONLY | O_CREAT, 0666); + if (iofd < 0) { + fprintf(stderr, "Error opening %s:%s\n", + out, strerror(errno)); + } + } + + if (line) { + if ((cmdfd = open(line, O_RDWR)) < 0) + die("open line '%s' failed: %s\n", + line, strerror(errno)); + dup2(cmdfd, 0); + stty(args); + return cmdfd; + } + + /* seems to work fine on linux, openbsd and freebsd */ + if (openpty(&m, &s, NULL, NULL, NULL) < 0) + die("openpty failed: %s\n", strerror(errno)); + + switch (pid = fork()) { + case -1: + die("fork failed: %s\n", strerror(errno)); + break; + case 0: + close(iofd); + setsid(); /* create a new process group */ + dup2(s, 0); + dup2(s, 1); + dup2(s, 2); + if (ioctl(s, TIOCSCTTY, NULL) < 0) + die("ioctl TIOCSCTTY failed: %s\n", strerror(errno)); + close(s); + close(m); +#ifdef __OpenBSD__ + if (pledge("stdio getpw proc exec", NULL) == -1) + die("pledge\n"); +#endif + execsh(cmd, args); + break; + default: +#ifdef __OpenBSD__ + if (pledge("stdio rpath tty proc", NULL) == -1) + die("pledge\n"); +#endif + close(s); + cmdfd = m; + signal(SIGCHLD, sigchld); + break; + } + return cmdfd; +} + +size_t +ttyread(void) +{ + static char buf[BUFSIZ]; + static int buflen = 0; + int ret, written; + + /* append read bytes to unprocessed bytes */ + ret = read(cmdfd, buf+buflen, LEN(buf)-buflen); + + switch (ret) { + case 0: + exit(0); + case -1: + die("couldn't read from shell: %s\n", strerror(errno)); + default: + buflen += ret; + written = twrite(buf, buflen, 0); + buflen -= written; + /* keep any incomplete UTF-8 byte sequence for the next call */ + if (buflen > 0) + memmove(buf, buf + written, buflen); + return ret; + } +} + +void +ttywrite(const char *s, size_t n, int may_echo) +{ + const char *next; + Arg arg = (Arg) { .i = term.scr }; + + kscrolldown(&arg); + + if (may_echo && IS_SET(MODE_ECHO)) + twrite(s, n, 1); + + if (!IS_SET(MODE_CRLF)) { + ttywriteraw(s, n); + return; + } + + /* This is similar to how the kernel handles ONLCR for ttys */ + while (n > 0) { + if (*s == '\r') { + next = s + 1; + ttywriteraw("\r\n", 2); + } else { + next = memchr(s, '\r', n); + DEFAULT(next, s + n); + ttywriteraw(s, next - s); + } + n -= next - s; + s = next; + } +} + +void +ttywriteraw(const char *s, size_t n) +{ + fd_set wfd, rfd; + ssize_t r; + size_t lim = 256; + + /* + * Remember that we are using a pty, which might be a modem line. + * Writing too much will clog the line. That's why we are doing this + * dance. + * FIXME: Migrate the world to Plan 9. + */ + while (n > 0) { + FD_ZERO(&wfd); + FD_ZERO(&rfd); + FD_SET(cmdfd, &wfd); + FD_SET(cmdfd, &rfd); + + /* Check if we can write. */ + if (pselect(cmdfd+1, &rfd, &wfd, NULL, NULL, NULL) < 0) { + if (errno == EINTR) + continue; + die("select failed: %s\n", strerror(errno)); + } + if (FD_ISSET(cmdfd, &wfd)) { + /* + * Only write the bytes written by ttywrite() or the + * default of 256. This seems to be a reasonable value + * for a serial line. Bigger values might clog the I/O. + */ + if ((r = write(cmdfd, s, (n < lim)? n : lim)) < 0) + goto write_error; + if (r < n) { + /* + * We weren't able to write out everything. + * This means the buffer is getting full + * again. Empty it. + */ + if (n < lim) + lim = ttyread(); + n -= r; + s += r; + } else { + /* All bytes have been written. */ + break; + } + } + if (FD_ISSET(cmdfd, &rfd)) + lim = ttyread(); + } + return; + +write_error: + die("write error on tty: %s\n", strerror(errno)); +} + +void +ttyresize(int tw, int th) +{ + struct winsize w; + + w.ws_row = term.row; + w.ws_col = term.col; + w.ws_xpixel = tw; + w.ws_ypixel = th; + if (ioctl(cmdfd, TIOCSWINSZ, &w) < 0) + fprintf(stderr, "Couldn't set window size: %s\n", strerror(errno)); +} + +void +ttyhangup() +{ + /* Send SIGHUP to shell */ + kill(pid, SIGHUP); +} + +int +tattrset(int attr) +{ + int i, j; + + for (i = 0; i < term.row-1; i++) { + for (j = 0; j < term.col-1; j++) { + if (term.line[i][j].mode & attr) + return 1; + } + } + + return 0; +} + +void +tsetdirt(int top, int bot) +{ + int i; + + LIMIT(top, 0, term.row-1); + LIMIT(bot, 0, term.row-1); + + for (i = top; i <= bot; i++) + term.dirty[i] = 1; +} + +void +tsetdirtattr(int attr) +{ + int i, j; + + for (i = 0; i < term.row-1; i++) { + for (j = 0; j < term.col-1; j++) { + if (term.line[i][j].mode & attr) { + tsetdirt(i, i); + break; + } + } + } +} + +void +tfulldirt(void) +{ + tsetdirt(0, term.row-1); +} + +void +tcursor(int mode) +{ + static TCursor c[2]; + int alt = IS_SET(MODE_ALTSCREEN); + + if (mode == CURSOR_SAVE) { + c[alt] = term.c; + } else if (mode == CURSOR_LOAD) { + term.c = c[alt]; + tmoveto(c[alt].x, c[alt].y); + } +} + +void +treset(void) +{ + uint i; + + term.c = (TCursor){{ + .mode = ATTR_NULL, + .fg = defaultfg, + .bg = defaultbg + }, .x = 0, .y = 0, .state = CURSOR_DEFAULT}; + + memset(term.tabs, 0, term.col * sizeof(*term.tabs)); + for (i = tabspaces; i < term.col; i += tabspaces) + term.tabs[i] = 1; + term.top = 0; + term.bot = term.row - 1; + term.mode = MODE_WRAP|MODE_UTF8; + memset(term.trantbl, CS_USA, sizeof(term.trantbl)); + term.charset = 0; + + for (i = 0; i < 2; i++) { + tmoveto(0, 0); + tcursor(CURSOR_SAVE); + tclearregion(0, 0, term.col-1, term.row-1); + tswapscreen(); + } +} + +void +tnew(int col, int row) +{ + term = (Term){ .c = { .attr = { .fg = defaultfg, .bg = defaultbg } } }; + tresize(col, row); + treset(); +} + +void +tswapscreen(void) +{ + Line *tmp = term.line; + + term.line = term.alt; + term.alt = tmp; + term.mode ^= MODE_ALTSCREEN; + tfulldirt(); +} + +void +kscrolldown(const Arg* a) +{ + int n = a->i; + + if (n < 0) + n = term.row + n; + + if (n > term.scr) + n = term.scr; + + if (term.scr > 0) { + term.scr -= n; + selscroll(0, -n); + tfulldirt(); + } +} + +void +kscrollup(const Arg* a) +{ + int n = a->i; + + if (n < 0) + n = term.row + n; + + if (term.scr <= HISTSIZE-n) { + term.scr += n; + selscroll(0, n); + tfulldirt(); + } +} + +int +tisaltscr(void) +{ + return IS_SET(MODE_ALTSCREEN); +} + +void +tscrolldown(int orig, int n, int copyhist) +{ + int i; + Line temp; + + LIMIT(n, 0, term.bot-orig+1); + + if (copyhist) { + term.histi = (term.histi - 1 + HISTSIZE) % HISTSIZE; + temp = term.hist[term.histi]; + term.hist[term.histi] = term.line[term.bot]; + term.line[term.bot] = temp; + } + + tsetdirt(orig, term.bot-n); + tclearregion(0, term.bot-n+1, term.col-1, term.bot); + + for (i = term.bot; i >= orig+n; i--) { + temp = term.line[i]; + term.line[i] = term.line[i-n]; + term.line[i-n] = temp; + } + + if (term.scr == 0) + selscroll(orig, n); +} + +void +tscrollup(int orig, int n, int copyhist) +{ + int i; + Line temp; + + LIMIT(n, 0, term.bot-orig+1); + + if (copyhist) { + term.histi = (term.histi + 1) % HISTSIZE; + temp = term.hist[term.histi]; + term.hist[term.histi] = term.line[orig]; + term.line[orig] = temp; + } + + if (term.scr > 0 && term.scr < HISTSIZE) + term.scr = MIN(term.scr + n, HISTSIZE-1); + + tclearregion(0, orig, term.col-1, orig+n-1); + tsetdirt(orig+n, term.bot); + + for (i = orig; i <= term.bot-n; i++) { + temp = term.line[i]; + term.line[i] = term.line[i+n]; + term.line[i+n] = temp; + } + + if (term.scr == 0) + selscroll(orig, -n); +} + +void +selscroll(int orig, int n) +{ + if (sel.ob.x == -1) + return; + + if (BETWEEN(sel.nb.y, orig, term.bot) != BETWEEN(sel.ne.y, orig, term.bot)) { + selclear(); + } else if (BETWEEN(sel.nb.y, orig, term.bot)) { + sel.ob.y += n; + sel.oe.y += n; + if (sel.ob.y < term.top || sel.ob.y > term.bot || + sel.oe.y < term.top || sel.oe.y > term.bot) { + selclear(); + } else { + selnormalize(); + } + } +} + +void +tnewline(int first_col) +{ + int y = term.c.y; + + if (y == term.bot) { + tscrollup(term.top, 1, 1); + } else { + y++; + } + tmoveto(first_col ? 0 : term.c.x, y); +} + +void +csiparse(void) +{ + char *p = csiescseq.buf, *np; + long int v; + + csiescseq.narg = 0; + if (*p == '?') { + csiescseq.priv = 1; + p++; + } + + csiescseq.buf[csiescseq.len] = '\0'; + while (p < csiescseq.buf+csiescseq.len) { + np = NULL; + v = strtol(p, &np, 10); + if (np == p) + v = 0; + if (v == LONG_MAX || v == LONG_MIN) + v = -1; + csiescseq.arg[csiescseq.narg++] = v; + p = np; + if (*p != ';' || csiescseq.narg == ESC_ARG_SIZ) + break; + p++; + } + csiescseq.mode[0] = *p++; + csiescseq.mode[1] = (p < csiescseq.buf+csiescseq.len) ? *p : '\0'; +} + +/* for absolute user moves, when decom is set */ +void +tmoveato(int x, int y) +{ + tmoveto(x, y + ((term.c.state & CURSOR_ORIGIN) ? term.top: 0)); +} + +void +tmoveto(int x, int y) +{ + int miny, maxy; + + if (term.c.state & CURSOR_ORIGIN) { + miny = term.top; + maxy = term.bot; + } else { + miny = 0; + maxy = term.row - 1; + } + term.c.state &= ~CURSOR_WRAPNEXT; + term.c.x = LIMIT(x, 0, term.col-1); + term.c.y = LIMIT(y, miny, maxy); +} + +void +tsetchar(Rune u, Glyph *attr, int x, int y) +{ + static char *vt100_0[62] = { /* 0x41 - 0x7e */ + "↑", "↓", "→", "←", "█", "▚", "☃", /* A - G */ + 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */ + 0, 0, 0, 0, 0, 0, 0, 0, /* P - W */ + 0, 0, 0, 0, 0, 0, 0, " ", /* X - _ */ + "◆", "▒", "␉", "␌", "␍", "␊", "°", "±", /* ` - g */ + "␤", "␋", "┘", "┐", "┌", "└", "┼", "⎺", /* h - o */ + "⎻", "─", "⎼", "⎽", "├", "┤", "┴", "┬", /* p - w */ + "│", "≤", "≥", "π", "≠", "£", "·", /* x - ~ */ + }; + + /* + * The table is proudly stolen from rxvt. + */ + if (term.trantbl[term.charset] == CS_GRAPHIC0 && + BETWEEN(u, 0x41, 0x7e) && vt100_0[u - 0x41]) + utf8decode(vt100_0[u - 0x41], &u, UTF_SIZ); + + if (term.line[y][x].mode & ATTR_WIDE) { + if (x+1 < term.col) { + term.line[y][x+1].u = ' '; + term.line[y][x+1].mode &= ~ATTR_WDUMMY; + } + } else if (term.line[y][x].mode & ATTR_WDUMMY) { + term.line[y][x-1].u = ' '; + term.line[y][x-1].mode &= ~ATTR_WIDE; + } + + term.dirty[y] = 1; + term.line[y][x] = *attr; + term.line[y][x].u = u; +} + +void +tclearregion(int x1, int y1, int x2, int y2) +{ + int x, y, temp; + Glyph *gp; + + if (x1 > x2) + temp = x1, x1 = x2, x2 = temp; + if (y1 > y2) + temp = y1, y1 = y2, y2 = temp; + + LIMIT(x1, 0, term.col-1); + LIMIT(x2, 0, term.col-1); + LIMIT(y1, 0, term.row-1); + LIMIT(y2, 0, term.row-1); + + for (y = y1; y <= y2; y++) { + term.dirty[y] = 1; + for (x = x1; x <= x2; x++) { + gp = &term.line[y][x]; + if (selected(x, y)) + selclear(); + gp->fg = term.c.attr.fg; + gp->bg = term.c.attr.bg; + gp->mode = 0; + gp->u = ' '; + } + } +} + +void +tdeletechar(int n) +{ + int dst, src, size; + Glyph *line; + + LIMIT(n, 0, term.col - term.c.x); + + dst = term.c.x; + src = term.c.x + n; + size = term.col - src; + line = term.line[term.c.y]; + + memmove(&line[dst], &line[src], size * sizeof(Glyph)); + tclearregion(term.col-n, term.c.y, term.col-1, term.c.y); +} + +void +tinsertblank(int n) +{ + int dst, src, size; + Glyph *line; + + LIMIT(n, 0, term.col - term.c.x); + + dst = term.c.x + n; + src = term.c.x; + size = term.col - dst; + line = term.line[term.c.y]; + + memmove(&line[dst], &line[src], size * sizeof(Glyph)); + tclearregion(src, term.c.y, dst - 1, term.c.y); +} + +void +tinsertblankline(int n) +{ + if (BETWEEN(term.c.y, term.top, term.bot)) + tscrolldown(term.c.y, n, 0); +} + +void +tdeleteline(int n) +{ + if (BETWEEN(term.c.y, term.top, term.bot)) + tscrollup(term.c.y, n, 0); +} + +int32_t +tdefcolor(int *attr, int *npar, int l) +{ + int32_t idx = -1; + uint r, g, b; + + switch (attr[*npar + 1]) { + case 2: /* direct color in RGB space */ + if (*npar + 4 >= l) { + fprintf(stderr, + "erresc(38): Incorrect number of parameters (%d)\n", + *npar); + break; + } + r = attr[*npar + 2]; + g = attr[*npar + 3]; + b = attr[*npar + 4]; + *npar += 4; + if (!BETWEEN(r, 0, 255) || !BETWEEN(g, 0, 255) || !BETWEEN(b, 0, 255)) + fprintf(stderr, "erresc: bad rgb color (%u,%u,%u)\n", + r, g, b); + else + idx = TRUECOLOR(r, g, b); + break; + case 5: /* indexed color */ + if (*npar + 2 >= l) { + fprintf(stderr, + "erresc(38): Incorrect number of parameters (%d)\n", + *npar); + break; + } + *npar += 2; + if (!BETWEEN(attr[*npar], 0, 255)) + fprintf(stderr, "erresc: bad fgcolor %d\n", attr[*npar]); + else + idx = attr[*npar]; + break; + case 0: /* implemented defined (only foreground) */ + case 1: /* transparent */ + case 3: /* direct color in CMY space */ + case 4: /* direct color in CMYK space */ + default: + fprintf(stderr, + "erresc(38): gfx attr %d unknown\n", attr[*npar]); + break; + } + + return idx; +} + +void +tsetattr(int *attr, int l) +{ + int i; + int32_t idx; + + for (i = 0; i < l; i++) { + switch (attr[i]) { + case 0: + term.c.attr.mode &= ~( + ATTR_BOLD | + ATTR_FAINT | + ATTR_ITALIC | + ATTR_UNDERLINE | + ATTR_BLINK | + ATTR_REVERSE | + ATTR_INVISIBLE | + ATTR_STRUCK ); + term.c.attr.fg = defaultfg; + term.c.attr.bg = defaultbg; + break; + case 1: + term.c.attr.mode |= ATTR_BOLD; + break; + case 2: + term.c.attr.mode |= ATTR_FAINT; + break; + case 3: + term.c.attr.mode |= ATTR_ITALIC; + break; + case 4: + term.c.attr.mode |= ATTR_UNDERLINE; + break; + case 5: /* slow blink */ + /* FALLTHROUGH */ + case 6: /* rapid blink */ + term.c.attr.mode |= ATTR_BLINK; + break; + case 7: + term.c.attr.mode |= ATTR_REVERSE; + break; + case 8: + term.c.attr.mode |= ATTR_INVISIBLE; + break; + case 9: + term.c.attr.mode |= ATTR_STRUCK; + break; + case 22: + term.c.attr.mode &= ~(ATTR_BOLD | ATTR_FAINT); + break; + case 23: + term.c.attr.mode &= ~ATTR_ITALIC; + break; + case 24: + term.c.attr.mode &= ~ATTR_UNDERLINE; + break; + case 25: + term.c.attr.mode &= ~ATTR_BLINK; + break; + case 27: + term.c.attr.mode &= ~ATTR_REVERSE; + break; + case 28: + term.c.attr.mode &= ~ATTR_INVISIBLE; + break; + case 29: + term.c.attr.mode &= ~ATTR_STRUCK; + break; + case 38: + if ((idx = tdefcolor(attr, &i, l)) >= 0) + term.c.attr.fg = idx; + break; + case 39: + term.c.attr.fg = defaultfg; + break; + case 48: + if ((idx = tdefcolor(attr, &i, l)) >= 0) + term.c.attr.bg = idx; + break; + case 49: + term.c.attr.bg = defaultbg; + break; + default: + if (BETWEEN(attr[i], 30, 37)) { + term.c.attr.fg = attr[i] - 30; + } else if (BETWEEN(attr[i], 40, 47)) { + term.c.attr.bg = attr[i] - 40; + } else if (BETWEEN(attr[i], 90, 97)) { + term.c.attr.fg = attr[i] - 90 + 8; + } else if (BETWEEN(attr[i], 100, 107)) { + term.c.attr.bg = attr[i] - 100 + 8; + } else { + fprintf(stderr, + "erresc(default): gfx attr %d unknown\n", + attr[i]); + csidump(); + } + break; + } + } +} + +void +tsetscroll(int t, int b) +{ + int temp; + + LIMIT(t, 0, term.row-1); + LIMIT(b, 0, term.row-1); + if (t > b) { + temp = t; + t = b; + b = temp; + } + term.top = t; + term.bot = b; +} + +void +tsetmode(int priv, int set, int *args, int narg) +{ + int alt, *lim; + + for (lim = args + narg; args < lim; ++args) { + if (priv) { + switch (*args) { + case 1: /* DECCKM -- Cursor key */ + xsetmode(set, MODE_APPCURSOR); + break; + case 5: /* DECSCNM -- Reverse video */ + xsetmode(set, MODE_REVERSE); + break; + case 6: /* DECOM -- Origin */ + MODBIT(term.c.state, set, CURSOR_ORIGIN); + tmoveato(0, 0); + break; + case 7: /* DECAWM -- Auto wrap */ + MODBIT(term.mode, set, MODE_WRAP); + break; + case 0: /* Error (IGNORED) */ + case 2: /* DECANM -- ANSI/VT52 (IGNORED) */ + case 3: /* DECCOLM -- Column (IGNORED) */ + case 4: /* DECSCLM -- Scroll (IGNORED) */ + case 8: /* DECARM -- Auto repeat (IGNORED) */ + case 18: /* DECPFF -- Printer feed (IGNORED) */ + case 19: /* DECPEX -- Printer extent (IGNORED) */ + case 42: /* DECNRCM -- National characters (IGNORED) */ + case 12: /* att610 -- Start blinking cursor (IGNORED) */ + break; + case 25: /* DECTCEM -- Text Cursor Enable Mode */ + xsetmode(!set, MODE_HIDE); + break; + case 9: /* X10 mouse compatibility mode */ + xsetpointermotion(0); + xsetmode(0, MODE_MOUSE); + xsetmode(set, MODE_MOUSEX10); + break; + case 1000: /* 1000: report button press */ + xsetpointermotion(0); + xsetmode(0, MODE_MOUSE); + xsetmode(set, MODE_MOUSEBTN); + break; + case 1002: /* 1002: report motion on button press */ + xsetpointermotion(0); + xsetmode(0, MODE_MOUSE); + xsetmode(set, MODE_MOUSEMOTION); + break; + case 1003: /* 1003: enable all mouse motions */ + xsetpointermotion(set); + xsetmode(0, MODE_MOUSE); + xsetmode(set, MODE_MOUSEMANY); + break; + case 1004: /* 1004: send focus events to tty */ + xsetmode(set, MODE_FOCUS); + break; + case 1006: /* 1006: extended reporting mode */ + xsetmode(set, MODE_MOUSESGR); + break; + case 1034: + xsetmode(set, MODE_8BIT); + break; + case 1049: /* swap screen & set/restore cursor as xterm */ + if (!allowaltscreen) + break; + tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD); + /* FALLTHROUGH */ + case 47: /* swap screen */ + case 1047: + if (!allowaltscreen) + break; + alt = IS_SET(MODE_ALTSCREEN); + if (alt) { + tclearregion(0, 0, term.col-1, + term.row-1); + } + if (set ^ alt) /* set is always 1 or 0 */ + tswapscreen(); + if (*args != 1049) + break; + /* FALLTHROUGH */ + case 1048: + tcursor((set) ? CURSOR_SAVE : CURSOR_LOAD); + break; + case 2004: /* 2004: bracketed paste mode */ + xsetmode(set, MODE_BRCKTPASTE); + break; + /* Not implemented mouse modes. See comments there. */ + case 1001: /* mouse highlight mode; can hang the + terminal by design when implemented. */ + case 1005: /* UTF-8 mouse mode; will confuse + applications not supporting UTF-8 + and luit. */ + case 1015: /* urxvt mangled mouse mode; incompatible + and can be mistaken for other control + codes. */ + break; + default: + fprintf(stderr, + "erresc: unknown private set/reset mode %d\n", + *args); + break; + } + } else { + switch (*args) { + case 0: /* Error (IGNORED) */ + break; + case 2: + xsetmode(set, MODE_KBDLOCK); + break; + case 4: /* IRM -- Insertion-replacement */ + MODBIT(term.mode, set, MODE_INSERT); + break; + case 12: /* SRM -- Send/Receive */ + MODBIT(term.mode, !set, MODE_ECHO); + break; + case 20: /* LNM -- Linefeed/new line */ + MODBIT(term.mode, set, MODE_CRLF); + break; + default: + fprintf(stderr, + "erresc: unknown set/reset mode %d\n", + *args); + break; + } + } + } +} + +void +csihandle(void) +{ + char buf[40]; + int len; + + switch (csiescseq.mode[0]) { + default: + unknown: + fprintf(stderr, "erresc: unknown csi "); + csidump(); + /* die(""); */ + break; + case '@': /* ICH -- Insert blank char */ + DEFAULT(csiescseq.arg[0], 1); + tinsertblank(csiescseq.arg[0]); + break; + case 'A': /* CUU -- Cursor Up */ + DEFAULT(csiescseq.arg[0], 1); + tmoveto(term.c.x, term.c.y-csiescseq.arg[0]); + break; + case 'B': /* CUD -- Cursor Down */ + case 'e': /* VPR --Cursor Down */ + DEFAULT(csiescseq.arg[0], 1); + tmoveto(term.c.x, term.c.y+csiescseq.arg[0]); + break; + case 'i': /* MC -- Media Copy */ + switch (csiescseq.arg[0]) { + case 0: + tdump(); + break; + case 1: + tdumpline(term.c.y); + break; + case 2: + tdumpsel(); + break; + case 4: + term.mode &= ~MODE_PRINT; + break; + case 5: + term.mode |= MODE_PRINT; + break; + } + break; + case 'c': /* DA -- Device Attributes */ + if (csiescseq.arg[0] == 0) + ttywrite(vtiden, strlen(vtiden), 0); + break; + case 'b': /* REP -- if last char is printable print it more times */ + DEFAULT(csiescseq.arg[0], 1); + if (term.lastc) + while (csiescseq.arg[0]-- > 0) + tputc(term.lastc); + break; + case 'C': /* CUF -- Cursor Forward */ + case 'a': /* HPR -- Cursor Forward */ + DEFAULT(csiescseq.arg[0], 1); + tmoveto(term.c.x+csiescseq.arg[0], term.c.y); + break; + case 'D': /* CUB -- Cursor Backward */ + DEFAULT(csiescseq.arg[0], 1); + tmoveto(term.c.x-csiescseq.arg[0], term.c.y); + break; + case 'E': /* CNL -- Cursor Down and first col */ + DEFAULT(csiescseq.arg[0], 1); + tmoveto(0, term.c.y+csiescseq.arg[0]); + break; + case 'F': /* CPL -- Cursor Up and first col */ + DEFAULT(csiescseq.arg[0], 1); + tmoveto(0, term.c.y-csiescseq.arg[0]); + break; + case 'g': /* TBC -- Tabulation clear */ + switch (csiescseq.arg[0]) { + case 0: /* clear current tab stop */ + term.tabs[term.c.x] = 0; + break; + case 3: /* clear all the tabs */ + memset(term.tabs, 0, term.col * sizeof(*term.tabs)); + break; + default: + goto unknown; + } + break; + case 'G': /* CHA -- Move to */ + case '`': /* HPA */ + DEFAULT(csiescseq.arg[0], 1); + tmoveto(csiescseq.arg[0]-1, term.c.y); + break; + case 'H': /* CUP -- Move to */ + case 'f': /* HVP */ + DEFAULT(csiescseq.arg[0], 1); + DEFAULT(csiescseq.arg[1], 1); + tmoveato(csiescseq.arg[1]-1, csiescseq.arg[0]-1); + break; + case 'I': /* CHT -- Cursor Forward Tabulation tab stops */ + DEFAULT(csiescseq.arg[0], 1); + tputtab(csiescseq.arg[0]); + break; + case 'J': /* ED -- Clear screen */ + switch (csiescseq.arg[0]) { + case 0: /* below */ + tclearregion(term.c.x, term.c.y, term.col-1, term.c.y); + if (term.c.y < term.row-1) { + tclearregion(0, term.c.y+1, term.col-1, + term.row-1); + } + break; + case 1: /* above */ + if (term.c.y > 1) + tclearregion(0, 0, term.col-1, term.c.y-1); + tclearregion(0, term.c.y, term.c.x, term.c.y); + break; + case 2: /* all */ + tclearregion(0, 0, term.col-1, term.row-1); + break; + default: + goto unknown; + } + break; + case 'K': /* EL -- Clear line */ + switch (csiescseq.arg[0]) { + case 0: /* right */ + tclearregion(term.c.x, term.c.y, term.col-1, + term.c.y); + break; + case 1: /* left */ + tclearregion(0, term.c.y, term.c.x, term.c.y); + break; + case 2: /* all */ + tclearregion(0, term.c.y, term.col-1, term.c.y); + break; + } + break; + case 'S': /* SU -- Scroll line up */ + DEFAULT(csiescseq.arg[0], 1); + tscrollup(term.top, csiescseq.arg[0], 0); + break; + case 'T': /* SD -- Scroll line down */ + DEFAULT(csiescseq.arg[0], 1); + tscrolldown(term.top, csiescseq.arg[0], 0); + break; + case 'L': /* IL -- Insert blank lines */ + DEFAULT(csiescseq.arg[0], 1); + tinsertblankline(csiescseq.arg[0]); + break; + case 'l': /* RM -- Reset Mode */ + tsetmode(csiescseq.priv, 0, csiescseq.arg, csiescseq.narg); + break; + case 'M': /* DL -- Delete lines */ + DEFAULT(csiescseq.arg[0], 1); + tdeleteline(csiescseq.arg[0]); + break; + case 'X': /* ECH -- Erase char */ + DEFAULT(csiescseq.arg[0], 1); + tclearregion(term.c.x, term.c.y, + term.c.x + csiescseq.arg[0] - 1, term.c.y); + break; + case 'P': /* DCH -- Delete char */ + DEFAULT(csiescseq.arg[0], 1); + tdeletechar(csiescseq.arg[0]); + break; + case 'Z': /* CBT -- Cursor Backward Tabulation tab stops */ + DEFAULT(csiescseq.arg[0], 1); + tputtab(-csiescseq.arg[0]); + break; + case 'd': /* VPA -- Move to */ + DEFAULT(csiescseq.arg[0], 1); + tmoveato(term.c.x, csiescseq.arg[0]-1); + break; + case 'h': /* SM -- Set terminal mode */ + tsetmode(csiescseq.priv, 1, csiescseq.arg, csiescseq.narg); + break; + case 'm': /* SGR -- Terminal attribute (color) */ + tsetattr(csiescseq.arg, csiescseq.narg); + break; + case 'n': /* DSR – Device Status Report (cursor position) */ + if (csiescseq.arg[0] == 6) { + len = snprintf(buf, sizeof(buf), "\033[%i;%iR", + term.c.y+1, term.c.x+1); + ttywrite(buf, len, 0); + } + break; + case 'r': /* DECSTBM -- Set Scrolling Region */ + if (csiescseq.priv) { + goto unknown; + } else { + DEFAULT(csiescseq.arg[0], 1); + DEFAULT(csiescseq.arg[1], term.row); + tsetscroll(csiescseq.arg[0]-1, csiescseq.arg[1]-1); + tmoveato(0, 0); + } + break; + case 's': /* DECSC -- Save cursor position (ANSI.SYS) */ + tcursor(CURSOR_SAVE); + break; + case 'u': /* DECRC -- Restore cursor position (ANSI.SYS) */ + tcursor(CURSOR_LOAD); + break; + case ' ': + switch (csiescseq.mode[1]) { + case 'q': /* DECSCUSR -- Set Cursor Style */ + if (xsetcursor(csiescseq.arg[0])) + goto unknown; + break; + default: + goto unknown; + } + break; + } +} + +void +csidump(void) +{ + size_t i; + uint c; + + fprintf(stderr, "ESC["); + for (i = 0; i < csiescseq.len; i++) { + c = csiescseq.buf[i] & 0xff; + if (isprint(c)) { + putc(c, stderr); + } else if (c == '\n') { + fprintf(stderr, "(\\n)"); + } else if (c == '\r') { + fprintf(stderr, "(\\r)"); + } else if (c == 0x1b) { + fprintf(stderr, "(\\e)"); + } else { + fprintf(stderr, "(%02x)", c); + } + } + putc('\n', stderr); +} + +void +csireset(void) +{ + memset(&csiescseq, 0, sizeof(csiescseq)); +} + +void +strhandle(void) +{ + char *p = NULL, *dec; + int j, narg, par; + + term.esc &= ~(ESC_STR_END|ESC_STR); + strparse(); + par = (narg = strescseq.narg) ? atoi(strescseq.args[0]) : 0; + + switch (strescseq.type) { + case ']': /* OSC -- Operating System Command */ + switch (par) { + case 0: + case 1: + case 2: + if (narg > 1) + xsettitle(strescseq.args[1]); + return; + case 52: + if (narg > 2 && allowwindowops) { + dec = base64dec(strescseq.args[2]); + if (dec) { + xsetsel(dec); + xclipcopy(); + } else { + fprintf(stderr, "erresc: invalid base64\n"); + } + } + return; + case 4: /* color set */ + if (narg < 3) + break; + p = strescseq.args[2]; + /* FALLTHROUGH */ + case 104: /* color reset, here p = NULL */ + j = (narg > 1) ? atoi(strescseq.args[1]) : -1; + if (xsetcolorname(j, p)) { + if (par == 104 && narg <= 1) + return; /* color reset without parameter */ + fprintf(stderr, "erresc: invalid color j=%d, p=%s\n", + j, p ? p : "(null)"); + } else { + /* + * TODO if defaultbg color is changed, borders + * are dirty + */ + redraw(); + } + return; + } + break; + case 'k': /* old title set compatibility */ + xsettitle(strescseq.args[0]); + return; + case 'P': /* DCS -- Device Control String */ + case '_': /* APC -- Application Program Command */ + case '^': /* PM -- Privacy Message */ + return; + } + + fprintf(stderr, "erresc: unknown str "); + strdump(); +} + +void +strparse(void) +{ + int c; + char *p = strescseq.buf; + + strescseq.narg = 0; + strescseq.buf[strescseq.len] = '\0'; + + if (*p == '\0') + return; + + while (strescseq.narg < STR_ARG_SIZ) { + strescseq.args[strescseq.narg++] = p; + while ((c = *p) != ';' && c != '\0') + ++p; + if (c == '\0') + return; + *p++ = '\0'; + } +} + +void +externalpipe(const Arg *arg) +{ + int to[2]; + char buf[UTF_SIZ]; + void (*oldsigpipe)(int); + Glyph *bp, *end; + int lastpos, n, newline; + + if (pipe(to) == -1) + return; + + switch (fork()) { + case -1: + close(to[0]); + close(to[1]); + return; + case 0: + dup2(to[0], STDIN_FILENO); + close(to[0]); + close(to[1]); + execvp(((char **)arg->v)[0], (char **)arg->v); + fprintf(stderr, "st: execvp %s\n", ((char **)arg->v)[0]); + perror("failed"); + exit(0); + } + + close(to[0]); + /* ignore sigpipe for now, in case child exists early */ + oldsigpipe = signal(SIGPIPE, SIG_IGN); + newline = 0; + for (n = 0; n < term.row; n++) { + bp = term.line[n]; + lastpos = MIN(tlinelen(n) + 1, term.col) - 1; + if (lastpos < 0) + break; + end = &bp[lastpos + 1]; + for (; bp < end; ++bp) + if (xwrite(to[1], buf, utf8encode(bp->u, buf)) < 0) + break; + if ((newline = term.line[n][lastpos].mode & ATTR_WRAP)) + continue; + if (xwrite(to[1], "\n", 1) < 0) + break; + newline = 0; + } + if (newline) + (void)xwrite(to[1], "\n", 1); + close(to[1]); + /* restore */ + signal(SIGPIPE, oldsigpipe); +} + +void +strdump(void) +{ + size_t i; + uint c; + + fprintf(stderr, "ESC%c", strescseq.type); + for (i = 0; i < strescseq.len; i++) { + c = strescseq.buf[i] & 0xff; + if (c == '\0') { + putc('\n', stderr); + return; + } else if (isprint(c)) { + putc(c, stderr); + } else if (c == '\n') { + fprintf(stderr, "(\\n)"); + } else if (c == '\r') { + fprintf(stderr, "(\\r)"); + } else if (c == 0x1b) { + fprintf(stderr, "(\\e)"); + } else { + fprintf(stderr, "(%02x)", c); + } + } + fprintf(stderr, "ESC\\\n"); +} + +void +strreset(void) +{ + strescseq = (STREscape){ + .buf = xrealloc(strescseq.buf, STR_BUF_SIZ), + .siz = STR_BUF_SIZ, + }; +} + +void +sendbreak(const Arg *arg) +{ + if (tcsendbreak(cmdfd, 0)) + perror("Error sending break"); +} + +void +tprinter(char *s, size_t len) +{ + if (iofd != -1 && xwrite(iofd, s, len) < 0) { + perror("Error writing to output file"); + close(iofd); + iofd = -1; + } +} + +void +toggleprinter(const Arg *arg) +{ + term.mode ^= MODE_PRINT; +} + +void +printscreen(const Arg *arg) +{ + tdump(); +} + +void +printsel(const Arg *arg) +{ + tdumpsel(); +} + +void +tdumpsel(void) +{ + char *ptr; + + if ((ptr = getsel())) { + tprinter(ptr, strlen(ptr)); + free(ptr); + } +} + +void +tdumpline(int n) +{ + char buf[UTF_SIZ]; + Glyph *bp, *end; + + bp = &term.line[n][0]; + end = &bp[MIN(tlinelen(n), term.col) - 1]; + if (bp != end || bp->u != ' ') { + for ( ; bp <= end; ++bp) + tprinter(buf, utf8encode(bp->u, buf)); + } + tprinter("\n", 1); +} + +void +tdump(void) +{ + int i; + + for (i = 0; i < term.row; ++i) + tdumpline(i); +} + +void +tputtab(int n) +{ + uint x = term.c.x; + + if (n > 0) { + while (x < term.col && n--) + for (++x; x < term.col && !term.tabs[x]; ++x) + /* nothing */ ; + } else if (n < 0) { + while (x > 0 && n++) + for (--x; x > 0 && !term.tabs[x]; --x) + /* nothing */ ; + } + term.c.x = LIMIT(x, 0, term.col-1); +} + +void +tdefutf8(char ascii) +{ + if (ascii == 'G') + term.mode |= MODE_UTF8; + else if (ascii == '@') + term.mode &= ~MODE_UTF8; +} + +void +tdeftran(char ascii) +{ + static char cs[] = "0B"; + static int vcs[] = {CS_GRAPHIC0, CS_USA}; + char *p; + + if ((p = strchr(cs, ascii)) == NULL) { + fprintf(stderr, "esc unhandled charset: ESC ( %c\n", ascii); + } else { + term.trantbl[term.icharset] = vcs[p - cs]; + } +} + +void +tdectest(char c) +{ + int x, y; + + if (c == '8') { /* DEC screen alignment test. */ + for (x = 0; x < term.col; ++x) { + for (y = 0; y < term.row; ++y) + tsetchar('E', &term.c.attr, x, y); + } + } +} + +void +tstrsequence(uchar c) +{ + switch (c) { + case 0x90: /* DCS -- Device Control String */ + c = 'P'; + break; + case 0x9f: /* APC -- Application Program Command */ + c = '_'; + break; + case 0x9e: /* PM -- Privacy Message */ + c = '^'; + break; + case 0x9d: /* OSC -- Operating System Command */ + c = ']'; + break; + } + strreset(); + strescseq.type = c; + term.esc |= ESC_STR; +} + +void +tcontrolcode(uchar ascii) +{ + switch (ascii) { + case '\t': /* HT */ + tputtab(1); + return; + case '\b': /* BS */ + tmoveto(term.c.x-1, term.c.y); + return; + case '\r': /* CR */ + tmoveto(0, term.c.y); + return; + case '\f': /* LF */ + case '\v': /* VT */ + case '\n': /* LF */ + /* go to first col if the mode is set */ + tnewline(IS_SET(MODE_CRLF)); + return; + case '\a': /* BEL */ + if (term.esc & ESC_STR_END) { + /* backwards compatibility to xterm */ + strhandle(); + } else { + xbell(); + } + break; + case '\033': /* ESC */ + csireset(); + term.esc &= ~(ESC_CSI|ESC_ALTCHARSET|ESC_TEST); + term.esc |= ESC_START; + return; + case '\016': /* SO (LS1 -- Locking shift 1) */ + case '\017': /* SI (LS0 -- Locking shift 0) */ + term.charset = 1 - (ascii - '\016'); + return; + case '\032': /* SUB */ + tsetchar('?', &term.c.attr, term.c.x, term.c.y); + /* FALLTHROUGH */ + case '\030': /* CAN */ + csireset(); + break; + case '\005': /* ENQ (IGNORED) */ + case '\000': /* NUL (IGNORED) */ + case '\021': /* XON (IGNORED) */ + case '\023': /* XOFF (IGNORED) */ + case 0177: /* DEL (IGNORED) */ + return; + case 0x80: /* TODO: PAD */ + case 0x81: /* TODO: HOP */ + case 0x82: /* TODO: BPH */ + case 0x83: /* TODO: NBH */ + case 0x84: /* TODO: IND */ + break; + case 0x85: /* NEL -- Next line */ + tnewline(1); /* always go to first col */ + break; + case 0x86: /* TODO: SSA */ + case 0x87: /* TODO: ESA */ + break; + case 0x88: /* HTS -- Horizontal tab stop */ + term.tabs[term.c.x] = 1; + break; + case 0x89: /* TODO: HTJ */ + case 0x8a: /* TODO: VTS */ + case 0x8b: /* TODO: PLD */ + case 0x8c: /* TODO: PLU */ + case 0x8d: /* TODO: RI */ + case 0x8e: /* TODO: SS2 */ + case 0x8f: /* TODO: SS3 */ + case 0x91: /* TODO: PU1 */ + case 0x92: /* TODO: PU2 */ + case 0x93: /* TODO: STS */ + case 0x94: /* TODO: CCH */ + case 0x95: /* TODO: MW */ + case 0x96: /* TODO: SPA */ + case 0x97: /* TODO: EPA */ + case 0x98: /* TODO: SOS */ + case 0x99: /* TODO: SGCI */ + break; + case 0x9a: /* DECID -- Identify Terminal */ + ttywrite(vtiden, strlen(vtiden), 0); + break; + case 0x9b: /* TODO: CSI */ + case 0x9c: /* TODO: ST */ + break; + case 0x90: /* DCS -- Device Control String */ + case 0x9d: /* OSC -- Operating System Command */ + case 0x9e: /* PM -- Privacy Message */ + case 0x9f: /* APC -- Application Program Command */ + tstrsequence(ascii); + return; + } + /* only CAN, SUB, \a and C1 chars interrupt a sequence */ + term.esc &= ~(ESC_STR_END|ESC_STR); +} + +/* + * returns 1 when the sequence is finished and it hasn't to read + * more characters for this sequence, otherwise 0 + */ +int +eschandle(uchar ascii) +{ + switch (ascii) { + case '[': + term.esc |= ESC_CSI; + return 0; + case '#': + term.esc |= ESC_TEST; + return 0; + case '%': + term.esc |= ESC_UTF8; + return 0; + case 'P': /* DCS -- Device Control String */ + case '_': /* APC -- Application Program Command */ + case '^': /* PM -- Privacy Message */ + case ']': /* OSC -- Operating System Command */ + case 'k': /* old title set compatibility */ + tstrsequence(ascii); + return 0; + case 'n': /* LS2 -- Locking shift 2 */ + case 'o': /* LS3 -- Locking shift 3 */ + term.charset = 2 + (ascii - 'n'); + break; + case '(': /* GZD4 -- set primary charset G0 */ + case ')': /* G1D4 -- set secondary charset G1 */ + case '*': /* G2D4 -- set tertiary charset G2 */ + case '+': /* G3D4 -- set quaternary charset G3 */ + term.icharset = ascii - '('; + term.esc |= ESC_ALTCHARSET; + return 0; + case 'D': /* IND -- Linefeed */ + if (term.c.y == term.bot) { + tscrollup(term.top, 1, 1); + } else { + tmoveto(term.c.x, term.c.y+1); + } + break; + case 'E': /* NEL -- Next line */ + tnewline(1); /* always go to first col */ + break; + case 'H': /* HTS -- Horizontal tab stop */ + term.tabs[term.c.x] = 1; + break; + case 'M': /* RI -- Reverse index */ + if (term.c.y == term.top) { + tscrolldown(term.top, 1, 1); + } else { + tmoveto(term.c.x, term.c.y-1); + } + break; + case 'Z': /* DECID -- Identify Terminal */ + ttywrite(vtiden, strlen(vtiden), 0); + break; + case 'c': /* RIS -- Reset to initial state */ + treset(); + resettitle(); + xloadcols(); + break; + case '=': /* DECPAM -- Application keypad */ + xsetmode(1, MODE_APPKEYPAD); + break; + case '>': /* DECPNM -- Normal keypad */ + xsetmode(0, MODE_APPKEYPAD); + break; + case '7': /* DECSC -- Save Cursor */ + tcursor(CURSOR_SAVE); + break; + case '8': /* DECRC -- Restore Cursor */ + tcursor(CURSOR_LOAD); + break; + case '\\': /* ST -- String Terminator */ + if (term.esc & ESC_STR_END) + strhandle(); + break; + default: + fprintf(stderr, "erresc: unknown sequence ESC 0x%02X '%c'\n", + (uchar) ascii, isprint(ascii)? ascii:'.'); + break; + } + return 1; +} + +void +tputc(Rune u) +{ + char c[UTF_SIZ]; + int control; + int width, len; + Glyph *gp; + + control = ISCONTROL(u); + if (u < 127 || !IS_SET(MODE_UTF8)) { + c[0] = u; + width = len = 1; + } else { + len = utf8encode(u, c); + if (!control && (width = wcwidth(u)) == -1) + width = 1; + } + + if (IS_SET(MODE_PRINT)) + tprinter(c, len); + + /* + * STR sequence must be checked before anything else + * because it uses all following characters until it + * receives a ESC, a SUB, a ST or any other C1 control + * character. + */ + if (term.esc & ESC_STR) { + if (u == '\a' || u == 030 || u == 032 || u == 033 || + ISCONTROLC1(u)) { + term.esc &= ~(ESC_START|ESC_STR); + term.esc |= ESC_STR_END; + goto check_control_code; + } + + if (strescseq.len+len >= strescseq.siz) { + /* + * Here is a bug in terminals. If the user never sends + * some code to stop the str or esc command, then st + * will stop responding. But this is better than + * silently failing with unknown characters. At least + * then users will report back. + * + * In the case users ever get fixed, here is the code: + */ + /* + * term.esc = 0; + * strhandle(); + */ + if (strescseq.siz > (SIZE_MAX - UTF_SIZ) / 2) + return; + strescseq.siz *= 2; + strescseq.buf = xrealloc(strescseq.buf, strescseq.siz); + } + + memmove(&strescseq.buf[strescseq.len], c, len); + strescseq.len += len; + return; + } + +check_control_code: + /* + * Actions of control codes must be performed as soon they arrive + * because they can be embedded inside a control sequence, and + * they must not cause conflicts with sequences. + */ + if (control) { + tcontrolcode(u); + /* + * control codes are not shown ever + */ + if (!term.esc) + term.lastc = 0; + return; + } else if (term.esc & ESC_START) { + if (term.esc & ESC_CSI) { + csiescseq.buf[csiescseq.len++] = u; + if (BETWEEN(u, 0x40, 0x7E) + || csiescseq.len >= \ + sizeof(csiescseq.buf)-1) { + term.esc = 0; + csiparse(); + csihandle(); + } + return; + } else if (term.esc & ESC_UTF8) { + tdefutf8(u); + } else if (term.esc & ESC_ALTCHARSET) { + tdeftran(u); + } else if (term.esc & ESC_TEST) { + tdectest(u); + } else { + if (!eschandle(u)) + return; + /* sequence already finished */ + } + term.esc = 0; + /* + * All characters which form part of a sequence are not + * printed + */ + return; + } + if (selected(term.c.x, term.c.y)) + selclear(); + + gp = &term.line[term.c.y][term.c.x]; + if (IS_SET(MODE_WRAP) && (term.c.state & CURSOR_WRAPNEXT)) { + gp->mode |= ATTR_WRAP; + tnewline(1); + gp = &term.line[term.c.y][term.c.x]; + } + + if (IS_SET(MODE_INSERT) && term.c.x+width < term.col) + memmove(gp+width, gp, (term.col - term.c.x - width) * sizeof(Glyph)); + + if (term.c.x+width > term.col) { + tnewline(1); + gp = &term.line[term.c.y][term.c.x]; + } + + tsetchar(u, &term.c.attr, term.c.x, term.c.y); + term.lastc = u; + + if (width == 2) { + gp->mode |= ATTR_WIDE; + if (term.c.x+1 < term.col) { + gp[1].u = '\0'; + gp[1].mode = ATTR_WDUMMY; + } + } + if (term.c.x+width < term.col) { + tmoveto(term.c.x+width, term.c.y); + } else { + term.c.state |= CURSOR_WRAPNEXT; + } +} + +int +twrite(const char *buf, int buflen, int show_ctrl) +{ + int charsize; + Rune u; + int n; + + for (n = 0; n < buflen; n += charsize) { + if (IS_SET(MODE_UTF8)) { + /* process a complete utf8 char */ + charsize = utf8decode(buf + n, &u, buflen - n); + if (charsize == 0) + break; + } else { + u = buf[n] & 0xFF; + charsize = 1; + } + if (show_ctrl && ISCONTROL(u)) { + if (u & 0x80) { + u &= 0x7f; + tputc('^'); + tputc('['); + } else if (u != '\n' && u != '\r' && u != '\t') { + u ^= 0x40; + tputc('^'); + } + } + tputc(u); + } + return n; +} + +void +tresize(int col, int row) +{ + int i, j; + int minrow = MIN(row, term.row); + int mincol = MIN(col, term.col); + int *bp; + TCursor c; + + if (col < 1 || row < 1) { + fprintf(stderr, + "tresize: error resizing to %dx%d\n", col, row); + return; + } + + /* + * slide screen to keep cursor where we expect it - + * tscrollup would work here, but we can optimize to + * memmove because we're freeing the earlier lines + */ + for (i = 0; i <= term.c.y - row; i++) { + free(term.line[i]); + free(term.alt[i]); + } + /* ensure that both src and dst are not NULL */ + if (i > 0) { + memmove(term.line, term.line + i, row * sizeof(Line)); + memmove(term.alt, term.alt + i, row * sizeof(Line)); + } + for (i += row; i < term.row; i++) { + free(term.line[i]); + free(term.alt[i]); + } + + /* resize to new height */ + term.line = xrealloc(term.line, row * sizeof(Line)); + term.alt = xrealloc(term.alt, row * sizeof(Line)); + term.dirty = xrealloc(term.dirty, row * sizeof(*term.dirty)); + term.tabs = xrealloc(term.tabs, col * sizeof(*term.tabs)); + + for (i = 0; i < HISTSIZE; i++) { + term.hist[i] = xrealloc(term.hist[i], col * sizeof(Glyph)); + for (j = mincol; j < col; j++) { + term.hist[i][j] = term.c.attr; + term.hist[i][j].u = ' '; + } + } + + /* resize each row to new width, zero-pad if needed */ + for (i = 0; i < minrow; i++) { + term.line[i] = xrealloc(term.line[i], col * sizeof(Glyph)); + term.alt[i] = xrealloc(term.alt[i], col * sizeof(Glyph)); + } + + /* allocate any new rows */ + for (/* i = minrow */; i < row; i++) { + term.line[i] = xmalloc(col * sizeof(Glyph)); + term.alt[i] = xmalloc(col * sizeof(Glyph)); + } + if (col > term.col) { + bp = term.tabs + term.col; + + memset(bp, 0, sizeof(*term.tabs) * (col - term.col)); + while (--bp > term.tabs && !*bp) + /* nothing */ ; + for (bp += tabspaces; bp < term.tabs + col; bp += tabspaces) + *bp = 1; + } + /* update terminal size */ + term.col = col; + term.row = row; + /* reset scrolling region */ + tsetscroll(0, row-1); + /* make use of the LIMIT in tmoveto */ + tmoveto(term.c.x, term.c.y); + /* Clearing both screens (it makes dirty all lines) */ + c = term.c; + for (i = 0; i < 2; i++) { + if (mincol < col && 0 < minrow) { + tclearregion(mincol, 0, col - 1, minrow - 1); + } + if (0 < col && minrow < row) { + tclearregion(0, minrow, col - 1, row - 1); + } + tswapscreen(); + tcursor(CURSOR_LOAD); + } + term.c = c; +} + +void +resettitle(void) +{ + xsettitle(NULL); +} + +void +drawregion(int x1, int y1, int x2, int y2) +{ + int y; + + for (y = y1; y < y2; y++) { + if (!term.dirty[y]) + continue; + + term.dirty[y] = 0; + xdrawline(TLINE(y), x1, y, x2); + } +} + +void +draw(void) +{ + int cx = term.c.x, ocx = term.ocx, ocy = term.ocy; + + if (!xstartdraw()) + return; + + /* adjust cursor position */ + LIMIT(term.ocx, 0, term.col-1); + LIMIT(term.ocy, 0, term.row-1); + if (term.line[term.ocy][term.ocx].mode & ATTR_WDUMMY) + term.ocx--; + if (term.line[term.c.y][cx].mode & ATTR_WDUMMY) + cx--; + + term.dirty[term.ocy] = 1; + drawregion(0, 0, term.col, term.row); + if (term.scr == 0) + xdrawcursor(cx, term.c.y, term.line[term.c.y][cx], + term.ocx, term.ocy, term.line[term.ocy][term.ocx]); + term.ocx = cx; + term.ocy = term.c.y; + xfinishdraw(); + if (ocx != term.ocx || ocy != term.ocy) + xximspot(term.ocx, term.ocy); +} + +void +redraw(void) +{ + tfulldirt(); + draw(); +} diff --git a/src/st/st.h b/src/st/st.h new file mode 100644 index 0000000..cd5d997 --- /dev/null +++ b/src/st/st.h @@ -0,0 +1,129 @@ +/* See LICENSE for license details. */ + +#include +#include + +/* macros */ +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) < (b) ? (b) : (a)) +#define LEN(a) (sizeof(a) / sizeof(a)[0]) +#define BETWEEN(x, a, b) ((a) <= (x) && (x) <= (b)) +#define DIVCEIL(n, d) (((n) + ((d) - 1)) / (d)) +#define DEFAULT(a, b) (a) = (a) ? (a) : (b) +#define LIMIT(x, a, b) (x) = (x) < (a) ? (a) : (x) > (b) ? (b) : (x) +#define ATTRCMP(a, b) ((a).mode != (b).mode || (a).fg != (b).fg || \ + (a).bg != (b).bg) +#define TIMEDIFF(t1, t2) ((t1.tv_sec-t2.tv_sec)*1000 + \ + (t1.tv_nsec-t2.tv_nsec)/1E6) +#define MODBIT(x, set, bit) ((set) ? ((x) |= (bit)) : ((x) &= ~(bit))) + +#define TRUECOLOR(r,g,b) (1 << 24 | (r) << 16 | (g) << 8 | (b)) +#define IS_TRUECOL(x) (1 << 24 & (x)) + +enum glyph_attribute { + ATTR_NULL = 0, + ATTR_BOLD = 1 << 0, + ATTR_FAINT = 1 << 1, + ATTR_ITALIC = 1 << 2, + ATTR_UNDERLINE = 1 << 3, + ATTR_BLINK = 1 << 4, + ATTR_REVERSE = 1 << 5, + ATTR_INVISIBLE = 1 << 6, + ATTR_STRUCK = 1 << 7, + ATTR_WRAP = 1 << 8, + ATTR_WIDE = 1 << 9, + ATTR_WDUMMY = 1 << 10, + ATTR_BOLD_FAINT = ATTR_BOLD | ATTR_FAINT, +}; + +enum selection_mode { + SEL_IDLE = 0, + SEL_EMPTY = 1, + SEL_READY = 2 +}; + +enum selection_type { + SEL_REGULAR = 1, + SEL_RECTANGULAR = 2 +}; + +enum selection_snap { + SNAP_WORD = 1, + SNAP_LINE = 2 +}; + +typedef unsigned char uchar; +typedef unsigned int uint; +typedef unsigned long ulong; +typedef unsigned short ushort; + +typedef uint_least32_t Rune; + +#define Glyph Glyph_ +typedef struct { + Rune u; /* character code */ + ushort mode; /* attribute flags */ + uint32_t fg; /* foreground */ + uint32_t bg; /* background */ +} Glyph; + +typedef Glyph *Line; + +typedef union { + int i; + uint ui; + float f; + const void *v; + const char *s; +} Arg; + +void die(const char *, ...); +void redraw(void); +void draw(void); + +void kscrolldown(const Arg *); +void kscrollup(const Arg *); +int tisaltscr(void); +void printscreen(const Arg *); +void printsel(const Arg *); +void sendbreak(const Arg *); +void toggleprinter(const Arg *); +void externalpipe(const Arg *); + +int tattrset(int); +void tnew(int, int); +void tresize(int, int); +void tsetdirtattr(int); +void ttyhangup(void); +int ttynew(char *, char *, char *, char **); +size_t ttyread(void); +void ttyresize(int, int); +void ttywrite(const char *, size_t, int); + +void resettitle(void); + +void selclear(void); +void selinit(void); +void selstart(int, int, int); +void selextend(int, int, int, int); +int selected(int, int); +char *getsel(void); + +size_t utf8encode(Rune, char *); + +void *xmalloc(size_t); +void *xrealloc(void *, size_t); +char *xstrdup(char *); + +/* config.h globals */ +extern char *utmp; +extern char *scroll; +extern char *stty_args; +extern char *vtiden; +extern wchar_t *worddelimiters; +extern int allowaltscreen; +extern int allowwindowops; +extern char *termname; +extern unsigned int tabspaces; +extern unsigned int defaultfg; +extern unsigned int defaultbg; diff --git a/src/st/st.info b/src/st/st.info new file mode 100644 index 0000000..8201ad6 --- /dev/null +++ b/src/st/st.info @@ -0,0 +1,239 @@ +st-mono| simpleterm monocolor, + acsc=+C\,D-A.B0E``aaffgghFiGjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~, + am, + bce, + bel=^G, + blink=\E[5m, + bold=\E[1m, + cbt=\E[Z, + cvvis=\E[?25h, + civis=\E[?25l, + clear=\E[H\E[2J, + cnorm=\E[?12l\E[?25h, + colors#2, + cols#80, + cr=^M, + csr=\E[%i%p1%d;%p2%dr, + cub=\E[%p1%dD, + cub1=^H, + cud1=^J, + cud=\E[%p1%dB, + cuf1=\E[C, + cuf=\E[%p1%dC, + cup=\E[%i%p1%d;%p2%dH, + cuu1=\E[A, + cuu=\E[%p1%dA, + dch=\E[%p1%dP, + dch1=\E[P, + dim=\E[2m, + dl=\E[%p1%dM, + dl1=\E[M, + ech=\E[%p1%dX, + ed=\E[J, + el=\E[K, + el1=\E[1K, + enacs=\E)0, + flash=\E[?5h$<80/>\E[?5l, + fsl=^G, + home=\E[H, + hpa=\E[%i%p1%dG, + hs, + ht=^I, + hts=\EH, + ich=\E[%p1%d@, + il1=\E[L, + il=\E[%p1%dL, + ind=^J, + indn=\E[%p1%dS, + invis=\E[8m, + is2=\E[4l\E>\E[?1034l, + it#8, + kel=\E[1;2F, + ked=\E[1;5F, + ka1=\E[1~, + ka3=\E[5~, + kc1=\E[4~, + kc3=\E[6~, + kbs=\177, + kcbt=\E[Z, + kb2=\EOu, + kcub1=\EOD, + kcud1=\EOB, + kcuf1=\EOC, + kcuu1=\EOA, + kDC=\E[3;2~, + kent=\EOM, + kEND=\E[1;2F, + kIC=\E[2;2~, + kNXT=\E[6;2~, + kPRV=\E[5;2~, + kHOM=\E[1;2H, + kLFT=\E[1;2D, + kRIT=\E[1;2C, + kind=\E[1;2B, + kri=\E[1;2A, + kclr=\E[3;5~, + kdl1=\E[3;2~, + kdch1=\E[3~, + kich1=\E[2~, + kend=\E[4~, + kf1=\EOP, + kf2=\EOQ, + kf3=\EOR, + kf4=\EOS, + kf5=\E[15~, + kf6=\E[17~, + kf7=\E[18~, + kf8=\E[19~, + kf9=\E[20~, + kf10=\E[21~, + kf11=\E[23~, + kf12=\E[24~, + kf13=\E[1;2P, + kf14=\E[1;2Q, + kf15=\E[1;2R, + kf16=\E[1;2S, + kf17=\E[15;2~, + kf18=\E[17;2~, + kf19=\E[18;2~, + kf20=\E[19;2~, + kf21=\E[20;2~, + kf22=\E[21;2~, + kf23=\E[23;2~, + kf24=\E[24;2~, + kf25=\E[1;5P, + kf26=\E[1;5Q, + kf27=\E[1;5R, + kf28=\E[1;5S, + kf29=\E[15;5~, + kf30=\E[17;5~, + kf31=\E[18;5~, + kf32=\E[19;5~, + kf33=\E[20;5~, + kf34=\E[21;5~, + kf35=\E[23;5~, + kf36=\E[24;5~, + kf37=\E[1;6P, + kf38=\E[1;6Q, + kf39=\E[1;6R, + kf40=\E[1;6S, + kf41=\E[15;6~, + kf42=\E[17;6~, + kf43=\E[18;6~, + kf44=\E[19;6~, + kf45=\E[20;6~, + kf46=\E[21;6~, + kf47=\E[23;6~, + kf48=\E[24;6~, + kf49=\E[1;3P, + kf50=\E[1;3Q, + kf51=\E[1;3R, + kf52=\E[1;3S, + kf53=\E[15;3~, + kf54=\E[17;3~, + kf55=\E[18;3~, + kf56=\E[19;3~, + kf57=\E[20;3~, + kf58=\E[21;3~, + kf59=\E[23;3~, + kf60=\E[24;3~, + kf61=\E[1;4P, + kf62=\E[1;4Q, + kf63=\E[1;4R, + khome=\E[1~, + kil1=\E[2;5~, + krmir=\E[2;2~, + knp=\E[6~, + kmous=\E[M, + kpp=\E[5~, + lines#24, + mir, + msgr, + npc, + op=\E[39;49m, + pairs#64, + mc0=\E[i, + mc4=\E[4i, + mc5=\E[5i, + rc=\E8, + rev=\E[7m, + ri=\EM, + rin=\E[%p1%dT, + ritm=\E[23m, + rmacs=\E(B, + rmcup=\E[?1049l, + rmir=\E[4l, + rmkx=\E[?1l\E>, + rmso=\E[27m, + rmul=\E[24m, + rs1=\Ec, + rs2=\E[4l\E>\E[?1034l, + sc=\E7, + sitm=\E[3m, + sgr0=\E[0m, + smacs=\E(0, + smcup=\E[?1049h, + smir=\E[4h, + smkx=\E[?1h\E=, + smso=\E[7m, + smul=\E[4m, + tbc=\E[3g, + tsl=\E]0;, + xenl, + vpa=\E[%i%p1%dd, +# XTerm extensions + rmxx=\E[29m, + smxx=\E[9m, +# disabled rep for now: causes some issues with older ncurses versions. +# rep=%p1%c\E[%p2%{1}%-%db, +# tmux extensions, see TERMINFO EXTENSIONS in tmux(1) + Tc, + Ms=\E]52;%p1%s;%p2%s\007, + Se=\E[2 q, + Ss=\E[%p1%d q, + +st| simpleterm, + use=st-mono, + colors#8, + setab=\E[4%p1%dm, + setaf=\E[3%p1%dm, + setb=\E[4%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m, + setf=\E[3%?%p1%{1}%=%t4%e%p1%{3}%=%t6%e%p1%{4}%=%t1%e%p1%{6}%=%t3%e%p1%d%;m, + sgr=%?%p9%t\E(0%e\E(B%;\E[0%?%p6%t;1%;%?%p2%t;4%;%?%p1%p3%|%t;7%;%?%p4%t;5%;%?%p7%t;8%;m, + +st-256color| simpleterm with 256 colors, + use=st, + ccc, + colors#256, + oc=\E]104\007, + pairs#32767, +# Nicked from xterm-256color + initc=\E]4;%p1%d;rgb\:%p2%{255}%*%{1000}%/%2.2X/%p3%{255}%*%{1000}%/%2.2X/%p4%{255}%*%{1000}%/%2.2X\E\\, + setab=\E[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m, + setaf=\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m, + +st-meta| simpleterm with meta key, + use=st, + km, + rmm=\E[?1034l, + smm=\E[?1034h, + rs2=\E[4l\E>\E[?1034h, + is2=\E[4l\E>\E[?1034h, + +st-meta-256color| simpleterm with meta key and 256 colors, + use=st-256color, + km, + rmm=\E[?1034l, + smm=\E[?1034h, + rs2=\E[4l\E>\E[?1034h, + is2=\E[4l\E>\E[?1034h, + +st-bs| simpleterm with backspace as backspace, + use=st, + kbs=\010, + kdch1=\177, + +st-bs-256color| simpleterm with backspace as backspace and 256colors, + use=st-256color, + kbs=\010, + kdch1=\177, diff --git a/src/st/win.h b/src/st/win.h new file mode 100644 index 0000000..a6ef1b9 --- /dev/null +++ b/src/st/win.h @@ -0,0 +1,39 @@ +/* See LICENSE for license details. */ + +enum win_mode { + MODE_VISIBLE = 1 << 0, + MODE_FOCUSED = 1 << 1, + MODE_APPKEYPAD = 1 << 2, + MODE_MOUSEBTN = 1 << 3, + MODE_MOUSEMOTION = 1 << 4, + MODE_REVERSE = 1 << 5, + MODE_KBDLOCK = 1 << 6, + MODE_HIDE = 1 << 7, + MODE_APPCURSOR = 1 << 8, + MODE_MOUSESGR = 1 << 9, + MODE_8BIT = 1 << 10, + MODE_BLINK = 1 << 11, + MODE_FBLINK = 1 << 12, + MODE_FOCUS = 1 << 13, + MODE_MOUSEX10 = 1 << 14, + MODE_MOUSEMANY = 1 << 15, + MODE_BRCKTPASTE = 1 << 16, + MODE_NUMLOCK = 1 << 17, + MODE_MOUSE = MODE_MOUSEBTN|MODE_MOUSEMOTION|MODE_MOUSEX10\ + |MODE_MOUSEMANY, +}; + +void xbell(void); +void xclipcopy(void); +void xdrawcursor(int, int, Glyph, int, int, Glyph); +void xdrawline(Line, int, int, int); +void xfinishdraw(void); +void xloadcols(void); +int xsetcolorname(int, const char *); +void xsettitle(char *); +int xsetcursor(int); +void xsetmode(int, unsigned int); +void xsetpointermotion(int); +void xsetsel(char *); +int xstartdraw(void); +void xximspot(int, int); diff --git a/src/st/x.c b/src/st/x.c new file mode 100644 index 0000000..cbce980 --- /dev/null +++ b/src/st/x.c @@ -0,0 +1,2671 @@ +/* See LICENSE for license details. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char *argv0; +#include "arg.h" +#include "st.h" +#include "win.h" +#include "hb.h" +#include "anode_scale.h" + +/* types used in config.h */ +typedef struct { + uint mod; + KeySym keysym; + void (*func)(const Arg *); + const Arg arg; +} Shortcut; + +typedef struct { + uint mod; + uint button; + void (*func)(const Arg *); + const Arg arg; + uint release; +} MouseShortcut; + +typedef struct { + KeySym k; + uint mask; + char *s; + /* three-valued logic variables: 0 indifferent, 1 on, -1 off */ + signed char appkey; /* application keypad */ + signed char appcursor; /* application cursor */ +} Key; + +/* Xresources preferences */ +enum resource_type { + STRING = 0, + INTEGER = 1, + FLOAT = 2 +}; + +typedef struct { + char *name; + enum resource_type type; + void *dst; +} ResourcePref; + +/* X modifiers */ +#define XK_ANY_MOD UINT_MAX +#define XK_NO_MOD 0 +#define XK_SWITCH_MOD (1<<13) + +/* function definitions used in config.h */ +static void clipcopy(const Arg *); +static void clippaste(const Arg *); +static void numlock(const Arg *); +static void selpaste(const Arg *); +static void zoom(const Arg *); +static void zoomabs(const Arg *); +static void zoomreset(const Arg *); +static void ttysend(const Arg *); +static void wheelscrollup(const Arg *); +static void wheelscrolldown(const Arg *); +static void invert(const Arg *); +static void toggleselectionmode(const Arg *); + +/* config.h for applying patches and the configuration. */ +#include "config.h" + +/* XEMBED messages */ +#define XEMBED_FOCUS_IN 4 +#define XEMBED_FOCUS_OUT 5 + +/* macros */ +#define IS_SET(flag) ((win.mode & (flag)) != 0) +#define TRUERED(x) (((x) & 0xff0000) >> 8) +#define TRUEGREEN(x) (((x) & 0xff00)) +#define TRUEBLUE(x) (((x) & 0xff) << 8) + +typedef XftDraw *Draw; +typedef XftColor Color; +typedef XftGlyphFontSpec GlyphFontSpec; + +/* Purely graphic info */ +typedef struct { + int tw, th; /* tty width and height */ + int w, h; /* window width and height */ + int ch; /* char height */ + int cw; /* char width */ + int mode; /* window state/mode flags */ + int cursor; /* cursor style */ +} TermWindow; + +typedef struct { + Display *dpy; + Colormap cmap; + Window win; + Drawable buf; + GlyphFontSpec *specbuf; /* font spec buffer used for rendering */ + Atom xembed, wmdeletewin, netwmname, netwmpid, selectionmode; + struct { + XIM xim; + XIC xic; + XPoint spot; + XVaNestedList spotlist; + } ime; + Draw draw; + Visual *vis; + XSetWindowAttributes attrs; + int scr; + int isfixed; /* is fixed geometry? */ + int l, t; /* left and top offset */ + int gm; /* geometry mask */ + Cursor vpointer, bpointer; + int pointerisvisible; + int xi_opcode; + int xfixes_ok; +} XWindow; + +typedef struct { + Atom xtarget; + char *primary, *clipboard; + struct timespec tclick1; + struct timespec tclick2; +} XSelection; + +/* Font structure */ +#define Font Font_ +typedef struct { + int height; + int width; + int ascent; + int descent; + int badslant; + int badweight; + short lbearing; + short rbearing; + XftFont *match; + FcFontSet *set; + FcPattern *pattern; +} Font; + +/* Drawing Context */ +typedef struct { + Color *col; + size_t collen; + Font font, bfont, ifont, ibfont; + GC gc; +} DC; + +static inline ushort sixd_to_16bit(int); +static int xmakeglyphfontspecs(XftGlyphFontSpec *, const Glyph *, int, int, int); +static void xdrawglyphfontspecs(const XftGlyphFontSpec *, Glyph, int, int, int); +static void xdrawglyph(Glyph, int, int); +static void xclear(int, int, int, int); +static int xgeommasktogravity(int); +static int ximopen(Display *); +static void ximinstantiate(Display *, XPointer, XPointer); +static void ximdestroy(XIM, XPointer, XPointer); +static int xicdestroy(XIC, XPointer, XPointer); +static void xinit(int, int); +static void cresize(int, int); +static void xresize(int, int); +static void xhints(void); +static int xloadcolor(int, const char *, Color *); +static int xloadfont(Font *, FcPattern *); +static void xloadfonts(char *, double); +static void xunloadfont(Font *); +static void xunloadfonts(void); +static void xsetenv(void); +static void xseturgency(int); +static int evcol(XEvent *); +static int evrow(XEvent *); + +static void expose(XEvent *); +static void visibility(XEvent *); +static void unmap(XEvent *); +static void kpress(XEvent *); +static void cmessage(XEvent *); +static void resize(XEvent *); +static void focus(XEvent *); +static uint buttonmask(uint); +static int mouseaction(XEvent *, uint); +static void brelease(XEvent *); +static void bpress(XEvent *); +static void bmotion(XEvent *); +static void propnotify(XEvent *); +static void selnotify(XEvent *); +static void selclear_(XEvent *); +static void selrequest(XEvent *); +static void setsel(char *, Time); +static void mousesel(XEvent *, int); +static void mousereport(XEvent *); +static char *kmap(KeySym, uint); +static int match(uint, uint); +static void updateselectionmodeatom(void); +static void st_xi_raw_select(int); +static void xhidepointer(void); +static void xshowpointer(void); + +static void run(void); +static void usage(void); + +static void (*handler[LASTEvent])(XEvent *) = { + [KeyPress] = kpress, + [ClientMessage] = cmessage, + [ConfigureNotify] = resize, + [VisibilityNotify] = visibility, + [UnmapNotify] = unmap, + [Expose] = expose, + [FocusIn] = focus, + [FocusOut] = focus, + [MotionNotify] = bmotion, + [ButtonPress] = bpress, + [ButtonRelease] = brelease, +/* + * Uncomment if you want the selection to disappear when you select something + * different in another window. + */ + [SelectionClear] = selclear_, + [SelectionNotify] = selnotify, +/* + * PropertyNotify is only turned on when there is some INCR transfer happening + * for the selection retrieval. + */ + [PropertyNotify] = propnotify, + [SelectionRequest] = selrequest, +}; + +/* Globals */ +static DC dc; +static XWindow xw; +static XSelection xsel; +static TermWindow win; + +/* Font Ring Cache */ +enum { + FRC_NORMAL, + FRC_ITALIC, + FRC_BOLD, + FRC_ITALICBOLD +}; + +typedef struct { + XftFont *font; + int flags; + Rune unicodep; +} Fontcache; + +/* Fontcache is an array now. A new font will be appended to the array. */ +static Fontcache *frc = NULL; +static int frclen = 0; +static int frccap = 0; +static char *usedfont = NULL; +static double usedfontsize = 0; +static double defaultfontsize = 0; + +static char *opt_class = NULL; +static char **opt_cmd = NULL; +static char *opt_embed = NULL; +static char *opt_font = NULL; +static char *opt_io = NULL; +static char *opt_line = NULL; +static char *opt_name = NULL; +static char *opt_title = NULL; + +static int invertcolors = 0; +static int oldbutton = 3; /* button event on startup: 3 = release */ +static int selectionmodeenabled = 1; + +#define MAX_XDIRTY_RECTS 32 + +typedef struct { + int x1, y1, x2, y2; +} XDirtyRect; + +typedef struct { + XftFont *font; + FT_UInt glyph; + uint32_t fg; + uint32_t bg; + ushort mode; + uchar nonspace; + uchar valid; +} XRenderedCell; + +static XDirtyRect xdirty[MAX_XDIRTY_RECTS]; +static int xdirty_cnt = 0; +static int xw_buf_ready = 0; +static XRenderedCell *xw_cells = NULL; +static int xw_cells_cols = 0; +static int xw_cells_rows = 0; +static int xlast_cur_drawn = 0; + +static void +xinvalidatecells(void) +{ + if (xw_cells && xw_cells_cols > 0 && xw_cells_rows > 0) + memset(xw_cells, 0, (size_t)xw_cells_cols * (size_t)xw_cells_rows * sizeof(*xw_cells)); + xlast_cur_drawn = 0; +} + +static void +xinvalidatecellrange(int y, int x1, int x2) +{ + int x; + + if (!xw_cells || y < 0 || y >= xw_cells_rows) + return; + if (x1 < 0) + x1 = 0; + if (x2 > xw_cells_cols) + x2 = xw_cells_cols; + for (x = x1; x < x2; x++) + xw_cells[y * xw_cells_cols + x].valid = 0; +} + +static void +xmarkdirty(int x1, int y1, int x2, int y2) +{ + int i; + + if (x1 < 0) + x1 = 0; + if (y1 < 0) + y1 = 0; + if (x2 > win.w) + x2 = win.w; + if (y2 > win.h) + y2 = win.h; + if (x1 >= x2 || y1 >= y2) + return; + + for (i = 0; i < xdirty_cnt; i++) { + if (x1 >= xdirty[i].x1 && y1 >= xdirty[i].y1 && + x2 <= xdirty[i].x2 && y2 <= xdirty[i].y2) + return; + if ((y1 == xdirty[i].y1 && y2 == xdirty[i].y2 && + x1 <= xdirty[i].x2 + win.cw && x2 >= xdirty[i].x1 - win.cw) || + (x1 == xdirty[i].x1 && x2 == xdirty[i].x2 && + y1 <= xdirty[i].y2 && y2 >= xdirty[i].y1) || + (x1 < xdirty[i].x2 && x2 > xdirty[i].x1 && + y1 < xdirty[i].y2 && y2 > xdirty[i].y1)) { + if (x1 < xdirty[i].x1) + xdirty[i].x1 = x1; + if (y1 < xdirty[i].y1) + xdirty[i].y1 = y1; + if (x2 > xdirty[i].x2) + xdirty[i].x2 = x2; + if (y2 > xdirty[i].y2) + xdirty[i].y2 = y2; + return; + } + } + + if (xdirty_cnt >= MAX_XDIRTY_RECTS) { + for (i = 1; i < xdirty_cnt; i++) { + if (xdirty[i].x1 < xdirty[0].x1) + xdirty[0].x1 = xdirty[i].x1; + if (xdirty[i].y1 < xdirty[0].y1) + xdirty[0].y1 = xdirty[i].y1; + if (xdirty[i].x2 > xdirty[0].x2) + xdirty[0].x2 = xdirty[i].x2; + if (xdirty[i].y2 > xdirty[0].y2) + xdirty[0].y2 = xdirty[i].y2; + } + if (x1 < xdirty[0].x1) + xdirty[0].x1 = x1; + if (y1 < xdirty[0].y1) + xdirty[0].y1 = y1; + if (x2 > xdirty[0].x2) + xdirty[0].x2 = x2; + if (y2 > xdirty[0].y2) + xdirty[0].y2 = y2; + xdirty_cnt = 1; + return; + } + + xdirty[xdirty_cnt++] = (XDirtyRect){ x1, y1, x2, y2 }; +} + +void +invert(const Arg *dummy) +{ + invertcolors = !invertcolors; + xinvalidatecells(); + redraw(); +} + +void +toggleselectionmode(const Arg *dummy) +{ + selectionmodeenabled = !selectionmodeenabled; + selclear(); + updateselectionmodeatom(); +} + +Color +invertedcolor(Color *clr) { + XRenderColor rc; + Color inverted; + rc.red = ~clr->color.red; + rc.green = ~clr->color.green; + rc.blue = ~clr->color.blue; + rc.alpha = clr->color.alpha; + XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &rc, &inverted); + return inverted; +} + +void +clipcopy(const Arg *dummy) +{ + Atom clipboard; + + free(xsel.clipboard); + xsel.clipboard = NULL; + + if (xsel.primary != NULL) { + xsel.clipboard = xstrdup(xsel.primary); + clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); + XSetSelectionOwner(xw.dpy, clipboard, xw.win, CurrentTime); + } +} + +void +clippaste(const Arg *dummy) +{ + Atom clipboard; + + clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); + XConvertSelection(xw.dpy, clipboard, xsel.xtarget, clipboard, + xw.win, CurrentTime); +} + +void +selpaste(const Arg *dummy) +{ + XConvertSelection(xw.dpy, XA_PRIMARY, xsel.xtarget, XA_PRIMARY, + xw.win, CurrentTime); +} + +void +numlock(const Arg *dummy) +{ + win.mode ^= MODE_NUMLOCK; +} + +void +zoom(const Arg *arg) +{ + Arg larg; + + larg.f = usedfontsize + arg->f; + zoomabs(&larg); +} + +void +zoomabs(const Arg *arg) +{ + xunloadfonts(); + xloadfonts(usedfont, arg->f); + cresize(0, 0); + redraw(); + xhints(); +} + +void +zoomreset(const Arg *arg) +{ + Arg larg; + + if (defaultfontsize > 0) { + larg.f = defaultfontsize; + zoomabs(&larg); + } +} + +void +ttysend(const Arg *arg) +{ + ttywrite(arg->s, strlen(arg->s), 1); +} + +void +wheelscrollup(const Arg *a) +{ + if (tisaltscr()) + ttysend(&(Arg){ .s = "\031" }); + else + kscrollup(a); +} + +void +wheelscrolldown(const Arg *a) +{ + if (tisaltscr()) + ttysend(&(Arg){ .s = "\005" }); + else + kscrolldown(a); +} + +int +evcol(XEvent *e) +{ + int x = e->xbutton.x - borderpx; + LIMIT(x, 0, win.tw - 1); + return x / win.cw; +} + +int +evrow(XEvent *e) +{ + int y = e->xbutton.y - borderpx; + LIMIT(y, 0, win.th - 1); + return y / win.ch; +} + +void +mousesel(XEvent *e, int done) +{ + int type, seltype = SEL_REGULAR; + uint state = e->xbutton.state & ~(Button1Mask | forcemousemod); + + for (type = 1; type < LEN(selmasks); ++type) { + if (match(selmasks[type], state)) { + seltype = type; + break; + } + } + selextend(evcol(e), evrow(e), seltype, done); + if (done) + setsel(getsel(), e->xbutton.time); +} + +void +mousereport(XEvent *e) +{ + int len, x = evcol(e), y = evrow(e), + button = e->xbutton.button, state = e->xbutton.state; + char buf[40]; + static int ox, oy; + + /* from urxvt */ + if (e->xbutton.type == MotionNotify) { + if (x == ox && y == oy) + return; + if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY)) + return; + /* MOUSE_MOTION: no reporting if no button is pressed */ + if (IS_SET(MODE_MOUSEMOTION) && oldbutton == 3) + return; + + button = oldbutton + 32; + ox = x; + oy = y; + } else { + if (!IS_SET(MODE_MOUSESGR) && e->xbutton.type == ButtonRelease) { + button = 3; + } else { + button -= Button1; + if (button >= 3) + button += 64 - 3; + } + if (e->xbutton.type == ButtonPress) { + oldbutton = button; + ox = x; + oy = y; + } else if (e->xbutton.type == ButtonRelease) { + oldbutton = 3; + /* MODE_MOUSEX10: no button release reporting */ + if (IS_SET(MODE_MOUSEX10)) + return; + if (button == 64 || button == 65) + return; + } + } + + if (!IS_SET(MODE_MOUSEX10)) { + button += ((state & ShiftMask ) ? 4 : 0) + + ((state & Mod4Mask ) ? 8 : 0) + + ((state & ControlMask) ? 16 : 0); + } + + if (IS_SET(MODE_MOUSESGR)) { + len = snprintf(buf, sizeof(buf), "\033[<%d;%d;%d%c", + button, x+1, y+1, + e->xbutton.type == ButtonRelease ? 'm' : 'M'); + } else if (x < 223 && y < 223) { + len = snprintf(buf, sizeof(buf), "\033[M%c%c%c", + 32+button, 32+x+1, 32+y+1); + } else { + return; + } + + ttywrite(buf, len, 0); +} + +uint +buttonmask(uint button) +{ + return button == Button1 ? Button1Mask + : button == Button2 ? Button2Mask + : button == Button3 ? Button3Mask + : button == Button4 ? Button4Mask + : button == Button5 ? Button5Mask + : 0; +} + +int +mouseaction(XEvent *e, uint release) +{ + MouseShortcut *ms; + + /* ignore Buttonmask for Button - it's set on release */ + uint state = e->xbutton.state & ~buttonmask(e->xbutton.button); + + for (ms = mshortcuts; ms < mshortcuts + LEN(mshortcuts); ms++) { + if (ms->release == release && + ms->button == e->xbutton.button && + (match(ms->mod, state) || /* exact or forced */ + match(ms->mod, state & ~forcemousemod))) { + ms->func(&(ms->arg)); + return 1; + } + } + + return 0; +} + +void +bpress(XEvent *e) +{ + struct timespec now; + int snap; + + xshowpointer(); + if (!selectionmodeenabled) + return; + + if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { + mousereport(e); + return; + } + + if (mouseaction(e, 0)) + return; + + if (e->xbutton.button == Button1) { + /* + * If the user clicks below predefined timeouts specific + * snapping behaviour is exposed. + */ + clock_gettime(CLOCK_MONOTONIC, &now); + if (TIMEDIFF(now, xsel.tclick2) <= tripleclicktimeout) { + snap = SNAP_LINE; + } else if (TIMEDIFF(now, xsel.tclick1) <= doubleclicktimeout) { + snap = SNAP_WORD; + } else { + snap = 0; + } + xsel.tclick2 = xsel.tclick1; + xsel.tclick1 = now; + + selstart(evcol(e), evrow(e), snap); + } +} + +void +propnotify(XEvent *e) +{ + XPropertyEvent *xpev; + Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); + + xpev = &e->xproperty; + if (xpev->state == PropertyNewValue && + (xpev->atom == XA_PRIMARY || + xpev->atom == clipboard)) { + selnotify(e); + } +} + +void +selnotify(XEvent *e) +{ + ulong nitems, ofs, rem; + int format; + uchar *data, *last, *repl; + Atom type, incratom, property = None; + + incratom = XInternAtom(xw.dpy, "INCR", 0); + + ofs = 0; + if (e->type == SelectionNotify) + property = e->xselection.property; + else if (e->type == PropertyNotify) + property = e->xproperty.atom; + + if (property == None) + return; + + do { + if (XGetWindowProperty(xw.dpy, xw.win, property, ofs, + BUFSIZ/4, False, AnyPropertyType, + &type, &format, &nitems, &rem, + &data)) { + fprintf(stderr, "Clipboard allocation failed\n"); + return; + } + + if (e->type == PropertyNotify && nitems == 0 && rem == 0) { + /* + * If there is some PropertyNotify with no data, then + * this is the signal of the selection owner that all + * data has been transferred. We won't need to receive + * PropertyNotify events anymore. + */ + MODBIT(xw.attrs.event_mask, 0, PropertyChangeMask); + XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, + &xw.attrs); + } + + if (type == incratom) { + /* + * Activate the PropertyNotify events so we receive + * when the selection owner does send us the next + * chunk of data. + */ + MODBIT(xw.attrs.event_mask, 1, PropertyChangeMask); + XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, + &xw.attrs); + + /* + * Deleting the property is the transfer start signal. + */ + XDeleteProperty(xw.dpy, xw.win, (int)property); + continue; + } + + /* + * As seen in getsel: + * Line endings are inconsistent in the terminal and GUI world + * copy and pasting. When receiving some selection data, + * replace all '\n' with '\r'. + * FIXME: Fix the computer world. + */ + repl = data; + last = data + nitems * format / 8; + while ((repl = memchr(repl, '\n', last - repl))) { + *repl++ = '\r'; + } + + if (IS_SET(MODE_BRCKTPASTE) && ofs == 0) + ttywrite("\033[200~", 6, 0); + ttywrite((char *)data, nitems * format / 8, 1); + if (IS_SET(MODE_BRCKTPASTE) && rem == 0) + ttywrite("\033[201~", 6, 0); + XFree(data); + /* number of 32-bit chunks returned */ + ofs += nitems * format / 32; + } while (rem > 0); + + /* + * Deleting the property again tells the selection owner to send the + * next data chunk in the property. + */ + XDeleteProperty(xw.dpy, xw.win, (int)property); +} + +void +xclipcopy(void) +{ + clipcopy(NULL); +} + +void +selclear_(XEvent *e) +{ + selclear(); +} + +void +selrequest(XEvent *e) +{ + XSelectionRequestEvent *xsre; + XSelectionEvent xev; + Atom xa_targets, string, clipboard; + char *seltext; + + xsre = (XSelectionRequestEvent *) e; + xev.type = SelectionNotify; + xev.requestor = xsre->requestor; + xev.selection = xsre->selection; + xev.target = xsre->target; + xev.time = xsre->time; + if (xsre->property == None) + xsre->property = xsre->target; + + /* reject */ + xev.property = None; + + xa_targets = XInternAtom(xw.dpy, "TARGETS", 0); + if (xsre->target == xa_targets) { + /* respond with the supported type */ + string = xsel.xtarget; + XChangeProperty(xsre->display, xsre->requestor, xsre->property, + XA_ATOM, 32, PropModeReplace, + (uchar *) &string, 1); + xev.property = xsre->property; + } else if (xsre->target == xsel.xtarget || xsre->target == XA_STRING) { + /* + * xith XA_STRING non ascii characters may be incorrect in the + * requestor. It is not our problem, use utf8. + */ + clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); + if (xsre->selection == XA_PRIMARY) { + seltext = xsel.primary; + } else if (xsre->selection == clipboard) { + seltext = xsel.clipboard; + } else { + fprintf(stderr, + "Unhandled clipboard selection 0x%lx\n", + xsre->selection); + return; + } + if (seltext != NULL) { + XChangeProperty(xsre->display, xsre->requestor, + xsre->property, xsre->target, + 8, PropModeReplace, + (uchar *)seltext, strlen(seltext)); + xev.property = xsre->property; + } + } + + /* all done, send a notification to the listener */ + if (!XSendEvent(xsre->display, xsre->requestor, 1, 0, (XEvent *) &xev)) + fprintf(stderr, "Error sending SelectionNotify event\n"); +} + +void +setsel(char *str, Time t) +{ + if (!str) + return; + + free(xsel.primary); + xsel.primary = str; + + XSetSelectionOwner(xw.dpy, XA_PRIMARY, xw.win, t); + if (XGetSelectionOwner(xw.dpy, XA_PRIMARY) != xw.win) + selclear(); +} + +void +xsetsel(char *str) +{ + setsel(str, CurrentTime); +} + +void +brelease(XEvent *e) +{ + if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { + mousereport(e); + return; + } + + if (mouseaction(e, 1)) + return; + if (e->xbutton.button == Button1) + mousesel(e, 1); +} + +void +bmotion(XEvent *e) +{ + xshowpointer(); + if (IS_SET(MODE_MOUSE) && !(e->xbutton.state & forcemousemod)) { + mousereport(e); + return; + } + + mousesel(e, 0); +} + +void +cresize(int width, int height) +{ + int col, row; + + if (width != 0) + win.w = width; + if (height != 0) + win.h = height; + + col = (win.w - 2 * borderpx) / win.cw; + row = (win.h - 2 * borderpx) / win.ch; + col = MAX(1, col); + row = MAX(1, row); + + tresize(col, row); + xresize(col, row); + ttyresize(win.tw, win.th); +} + +void +xresize(int col, int row) +{ + win.tw = col * win.cw; + win.th = row * win.ch; + + xw_cells = xrealloc(xw_cells, (size_t)col * (size_t)row * sizeof(*xw_cells)); + xw_cells_cols = col; + xw_cells_rows = row; + xinvalidatecells(); + xw_buf_ready = 0; + xdirty_cnt = 0; + + XFreePixmap(xw.dpy, xw.buf); + xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, + DefaultDepth(xw.dpy, xw.scr)); + XftDrawChange(xw.draw, xw.buf); + xclear(0, 0, win.w, win.h); + + /* resize to new width */ + xw.specbuf = xrealloc(xw.specbuf, col * sizeof(GlyphFontSpec)); +} + +ushort +sixd_to_16bit(int x) +{ + return x == 0 ? 0 : 0x3737 + 0x2828 * x; +} + +int +xloadcolor(int i, const char *name, Color *ncolor) +{ + XRenderColor color = { .alpha = 0xffff }; + + if (!name) { + if (BETWEEN(i, 16, 255)) { /* 256 color */ + if (i < 6*6*6+16) { /* same colors as xterm */ + color.red = sixd_to_16bit( ((i-16)/36)%6 ); + color.green = sixd_to_16bit( ((i-16)/6) %6 ); + color.blue = sixd_to_16bit( ((i-16)/1) %6 ); + } else { /* greyscale */ + color.red = 0x0808 + 0x0a0a * (i - (6*6*6+16)); + color.green = color.blue = color.red; + } + return XftColorAllocValue(xw.dpy, xw.vis, + xw.cmap, &color, ncolor); + } else + name = colorname[i]; + } + + return XftColorAllocName(xw.dpy, xw.vis, xw.cmap, name, ncolor); +} + +void +xloadcols(void) +{ + int i; + static int loaded; + Color *cp; + + if (loaded) { + for (cp = dc.col; cp < &dc.col[dc.collen]; ++cp) + XftColorFree(xw.dpy, xw.vis, xw.cmap, cp); + } else { + dc.collen = MAX(LEN(colorname), 256); + dc.col = xmalloc(dc.collen * sizeof(Color)); + } + + for (i = 0; i < dc.collen; i++) + if (!xloadcolor(i, NULL, &dc.col[i])) { + if (colorname[i]) + die("could not allocate color '%s'\n", colorname[i]); + else + die("could not allocate color %d\n", i); + } + loaded = 1; + xinvalidatecells(); +} + +int +xsetcolorname(int x, const char *name) +{ + Color ncolor; + + if (!BETWEEN(x, 0, dc.collen)) + return 1; + + if (!xloadcolor(x, name, &ncolor)) + return 1; + + XftColorFree(xw.dpy, xw.vis, xw.cmap, &dc.col[x]); + dc.col[x] = ncolor; + xinvalidatecells(); + + return 0; +} + +/* + * Absolute coordinates. + */ +void +xclear(int x1, int y1, int x2, int y2) +{ + Color c; + c = dc.col[IS_SET(MODE_REVERSE)? defaultfg : defaultbg]; + if (invertcolors) { + c = invertedcolor(&c); + } + if (x2 > borderpx && x1 < borderpx + win.tw && + y2 > borderpx && y1 < borderpx + win.th) + xinvalidatecells(); + XftDrawRect(xw.draw, &c, x1, y1, x2-x1, y2-y1); + xmarkdirty(x1, y1, x2, y2); +} + +void +xhints(void) +{ + XClassHint class = {opt_name ? opt_name : "st-256color", + opt_class ? opt_class : "st-256color"}; + XWMHints wm = {.flags = InputHint, .input = 1}; + XSizeHints *sizeh; + + sizeh = XAllocSizeHints(); + + sizeh->flags = PSize | PResizeInc | PBaseSize | PMinSize; + sizeh->height = win.h; + sizeh->width = win.w; + sizeh->height_inc = win.ch; + sizeh->width_inc = win.cw; + sizeh->base_height = 2 * borderpx; + sizeh->base_width = 2 * borderpx; + sizeh->min_height = win.ch + 2 * borderpx; + sizeh->min_width = win.cw + 2 * borderpx; + if (xw.isfixed) { + sizeh->flags |= PMaxSize; + sizeh->min_width = sizeh->max_width = win.w; + sizeh->min_height = sizeh->max_height = win.h; + } + if (xw.gm & (XValue|YValue)) { + sizeh->flags |= USPosition | PWinGravity; + sizeh->x = xw.l; + sizeh->y = xw.t; + sizeh->win_gravity = xgeommasktogravity(xw.gm); + } + + XSetWMProperties(xw.dpy, xw.win, NULL, NULL, NULL, 0, sizeh, &wm, + &class); + XFree(sizeh); +} + +int +xgeommasktogravity(int mask) +{ + switch (mask & (XNegative|YNegative)) { + case 0: + return NorthWestGravity; + case XNegative: + return NorthEastGravity; + case YNegative: + return SouthWestGravity; + } + + return SouthEastGravity; +} + +int +xloadfont(Font *f, FcPattern *pattern) +{ + FcPattern *configured; + FcPattern *match; + FcResult result; + XGlyphInfo extents; + int wantattr, haveattr; + + /* + * Manually configure instead of calling XftMatchFont + * so that we can use the configured pattern for + * "missing glyph" lookups. + */ + configured = FcPatternDuplicate(pattern); + if (!configured) + return 1; + + FcConfigSubstitute(NULL, configured, FcMatchPattern); + XftDefaultSubstitute(xw.dpy, xw.scr, configured); + + match = FcFontMatch(NULL, configured, &result); + if (!match) { + FcPatternDestroy(configured); + return 1; + } + + if (!(f->match = XftFontOpenPattern(xw.dpy, match))) { + FcPatternDestroy(configured); + FcPatternDestroy(match); + return 1; + } + + if ((XftPatternGetInteger(pattern, "slant", 0, &wantattr) == + XftResultMatch)) { + /* + * Check if xft was unable to find a font with the appropriate + * slant but gave us one anyway. Try to mitigate. + */ + if ((XftPatternGetInteger(f->match->pattern, "slant", 0, + &haveattr) != XftResultMatch) || haveattr < wantattr) { + f->badslant = 1; + fputs("font slant does not match\n", stderr); + } + } + + if ((XftPatternGetInteger(pattern, "weight", 0, &wantattr) == + XftResultMatch)) { + if ((XftPatternGetInteger(f->match->pattern, "weight", 0, + &haveattr) != XftResultMatch) || haveattr != wantattr) { + f->badweight = 1; + fputs("font weight does not match\n", stderr); + } + } + + XftTextExtentsUtf8(xw.dpy, f->match, + (const FcChar8 *) ascii_printable, + strlen(ascii_printable), &extents); + + f->set = NULL; + f->pattern = configured; + + f->ascent = f->match->ascent; + f->descent = f->match->descent; + f->lbearing = 0; + f->rbearing = f->match->max_advance_width; + + f->height = f->ascent + f->descent; + f->width = DIVCEIL(extents.xOff, strlen(ascii_printable)); + + return 0; +} + +void +xloadfonts(char *fontstr, double fontsize) +{ + FcPattern *pattern; + double fontval; + + if (fontstr[0] == '-') + pattern = XftXlfdParse(fontstr, False, False); + else + pattern = FcNameParse((FcChar8 *)fontstr); + + if (!pattern) + die("can't open font %s\n", fontstr); + + if (fontsize > 1) { + FcPatternDel(pattern, FC_PIXEL_SIZE); + FcPatternDel(pattern, FC_SIZE); + FcPatternAddDouble(pattern, FC_PIXEL_SIZE, (double)fontsize); + usedfontsize = fontsize; + } else { + if (FcPatternGetDouble(pattern, FC_PIXEL_SIZE, 0, &fontval) == + FcResultMatch) { + usedfontsize = fontval; + } else if (FcPatternGetDouble(pattern, FC_SIZE, 0, &fontval) == + FcResultMatch) { + usedfontsize = -1; + } else { + /* + * Default font size is 12, if none given. This is to + * have a known usedfontsize value. + */ + FcPatternAddDouble(pattern, FC_PIXEL_SIZE, 12); + usedfontsize = 12; + } + defaultfontsize = usedfontsize; + } + + if (xloadfont(&dc.font, pattern)) + die("can't open font %s\n", fontstr); + + if (usedfontsize < 0) { + FcPatternGetDouble(dc.font.match->pattern, + FC_PIXEL_SIZE, 0, &fontval); + usedfontsize = fontval; + if (fontsize == 0) + defaultfontsize = fontval; + } + + /* Setting character width and height. */ + win.cw = ceilf(dc.font.width * cwscale); + win.ch = ceilf(dc.font.height * chscale); + + FcPatternDel(pattern, FC_SLANT); + FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ITALIC); + if (xloadfont(&dc.ifont, pattern)) + die("can't open font %s\n", fontstr); + + FcPatternDel(pattern, FC_WEIGHT); + FcPatternAddInteger(pattern, FC_WEIGHT, FC_WEIGHT_BOLD); + if (xloadfont(&dc.ibfont, pattern)) + die("can't open font %s\n", fontstr); + + FcPatternDel(pattern, FC_SLANT); + FcPatternAddInteger(pattern, FC_SLANT, FC_SLANT_ROMAN); + if (xloadfont(&dc.bfont, pattern)) + die("can't open font %s\n", fontstr); + + FcPatternDestroy(pattern); +} + +void +xunloadfont(Font *f) +{ + XftFontClose(xw.dpy, f->match); + FcPatternDestroy(f->pattern); + if (f->set) + FcFontSetDestroy(f->set); +} + +void +xunloadfonts(void) +{ + /* Clear HarfBuzz font cache. */ + hbunloadfonts(); + + /* Free the loaded fonts in the font cache. */ + while (frclen > 0) + XftFontClose(xw.dpy, frc[--frclen].font); + + xunloadfont(&dc.font); + xunloadfont(&dc.bfont); + xunloadfont(&dc.ifont); + xunloadfont(&dc.ibfont); +} + +int +ximopen(Display *dpy) +{ + XIMCallback imdestroy = { .client_data = NULL, .callback = ximdestroy }; + XICCallback icdestroy = { .client_data = NULL, .callback = xicdestroy }; + + xw.ime.xim = XOpenIM(xw.dpy, NULL, NULL, NULL); + if (xw.ime.xim == NULL) + return 0; + + if (XSetIMValues(xw.ime.xim, XNDestroyCallback, &imdestroy, NULL)) + fprintf(stderr, "XSetIMValues: " + "Could not set XNDestroyCallback.\n"); + + xw.ime.spotlist = XVaCreateNestedList(0, XNSpotLocation, &xw.ime.spot, + NULL); + + if (xw.ime.xic == NULL) { + xw.ime.xic = XCreateIC(xw.ime.xim, XNInputStyle, + XIMPreeditNothing | XIMStatusNothing, + XNClientWindow, xw.win, + XNFocusWindow, xw.win, + XNDestroyCallback, &icdestroy, + NULL); + } + if (xw.ime.xic == NULL) + fprintf(stderr, "XCreateIC: Could not create input context.\n"); + else if (win.mode & MODE_FOCUSED) + XSetICFocus(xw.ime.xic); + + return 1; +} + +void +ximinstantiate(Display *dpy, XPointer client, XPointer call) +{ + if (ximopen(dpy)) + XUnregisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, + ximinstantiate, NULL); +} + +void +ximdestroy(XIM xim, XPointer client, XPointer call) +{ + xw.ime.xim = NULL; + XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, + ximinstantiate, NULL); + XFree(xw.ime.spotlist); +} + +int +xicdestroy(XIC xim, XPointer client, XPointer call) +{ + xw.ime.xic = NULL; + return 1; +} + +void +xinit(int cols, int rows) +{ + XGCValues gcvalues; + Window parent; + pid_t thispid = getpid(); + + xw.scr = XDefaultScreen(xw.dpy); + xw.vis = XDefaultVisual(xw.dpy, xw.scr); + + /* font */ + if (!FcInit()) + die("could not init fontconfig.\n"); + + usedfont = (opt_font == NULL)? font : opt_font; + xloadfonts(usedfont, 0); + + /* colors */ + xw.cmap = XDefaultColormap(xw.dpy, xw.scr); + xloadcols(); + + /* adjust fixed window geometry */ + win.w = 2 * borderpx + cols * win.cw; + win.h = 2 * borderpx + rows * win.ch; + if (xw.gm & XNegative) + xw.l += DisplayWidth(xw.dpy, xw.scr) - win.w - 2; + if (xw.gm & YNegative) + xw.t += DisplayHeight(xw.dpy, xw.scr) - win.h - 2; + + /* Events */ + xw.attrs.background_pixel = dc.col[defaultbg].pixel; + xw.attrs.border_pixel = dc.col[defaultbg].pixel; + xw.attrs.bit_gravity = NorthWestGravity; + xw.attrs.event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask + | ExposureMask | VisibilityChangeMask | StructureNotifyMask + | ButtonMotionMask | ButtonPressMask | ButtonReleaseMask; + xw.attrs.colormap = xw.cmap; + + if (!(opt_embed && (parent = strtol(opt_embed, NULL, 0)))) + parent = XRootWindow(xw.dpy, xw.scr); + xw.win = XCreateWindow(xw.dpy, parent, xw.l, xw.t, + win.w, win.h, 0, XDefaultDepth(xw.dpy, xw.scr), InputOutput, + xw.vis, CWBackPixel | CWBorderPixel | CWBitGravity + | CWEventMask | CWColormap, &xw.attrs); + + memset(&gcvalues, 0, sizeof(gcvalues)); + gcvalues.graphics_exposures = False; + dc.gc = XCreateGC(xw.dpy, parent, GCGraphicsExposures, + &gcvalues); + xw.buf = XCreatePixmap(xw.dpy, xw.win, win.w, win.h, + DefaultDepth(xw.dpy, xw.scr)); + XSetForeground(xw.dpy, dc.gc, dc.col[defaultbg].pixel); + XFillRectangle(xw.dpy, xw.buf, dc.gc, 0, 0, win.w, win.h); + xw_cells = xmalloc((size_t)cols * (size_t)rows * sizeof(*xw_cells)); + xw_cells_cols = cols; + xw_cells_rows = rows; + xinvalidatecells(); + xw_buf_ready = 0; + xmarkdirty(0, 0, win.w, win.h); + + /* font spec buffer */ + xw.specbuf = xmalloc(cols * sizeof(GlyphFontSpec)); + + /* Xft rendering context */ + xw.draw = XftDrawCreate(xw.dpy, xw.buf, xw.vis, xw.cmap); + + /* input methods */ + if (!ximopen(xw.dpy)) { + XRegisterIMInstantiateCallback(xw.dpy, NULL, NULL, NULL, + ximinstantiate, NULL); + } + + xw.xembed = XInternAtom(xw.dpy, "_XEMBED", False); + xw.wmdeletewin = XInternAtom(xw.dpy, "WM_DELETE_WINDOW", False); + xw.netwmname = XInternAtom(xw.dpy, "_NET_WM_NAME", False); + XSetWMProtocols(xw.dpy, xw.win, &xw.wmdeletewin, 1); + + xw.netwmpid = XInternAtom(xw.dpy, "_NET_WM_PID", False); + XChangeProperty(xw.dpy, xw.win, xw.netwmpid, XA_CARDINAL, 32, + PropModeReplace, (uchar *)&thispid, 1); + + xw.selectionmode = XInternAtom(xw.dpy, "_ST_SELMODE", False); + updateselectionmodeatom(); + + /* pointer cursor setup and blank cursor for hide-while-typing */ + { + int ev_base = 0, err_base = 0; + char blank_bits[1] = {0}; + Pixmap blank = XCreateBitmapFromData(xw.dpy, xw.win, blank_bits, 1, 1); + XColor black = {0}; + XColor xmousefg = {0}, xmousebg = {0}; + + xw.xfixes_ok = XFixesQueryExtension(xw.dpy, &ev_base, &err_base) ? 1 : 0; + xw.xi_opcode = -1; + if (XQueryExtension(xw.dpy, "XInputExtension", &xw.xi_opcode, &ev_base, &err_base)) { + int maj = 2, min = 2; + if (XIQueryVersion(xw.dpy, &maj, &min) != Success) + xw.xi_opcode = -1; + } else { + xw.xi_opcode = -1; + } + + xw.vpointer = XCreateFontCursor(xw.dpy, mouseshape); + xmousefg.red = dc.col[mousefg].color.red; + xmousefg.green = dc.col[mousefg].color.green; + xmousefg.blue = dc.col[mousefg].color.blue; + xmousebg.red = dc.col[mousebg].color.red; + xmousebg.green = dc.col[mousebg].color.green; + xmousebg.blue = dc.col[mousebg].color.blue; + XRecolorCursor(xw.dpy, xw.vpointer, &xmousefg, &xmousebg); + xw.bpointer = XCreatePixmapCursor(xw.dpy, blank, blank, &black, &black, 0, 0); + XFreePixmap(xw.dpy, blank); + xw.pointerisvisible = 1; + XDefineCursor(xw.dpy, xw.win, xw.vpointer); + } + + win.mode = MODE_NUMLOCK; + resettitle(); + xhints(); + XMapWindow(xw.dpy, xw.win); + XSync(xw.dpy, False); + + clock_gettime(CLOCK_MONOTONIC, &xsel.tclick1); + clock_gettime(CLOCK_MONOTONIC, &xsel.tclick2); + xsel.primary = NULL; + xsel.clipboard = NULL; + xsel.xtarget = XInternAtom(xw.dpy, "UTF8_STRING", 0); + if (xsel.xtarget == None) + xsel.xtarget = XA_STRING; +} + +int +xmakeglyphfontspecs(XftGlyphFontSpec *specs, const Glyph *glyphs, int len, int x, int y) +{ + float winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, xp, yp; + ushort mode, prevmode = USHRT_MAX; + Font *font = &dc.font; + int frcflags = FRC_NORMAL; + float runewidth = win.cw; + Rune rune; + FT_UInt glyphidx; + FcResult fcres; + FcPattern *fcpattern, *fontpattern; + FcFontSet *fcsets[] = { NULL }; + FcCharSet *fccharset; + int i, f, numspecs = 0; + + for (i = 0, xp = winx, yp = winy + font->ascent; i < len; ++i) { + /* Fetch rune and mode for current glyph. */ + rune = glyphs[i].u; + mode = glyphs[i].mode; + + /* Skip dummy wide-character spacing. */ + if (mode == ATTR_WDUMMY) + continue; + + /* Determine font for glyph if different from previous glyph. */ + if (prevmode != mode) { + prevmode = mode; + font = &dc.font; + frcflags = FRC_NORMAL; + runewidth = win.cw * ((mode & ATTR_WIDE) ? 2.0f : 1.0f); + if ((mode & ATTR_ITALIC) && (mode & ATTR_BOLD)) { + font = &dc.ibfont; + frcflags = FRC_ITALICBOLD; + } else if (mode & ATTR_ITALIC) { + font = &dc.ifont; + frcflags = FRC_ITALIC; + } else if (mode & ATTR_BOLD) { + font = &dc.bfont; + frcflags = FRC_BOLD; + } + yp = winy + font->ascent; + } + + /* Lookup character index with default font. */ + glyphidx = XftCharIndex(xw.dpy, font->match, rune); + if (glyphidx) { + specs[numspecs].font = font->match; + specs[numspecs].glyph = glyphidx; + specs[numspecs].x = (short)xp; + specs[numspecs].y = (short)yp; + xp += runewidth; + numspecs++; + continue; + } + + /* Fallback on font cache, search the font cache for match. */ + for (f = 0; f < frclen; f++) { + glyphidx = XftCharIndex(xw.dpy, frc[f].font, rune); + /* Everything correct. */ + if (glyphidx && frc[f].flags == frcflags) + break; + /* We got a default font for a not found glyph. */ + if (!glyphidx && frc[f].flags == frcflags + && frc[f].unicodep == rune) { + break; + } + } + + /* Nothing was found. Use fontconfig to find matching font. */ + if (f >= frclen) { + if (!font->set) + font->set = FcFontSort(0, font->pattern, + 1, 0, &fcres); + fcsets[0] = font->set; + + /* + * Nothing was found in the cache. Now use + * some dozen of Fontconfig calls to get the + * font for one single character. + * + * Xft and fontconfig are design failures. + */ + fcpattern = FcPatternDuplicate(font->pattern); + fccharset = FcCharSetCreate(); + + FcCharSetAddChar(fccharset, rune); + FcPatternAddCharSet(fcpattern, FC_CHARSET, + fccharset); + FcPatternAddBool(fcpattern, FC_SCALABLE, 1); + + FcConfigSubstitute(0, fcpattern, + FcMatchPattern); + FcDefaultSubstitute(fcpattern); + + fontpattern = FcFontSetMatch(0, fcsets, 1, + fcpattern, &fcres); + + /* Allocate memory for the new cache entry. */ + if (frclen >= frccap) { + frccap += 16; + frc = xrealloc(frc, frccap * sizeof(Fontcache)); + } + + frc[frclen].font = XftFontOpenPattern(xw.dpy, + fontpattern); + if (!frc[frclen].font) + die("XftFontOpenPattern failed seeking fallback font: %s\n", + strerror(errno)); + frc[frclen].flags = frcflags; + frc[frclen].unicodep = rune; + + glyphidx = XftCharIndex(xw.dpy, frc[frclen].font, rune); + + f = frclen; + frclen++; + + FcPatternDestroy(fcpattern); + FcCharSetDestroy(fccharset); + } + + specs[numspecs].font = frc[f].font; + specs[numspecs].glyph = glyphidx; + specs[numspecs].x = (short)xp; + specs[numspecs].y = (short)yp; + xp += runewidth; + numspecs++; + } + + /* HarfBuzz font shaping for programming ligatures (Fira Code) */ + hbtransform(specs, glyphs, len, x, y); + + return numspecs; +} + +void +xdrawglyphfontspecs(const XftGlyphFontSpec *specs, Glyph base, int len, int x, int y) +{ + int charlen = len * ((base.mode & ATTR_WIDE) ? 2 : 1); + int winx = borderpx + x * win.cw, winy = borderpx + y * win.ch, + width = charlen * win.cw; + Color *fg, *bg, *temp, revfg, revbg, truefg, truebg; + XRenderColor colfg, colbg; + XRectangle r; + + /* Fallback on color display for attributes not supported by the font */ + if (base.mode & ATTR_ITALIC && base.mode & ATTR_BOLD) { + if (dc.ibfont.badslant || dc.ibfont.badweight) + base.fg = defaultattr; + } else if ((base.mode & ATTR_ITALIC && dc.ifont.badslant) || + (base.mode & ATTR_BOLD && dc.bfont.badweight)) { + base.fg = defaultattr; + } + + if (IS_TRUECOL(base.fg)) { + colfg.alpha = 0xffff; + colfg.red = TRUERED(base.fg); + colfg.green = TRUEGREEN(base.fg); + colfg.blue = TRUEBLUE(base.fg); + XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &truefg); + fg = &truefg; + } else { + fg = &dc.col[base.fg]; + } + + if (IS_TRUECOL(base.bg)) { + colbg.alpha = 0xffff; + colbg.green = TRUEGREEN(base.bg); + colbg.red = TRUERED(base.bg); + colbg.blue = TRUEBLUE(base.bg); + XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, &truebg); + bg = &truebg; + } else { + bg = &dc.col[base.bg]; + } + + /* Change basic system colors [0-7] to bright system colors [8-15] */ + if ((base.mode & ATTR_BOLD_FAINT) == ATTR_BOLD && BETWEEN(base.fg, 0, 7)) + fg = &dc.col[base.fg + 8]; + + if (IS_SET(MODE_REVERSE)) { + if (fg == &dc.col[defaultfg]) { + fg = &dc.col[defaultbg]; + } else { + colfg.red = ~fg->color.red; + colfg.green = ~fg->color.green; + colfg.blue = ~fg->color.blue; + colfg.alpha = fg->color.alpha; + XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, + &revfg); + fg = &revfg; + } + + if (bg == &dc.col[defaultbg]) { + bg = &dc.col[defaultfg]; + } else { + colbg.red = ~bg->color.red; + colbg.green = ~bg->color.green; + colbg.blue = ~bg->color.blue; + colbg.alpha = bg->color.alpha; + XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colbg, + &revbg); + bg = &revbg; + } + } + + if ((base.mode & ATTR_BOLD_FAINT) == ATTR_FAINT) { + colfg.red = fg->color.red / 2; + colfg.green = fg->color.green / 2; + colfg.blue = fg->color.blue / 2; + colfg.alpha = fg->color.alpha; + XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, &colfg, &revfg); + fg = &revfg; + } + + if (base.mode & ATTR_REVERSE) { + temp = fg; + fg = bg; + bg = temp; + } + + if (base.mode & ATTR_BLINK && win.mode & MODE_BLINK) + fg = bg; + + if (base.mode & ATTR_INVISIBLE) + fg = bg; + + if (invertcolors) { + revfg = invertedcolor(fg); + revbg = invertedcolor(bg); + fg = &revfg; + bg = &revbg; + } + + /* Intelligent cleaning up of the borders. */ + if (x == 0) { + xclear(0, (y == 0)? 0 : winy, borderpx, + winy + win.ch + + ((winy + win.ch >= borderpx + win.th)? win.h : 0)); + } + if (winx + width >= borderpx + win.tw) { + xclear(winx + width, (y == 0)? 0 : winy, win.w, + ((winy + win.ch >= borderpx + win.th)? win.h : (winy + win.ch))); + } + if (y == 0) + xclear(winx, 0, winx + width, borderpx); + if (winy + win.ch >= borderpx + win.th) + xclear(winx, winy + win.ch, winx + width, win.h); + + /* Clean up the region we want to draw to. */ + XftDrawRect(xw.draw, bg, winx, winy, width, win.ch); + + /* Set the clip region because Xft is sometimes dirty. */ + r.x = 0; + r.y = 0; + r.height = win.ch; + r.width = width; + XftDrawSetClipRectangles(xw.draw, winx, winy, &r, 1); + + /* Render the glyphs. */ + XftDrawGlyphFontSpec(xw.draw, fg, specs, len); + + /* Render underline and strikethrough. */ + if (base.mode & ATTR_UNDERLINE) { + XftDrawRect(xw.draw, fg, winx, winy + dc.font.ascent + 1, + width, 1); + } + + if (base.mode & ATTR_STRUCK) { + XftDrawRect(xw.draw, fg, winx, winy + 2 * dc.font.ascent / 3, + width, 1); + } + + /* Reset clip to none. */ + XftDrawSetClip(xw.draw, 0); + xmarkdirty(winx, winy, winx + width, winy + win.ch); +} + +void +xdrawglyph(Glyph g, int x, int y) +{ + int numspecs; + XftGlyphFontSpec spec; + + numspecs = xmakeglyphfontspecs(&spec, &g, 1, x, y); + xdrawglyphfontspecs(&spec, g, numspecs, x, y); +} + +void +xdrawcursor(int cx, int cy, Glyph g, int ox, int oy, Glyph og) +{ + Color drawcol; + XRenderColor colbg; + + /* remove the old cursor */ + if (xlast_cur_drawn || !IS_SET(MODE_HIDE)) { + if (selected(ox, oy)) + og.mode ^= ATTR_REVERSE; + xinvalidatecellrange(oy, ox, ox + ((og.mode & ATTR_WIDE) ? 2 : 1)); + xdrawglyph(og, ox, oy); + xlast_cur_drawn = 0; + } + + if (IS_SET(MODE_HIDE)) + return; + + /* + * Select the right color for the right mode. + */ + g.mode &= ATTR_BOLD|ATTR_ITALIC|ATTR_UNDERLINE|ATTR_STRUCK|ATTR_WIDE; + + if (IS_SET(MODE_REVERSE)) { + g.mode |= ATTR_REVERSE; + g.bg = defaultfg; + if (selected(cx, cy)) { + drawcol = dc.col[defaultcs]; + g.fg = defaultrcs; + } else { + drawcol = dc.col[defaultrcs]; + g.fg = defaultcs; + } + } else { + if (selected(cx, cy)) { + g.fg = defaultfg; + g.bg = defaultrcs; + } else { + g.bg = g.fg; + g.fg = defaultbg; + } + + if (IS_TRUECOL(g.bg)) { + colbg.alpha = 0xffff; + colbg.red = TRUERED(g.bg); + colbg.green = TRUEGREEN(g.bg); + colbg.blue = TRUEBLUE(g.bg); + XftColorAllocValue(xw.dpy, xw.vis, xw.cmap, + &colbg, &drawcol); + } else { + drawcol = dc.col[g.bg]; + } + } + + /* draw the new one */ + if (IS_SET(MODE_FOCUSED)) { + switch (win.cursor) { + case 7: /* st extension */ + g.u = 0x2603; /* snowman (U+2603) */ + /* FALLTHROUGH */ + case 0: /* Blinking Block */ + case 1: /* Blinking Block (Default) */ + case 2: /* Steady Block */ + xdrawglyph(g, cx, cy); + break; + case 3: /* Blinking Underline */ + case 4: /* Steady Underline */ + XftDrawRect(xw.draw, &drawcol, + borderpx + cx * win.cw, + borderpx + (cy + 1) * win.ch - \ + cursorthickness, + win.cw, cursorthickness); + xmarkdirty(borderpx + cx * win.cw, borderpx + cy * win.ch, + borderpx + (cx + 1) * win.cw, borderpx + (cy + 1) * win.ch); + break; + case 5: /* Blinking bar */ + case 6: /* Steady bar */ + XftDrawRect(xw.draw, &drawcol, + borderpx + cx * win.cw, + borderpx + cy * win.ch, + cursorthickness, win.ch); + xmarkdirty(borderpx + cx * win.cw, borderpx + cy * win.ch, + borderpx + (cx + 1) * win.cw, borderpx + (cy + 1) * win.ch); + break; + } + } else { + XftDrawRect(xw.draw, &drawcol, + borderpx + cx * win.cw, + borderpx + cy * win.ch, + win.cw - 1, 1); + XftDrawRect(xw.draw, &drawcol, + borderpx + cx * win.cw, + borderpx + cy * win.ch, + 1, win.ch - 1); + XftDrawRect(xw.draw, &drawcol, + borderpx + (cx + 1) * win.cw - 1, + borderpx + cy * win.ch, + 1, win.ch - 1); + XftDrawRect(xw.draw, &drawcol, + borderpx + cx * win.cw, + borderpx + (cy + 1) * win.ch - 1, + win.cw, 1); + xmarkdirty(borderpx + cx * win.cw, borderpx + cy * win.ch, + borderpx + (cx + 1) * win.cw, borderpx + (cy + 1) * win.ch); + } + xinvalidatecellrange(cy, cx, cx + ((g.mode & ATTR_WIDE) ? 2 : 1)); + xlast_cur_drawn = 1; +} + +void +xsetenv(void) +{ + char buf[sizeof(long) * 8 + 1]; + + snprintf(buf, sizeof(buf), "%lu", xw.win); + setenv("WINDOWID", buf, 1); +} + +void +xsettitle(char *p) +{ + XTextProperty prop; + DEFAULT(p, opt_title); + + Xutf8TextListToTextProperty(xw.dpy, &p, 1, XUTF8StringStyle, + &prop); + XSetWMName(xw.dpy, xw.win, &prop); + XSetTextProperty(xw.dpy, xw.win, &prop, xw.netwmname); + XFree(prop.value); +} + +int +xstartdraw(void) +{ + return IS_SET(MODE_VISIBLE); +} + +void +xdrawline(Line line, int x1, int y1, int x2) +{ + int i, x, ox, numspecs; + Glyph base, new; + XftGlyphFontSpec *specs = xw.specbuf; + + numspecs = xmakeglyphfontspecs(specs, &line[x1], x2 - x1, x1, y1); + if (xw_cells && y1 >= 0 && y1 < xw_cells_rows && x1 >= 0 && x2 <= xw_cells_cols && + x2 > x1 && (x2 - x1) <= 512) { + int n = x2 - x1; + uchar draw_col[512]; + uchar tok_col[512]; + int sidx = 0; + int any_dirty = 0; + + for (int k = 0; k < n; k++) { + Glyph g = line[x1 + k]; + if (g.mode != ATTR_WDUMMY && selected(x1 + k, y1)) + g.mode ^= ATTR_REVERSE; + ushort eff_mode = g.mode; + if ((eff_mode & ATTR_BLINK) && (win.mode & MODE_BLINK)) + eff_mode |= ATTR_INVISIBLE; + uchar cur_ns = (g.mode == ATTR_WDUMMY) || (g.u != ' ' && g.u != 0); + XRenderedCell *rc = &xw_cells[y1 * xw_cells_cols + x1 + k]; + tok_col[k] = cur_ns || (rc->valid && rc->nonspace); + + int matches = 0; + if (g.mode == ATTR_WDUMMY) { + matches = rc->valid && rc->mode == ATTR_WDUMMY; + } else if (sidx < numspecs) { + matches = rc->valid && + rc->font == specs[sidx].font && + rc->glyph == specs[sidx].glyph && + rc->fg == g.fg && + rc->bg == g.bg && + rc->mode == eff_mode; + sidx++; + } + draw_col[k] = !matches; + if (!matches) + any_dirty = 1; + } + if (!any_dirty) + return; + + for (int k = 0; k < n - 1; k++) { + if (draw_col[k] && + (line[x1 + k + 1].mode == ATTR_WDUMMY || + (tok_col[k] && tok_col[k + 1]))) + draw_col[k + 1] = 1; + } + for (int k = n - 1; k > 0; k--) { + if (draw_col[k] && + (line[x1 + k].mode == ATTR_WDUMMY || + (tok_col[k] && tok_col[k - 1]))) + draw_col[k - 1] = 1; + } + + i = ox = 0; + for (x = x1; x < x2; x++) { + new = line[x]; + if (new.mode == ATTR_WDUMMY) { + if (draw_col[x - x1]) { + xw_cells[y1 * xw_cells_cols + x] = (XRenderedCell){ + .mode = ATTR_WDUMMY, + .nonspace = 1, + .valid = 1, + }; + } + continue; + } + if (i >= numspecs) + break; + if (!draw_col[x - x1]) { + if (i > 0) { + xdrawglyphfontspecs(specs, base, i, ox, y1); + specs += i; + numspecs -= i; + i = 0; + } + specs++; + numspecs--; + continue; + } + if (selected(x, y1)) + new.mode ^= ATTR_REVERSE; + if (i > 0 && ATTRCMP(base, new)) { + xdrawglyphfontspecs(specs, base, i, ox, y1); + specs += i; + numspecs -= i; + i = 0; + } + if (i == 0) { + ox = x; + base = new; + } + { + ushort eff_mode = new.mode; + if ((eff_mode & ATTR_BLINK) && (win.mode & MODE_BLINK)) + eff_mode |= ATTR_INVISIBLE; + xw_cells[y1 * xw_cells_cols + x] = (XRenderedCell){ + .font = specs[i].font, + .glyph = specs[i].glyph, + .fg = new.fg, + .bg = new.bg, + .mode = eff_mode, + .nonspace = (new.u != ' ' && new.u != 0), + .valid = 1, + }; + } + i++; + } + if (i > 0) + xdrawglyphfontspecs(specs, base, i, ox, y1); + return; + } + + i = ox = 0; + for (x = x1; x < x2 && i < numspecs; x++) { + new = line[x]; + if (new.mode == ATTR_WDUMMY) + continue; + if (selected(x, y1)) + new.mode ^= ATTR_REVERSE; + if (i > 0 && ATTRCMP(base, new)) { + xdrawglyphfontspecs(specs, base, i, ox, y1); + specs += i; + numspecs -= i; + i = 0; + } + if (i == 0) { + ox = x; + base = new; + } + i++; + } + if (i > 0) + xdrawglyphfontspecs(specs, base, i, ox, y1); +} + +void +xfinishdraw(void) +{ + int i; + + for (i = 0; i < xdirty_cnt; i++) { + XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, + xdirty[i].x1, xdirty[i].y1, + xdirty[i].x2 - xdirty[i].x1, + xdirty[i].y2 - xdirty[i].y1, + xdirty[i].x1, xdirty[i].y1); + } + xdirty_cnt = 0; + xw_buf_ready = 1; + XSetForeground(xw.dpy, dc.gc, + dc.col[IS_SET(MODE_REVERSE)? + defaultfg : defaultbg].pixel); +} + +void +xximspot(int x, int y) +{ + (void)x; + (void)y; +} + +void +expose(XEvent *ev) +{ + XExposeEvent *e = &ev->xexpose; + + if (xw_buf_ready && xw.buf != None) { + if (e->width > 0 && e->height > 0) + XCopyArea(xw.dpy, xw.buf, xw.win, dc.gc, + e->x, e->y, e->width, e->height, e->x, e->y); + return; + } + xinvalidatecells(); + redraw(); +} + +void +visibility(XEvent *ev) +{ + XVisibilityEvent *e = &ev->xvisibility; + + MODBIT(win.mode, e->state != VisibilityFullyObscured, MODE_VISIBLE); +} + +void +unmap(XEvent *ev) +{ + xshowpointer(); + win.mode &= ~MODE_VISIBLE; +} + +void +st_xi_raw_select(int enable) +{ + unsigned char mask[XIMaskLen(XI_LASTEVENT)]; + XIEventMask evmask; + + if (xw.xi_opcode < 0) + return; + memset(mask, 0, sizeof(mask)); + if (enable) { + XISetMask(mask, XI_RawMotion); + XISetMask(mask, XI_RawButtonPress); + XISetMask(mask, XI_RawTouchBegin); + } + evmask.deviceid = XIAllMasterDevices; + evmask.mask_len = (int)sizeof(mask); + evmask.mask = mask; + XISelectEvents(xw.dpy, XRootWindow(xw.dpy, xw.scr), &evmask, 1); +} + +void +xhidepointer(void) +{ + if (!xw.pointerisvisible) + return; + XDefineCursor(xw.dpy, xw.win, xw.bpointer); + if (xw.xfixes_ok) + XFixesHideCursor(xw.dpy, XRootWindow(xw.dpy, xw.scr)); + st_xi_raw_select(1); + xsetpointermotion(1); + xw.pointerisvisible = 0; + XFlush(xw.dpy); +} + +void +xshowpointer(void) +{ + if (xw.pointerisvisible) + return; + xw.pointerisvisible = 1; + st_xi_raw_select(0); + if (xw.xfixes_ok) + XFixesShowCursor(xw.dpy, XRootWindow(xw.dpy, xw.scr)); + XDefineCursor(xw.dpy, xw.win, xw.vpointer); + if (!IS_SET(MODE_MOUSEMOTION) && !IS_SET(MODE_MOUSEMANY)) + xsetpointermotion(0); + XFlush(xw.dpy); +} + +void +xsetpointermotion(int set) +{ + if (!set && !xw.pointerisvisible) + return; + MODBIT(xw.attrs.event_mask, set, PointerMotionMask); + XChangeWindowAttributes(xw.dpy, xw.win, CWEventMask, &xw.attrs); +} + +void +xsetmode(int set, unsigned int flags) +{ + int mode = win.mode; + MODBIT(win.mode, set, flags); + if ((win.mode & MODE_REVERSE) != (mode & MODE_REVERSE)) { + xinvalidatecells(); + redraw(); + } +} + +int +xsetcursor(int cursor) +{ + if (!BETWEEN(cursor, 0, 7)) /* 7: st extension */ + return 1; + win.cursor = cursor; + return 0; +} + +void +xseturgency(int add) +{ + XWMHints *h = XGetWMHints(xw.dpy, xw.win); + + MODBIT(h->flags, add, XUrgencyHint); + XSetWMHints(xw.dpy, xw.win, h); + XFree(h); +} + +void +xbell(void) +{ + if (!(IS_SET(MODE_FOCUSED))) + xseturgency(1); + if (bellvolume) + XkbBell(xw.dpy, xw.win, bellvolume, (Atom)NULL); +} + +void +focus(XEvent *ev) +{ + XFocusChangeEvent *e = &ev->xfocus; + + if (ev->type == FocusIn) { + if (xw.ime.xic) + XSetICFocus(xw.ime.xic); + if (e->mode == NotifyGrab) + return; + win.mode |= MODE_FOCUSED; + xseturgency(0); + if (!IS_SET(MODE_HIDE)) + xlast_cur_drawn = 1; + if (IS_SET(MODE_FOCUS)) + ttywrite("\033[I", 3, 0); + redraw(); + } else { + xshowpointer(); + if (xw.ime.xic) + XUnsetICFocus(xw.ime.xic); + if (e->mode == NotifyGrab) + return; + win.mode &= ~MODE_FOCUSED; + if (!IS_SET(MODE_HIDE)) + xlast_cur_drawn = 1; + if (IS_SET(MODE_FOCUS)) + ttywrite("\033[O", 3, 0); + redraw(); + } +} + +int +match(uint mask, uint state) +{ + return mask == XK_ANY_MOD || mask == (state & ~ignoremod); +} + +char* +kmap(KeySym k, uint state) +{ + Key *kp; + int i; + + /* Check for mapped keys out of X11 function keys. */ + for (i = 0; i < LEN(mappedkeys); i++) { + if (mappedkeys[i] == k) + break; + } + if (i == LEN(mappedkeys)) { + if ((k & 0xFFFF) < 0xFD00) + return NULL; + } + + for (kp = key; kp < key + LEN(key); kp++) { + if (kp->k != k) + continue; + + if (!match(kp->mask, state)) + continue; + + if (IS_SET(MODE_APPKEYPAD) ? kp->appkey < 0 : kp->appkey > 0) + continue; + if (IS_SET(MODE_NUMLOCK) && kp->appkey == 2) + continue; + + if (IS_SET(MODE_APPCURSOR) ? kp->appcursor < 0 : kp->appcursor > 0) + continue; + + return kp->s; + } + + return NULL; +} + +void +kpress(XEvent *ev) +{ + XKeyEvent *e = &ev->xkey; + KeySym ksym; + char buf[64], *customkey; + int len; + Rune c; + Status status; + Shortcut *bp; + + if (IS_SET(MODE_KBDLOCK)) + return; + + ksym = NoSymbol; + if (xw.ime.xic) { + len = Xutf8LookupString(xw.ime.xic, e, buf, sizeof buf, &ksym, &status); + if (status == XLookupNone) + return; + if (status == XLookupChars) { + xhidepointer(); + ttywrite(buf, len, 1); + return; + } + } else { + len = XLookupString(e, buf, sizeof buf, &ksym, NULL); + } + if (!IsModifierKey(ksym)) + xhidepointer(); + /* 1. shortcuts */ + for (bp = shortcuts; bp < shortcuts + LEN(shortcuts); bp++) { + if (ksym == bp->keysym && match(bp->mod, e->state)) { + bp->func(&(bp->arg)); + return; + } + } + + /* 2. custom keys from config.h */ + if ((customkey = kmap(ksym, e->state))) { + ttywrite(customkey, strlen(customkey), 1); + return; + } + + /* 3. composed string from input method */ + if (len == 0) + return; + if (len == 1 && e->state & Mod1Mask) { + if (IS_SET(MODE_8BIT)) { + if (*buf < 0177) { + c = *buf | 0x80; + len = utf8encode(c, buf); + } + } else { + buf[1] = buf[0]; + buf[0] = '\033'; + len = 2; + } + } + ttywrite(buf, len, 1); +} + +void +cmessage(XEvent *e) +{ + /* + * See xembed specs + * http://standards.freedesktop.org/xembed-spec/xembed-spec-latest.html + */ + if (e->xclient.message_type == xw.xembed && e->xclient.format == 32) { + if (e->xclient.data.l[1] == XEMBED_FOCUS_IN) { + win.mode |= MODE_FOCUSED; + xseturgency(0); + } else if (e->xclient.data.l[1] == XEMBED_FOCUS_OUT) { + win.mode &= ~MODE_FOCUSED; + } + } else if (e->xclient.data.l[0] == xw.wmdeletewin) { + ttyhangup(); + exit(0); + } +} + +void +updateselectionmodeatom() { + XChangeProperty(xw.dpy, xw.win, xw.selectionmode, XA_CARDINAL, 32, + PropModeReplace, (uchar *)&selectionmodeenabled, 1); +} + +void +resize(XEvent *e) +{ + if (e->xconfigure.width == win.w && e->xconfigure.height == win.h) + return; + + cresize(e->xconfigure.width, e->xconfigure.height); +} + +static volatile sig_atomic_t st_reload_requested = 0; +static char st_theme_font[256] = ""; +static char st_theme_bg[32] = ""; +static char st_theme_fg[32] = ""; +static char st_theme_cs[32] = ""; + +static void +st_sigusr1(int unused) +{ + (void)unused; + st_reload_requested = 1; +} + +void config_init(void); + +void +run(void) +{ + XEvent ev; + int w = win.w, h = win.h; + fd_set rfd; + int xfd = XConnectionNumber(xw.dpy), ttyfd, xev, drawing; + struct timespec seltv, *tv, now, lastblink, trigger; + double timeout; + + /* Waiting for window mapping */ + do { + XNextEvent(xw.dpy, &ev); + /* + * This XFilterEvent call is required because of XOpenIM. It + * does filter out the key event and some client message for + * the input method too. + */ + if (XFilterEvent(&ev, None)) + continue; + if (ev.type == ConfigureNotify) { + w = ev.xconfigure.width; + h = ev.xconfigure.height; + } else if (ev.type == FocusIn || ev.type == FocusOut) { + focus(&ev); + } + } while (ev.type != MapNotify); + + ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd); + cresize(w, h); + signal(SIGUSR1, st_sigusr1); + + for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) { + if (st_reload_requested) { + st_reload_requested = 0; + config_init(); + xloadcols(); + xunloadfonts(); + hbunloadfonts(); + xloadfonts(opt_font ? opt_font : font, 0); + cresize(win.w, win.h); + redraw(); + XFlush(xw.dpy); + } + FD_ZERO(&rfd); + FD_SET(ttyfd, &rfd); + FD_SET(xfd, &rfd); + + if (XPending(xw.dpy)) + timeout = 0; /* existing events might not set xfd */ + + seltv.tv_sec = timeout / 1E3; + seltv.tv_nsec = 1E6 * (timeout - 1E3 * seltv.tv_sec); + tv = timeout >= 0 ? &seltv : NULL; + + if (pselect(MAX(xfd, ttyfd)+1, &rfd, NULL, NULL, tv, NULL) < 0) { + if (errno == EINTR) + continue; + die("select failed: %s\n", strerror(errno)); + } + clock_gettime(CLOCK_MONOTONIC, &now); + + if (FD_ISSET(ttyfd, &rfd)) + ttyread(); + + xev = 0; + while (XPending(xw.dpy)) { + xev = 1; + XNextEvent(xw.dpy, &ev); + if (ev.type == GenericEvent) { + if (ev.xcookie.extension == xw.xi_opcode && + XGetEventData(xw.dpy, &ev.xcookie)) { + if (ev.xcookie.evtype == XI_RawMotion || + ev.xcookie.evtype == XI_RawButtonPress || + ev.xcookie.evtype == XI_RawTouchBegin) + xshowpointer(); + XFreeEventData(xw.dpy, &ev.xcookie); + } + continue; + } + if (ev.type == ClientMessage && + (Atom)ev.xclient.data.l[0] == xw.wmdeletewin) { + cmessage(&ev); + continue; + } + if (XFilterEvent(&ev, None)) + continue; + if (handler[ev.type]) + (handler[ev.type])(&ev); + } + + /* + * To reduce flicker and tearing, when new content or event + * triggers drawing, we first wait a bit to ensure we got + * everything, and if nothing new arrives - we draw. + * We start with trying to wait minlatency ms. If more content + * arrives sooner, we retry with shorter and shorter periods, + * and eventually draw even without idle after maxlatency ms. + * Typically this results in low latency while interacting, + * maximum latency intervals during `cat huge.txt`, and perfect + * sync with periodic updates from animations/key-repeats/etc. + */ + if (FD_ISSET(ttyfd, &rfd) || xev) { + if (!drawing) { + trigger = now; + drawing = 1; + } + timeout = (maxlatency - TIMEDIFF(now, trigger)) \ + / maxlatency * minlatency; + if (timeout > 0) + continue; /* we have time, try to find idle */ + } + + /* idle detected or maxlatency exhausted -> draw */ + timeout = -1; + if (blinktimeout && tattrset(ATTR_BLINK)) { + timeout = blinktimeout - TIMEDIFF(now, lastblink); + if (timeout <= 0) { + if (-timeout > blinktimeout) /* start visible */ + win.mode |= MODE_BLINK; + win.mode ^= MODE_BLINK; + tsetdirtattr(ATTR_BLINK); + lastblink = now; + timeout = blinktimeout; + } + } + + draw(); + XFlush(xw.dpy); + drawing = 0; + } +} + +int +resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst) +{ + char **sdst = dst; + int *idst = dst; + float *fdst = dst; + + char fullname[256]; + char fullclass[256]; + char *type; + XrmValue ret; + + snprintf(fullname, sizeof(fullname), "%s.%s", + opt_name ? opt_name : "st", name); + snprintf(fullclass, sizeof(fullclass), "%s.%s", + opt_class ? opt_class : "St", name); + fullname[sizeof(fullname) - 1] = fullclass[sizeof(fullclass) - 1] = '\0'; + + XrmGetResource(db, fullname, fullclass, &type, &ret); + if (ret.addr == NULL || strncmp("String", type, 64)) + return 1; + + switch (rtype) { + case STRING: + *sdst = strdup(ret.addr); + break; + case INTEGER: + *idst = strtoul(ret.addr, NULL, 10); + break; + case FLOAT: + *fdst = strtof(ret.addr, NULL); + break; + } + return 0; +} + +void +config_init(void) +{ + XrmDatabase db = NULL; + ResourcePref *p; + char *type = NULL; + XrmValue ret; + double dpi = 96.0, scale = 1.0; + + XrmInitialize(); + db = anode_open_xres_db(xw.dpy); + anode_read_xres_scale_from_db(db, xw.dpy, &dpi, &scale, NULL); + + /* Scale base defaults dynamically before reading explicit st.* overrides */ + borderpx = anode_scale_px(2, scale); + cursorthickness = (unsigned int)anode_scale_px(2, scale); + + if (db) { + for (p = resources; p < resources + LEN(resources); p++) + resource_load(db, p->name, p->type, p->dst); + } + + /* Apply Fira Code font sized for current scale unless st.font was explicitly set */ + if (!db || !(XrmGetResource(db, "st.font", "*", &type, &ret) && ret.addr && ret.addr[0])) { + const char *ff = NULL, *bsz = NULL; + if (db && XrmGetResource(db, "theme.fontFace", "*", &type, &ret) && ret.addr && ret.addr[0]) + ff = ret.addr; + if (db && XrmGetResource(db, "theme.baseFontSize", "*", &type, &ret) && ret.addr && ret.addr[0]) + bsz = ret.addr; + int px = bsz ? atoi(bsz) : anode_scale_px(15, scale); + if (px < 8 || px > 96) + px = anode_scale_px(15, scale); + snprintf(st_theme_font, sizeof(st_theme_font), + "%s:pixelsize=%d:style=Regular:antialias=true:autohint=true", + ff ? ff : "Fira Code", px); + font = st_theme_font; + } + if (db) { + if (!(XrmGetResource(db, "st.background", "*", &type, &ret) && ret.addr && ret.addr[0])) { + if (XrmGetResource(db, "theme.bgHeader", "*", &type, &ret) && ret.addr && ret.addr[0]) { + snprintf(st_theme_bg, sizeof(st_theme_bg), "%s", ret.addr); + colorname[256] = st_theme_bg; + } else if (XrmGetResource(db, "theme.bgMain", "*", &type, &ret) && ret.addr && ret.addr[0]) { + snprintf(st_theme_bg, sizeof(st_theme_bg), "%s", ret.addr); + colorname[256] = st_theme_bg; + } + } + if (!(XrmGetResource(db, "st.foreground", "*", &type, &ret) && ret.addr && ret.addr[0]) && + XrmGetResource(db, "theme.fgMain", "*", &type, &ret) && ret.addr && ret.addr[0]) { + snprintf(st_theme_fg, sizeof(st_theme_fg), "%s", ret.addr); + colorname[257] = st_theme_fg; + } + if (!(XrmGetResource(db, "st.cursorColor", "*", &type, &ret) && ret.addr && ret.addr[0]) && + XrmGetResource(db, "theme.accent", "*", &type, &ret) && ret.addr && ret.addr[0]) { + snprintf(st_theme_cs, sizeof(st_theme_cs), "%s", ret.addr); + colorname[258] = st_theme_cs; + } + XrmDestroyDatabase(db); + } +} + +void +usage(void) +{ + die("usage: %s [-aiv] [-c class] [-f font] [-g geometry]" + " [-n name] [-o file]\n" + " [-T title] [-t title] [-w windowid]" + " [[-e] command [args ...]]\n" + " %s [-aiv] [-c class] [-f font] [-g geometry]" + " [-n name] [-o file]\n" + " [-T title] [-t title] [-w windowid] -l line" + " [stty_args ...]\n", argv0, argv0); +} + +int +main(int argc, char *argv[]) +{ + xw.l = xw.t = 0; + xw.isfixed = False; + xsetcursor(cursorshape); + + ARGBEGIN { + case 'a': + allowaltscreen = 0; + break; + case 'c': + opt_class = EARGF(usage()); + break; + case 'e': + if (argc > 0) + --argc, ++argv; + goto run; + case 'f': + opt_font = EARGF(usage()); + break; + case 'g': + xw.gm = XParseGeometry(EARGF(usage()), + &xw.l, &xw.t, &cols, &rows); + break; + case 'i': + xw.isfixed = 1; + break; + case 'o': + opt_io = EARGF(usage()); + break; + case 'l': + opt_line = EARGF(usage()); + break; + case 'n': + opt_name = EARGF(usage()); + break; + case 't': + case 'T': + opt_title = EARGF(usage()); + break; + case 'w': + opt_embed = EARGF(usage()); + break; + case 'v': + die("%s " VERSION "\n", argv0); + break; + default: + usage(); + } ARGEND; + +run: + if (argc > 0) /* eat all remaining arguments */ + opt_cmd = argv; + + if (!opt_title) + opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0]; + + if (!getenv("DISPLAY")) + setenv("DISPLAY", ":0", 0); + + setlocale(LC_CTYPE, ""); + XSetLocaleModifiers(""); + + if(!(xw.dpy = XOpenDisplay(NULL))) + die("Can't open display\n"); + + config_init(); + cols = MAX(cols, 1); + rows = MAX(rows, 1); + tnew(cols, rows); + xinit(cols, rows); + xsetenv(); + selinit(); + run(); + + return 0; +} diff --git a/tests/test_posix_make.py b/tests/test_posix_make.py new file mode 100755 index 0000000..4fe4fb5 --- /dev/null +++ b/tests/test_posix_make.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Verify strict POSIX Makefile compliance and POSIX /bin/sh syntax across all scripts.""" + +import os +import re +import subprocess +import sys + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + + +def check_makefile() -> None: + mk_path = os.path.join(ROOT, "Makefile") + with open(mk_path, "r", encoding="utf-8") as f: + lines = f.read().splitlines() + + assert any(l.strip() == ".POSIX:" for l in lines), "Makefile must begin with .POSIX:" + + # Check for GNU-only or BSD-only constructs + forbidden = [ + (r"^\s*(ifeq|ifneq|ifdef|ifndef|else|endif)\b", "GNU conditional"), + (r"\$\(shell\b", "$(shell ...) GNU function"), + (r"\$\(wildcard\b", "$(wildcard ...) GNU function"), + (r"\$\(patsubst\b", "$(patsubst ...) GNU function"), + (r"\$\(subst\b", "$(subst ...) GNU function"), + (r":=", "non-POSIX immediate assignment :="), + (r"\+=", "non-POSIX append assignment +="), + (r"\?=", "non-POSIX conditional assignment ?="), + (r"\$\^", "non-POSIX automatic variable $^"), + (r"^[^#]*%[^:]*:", "GNU pattern rule %.o"), + (r"^\s*include\b|^\s*-include\b", "non-POSIX include directive"), + (r"^\s*export\b", "GNU export directive"), + (r"\bmake\s+-C\b|\$\(MAKE\)\s+-C\b", "GNU make -C option"), + ] + for lineno, line in enumerate(lines, 1): + stripped = line.strip() + if stripped.startswith("#") or not stripped: + continue + for pat, desc in forbidden: + assert not re.search(pat, line), f"Makefile:{lineno}: {desc}: {line}" + # $< is only allowed in inference rules (e.g. .c.o:), not explicit target rules + if "$<" in line: + raise AssertionError(f"Makefile:{lineno}: avoid $< in explicit rules: {line}") + + # Verify Makefile parses cleanly under make -n (no syntax errors) + res = subprocess.run(["make", "-n", "-f", mk_path], cwd=ROOT, capture_output=True, text=True) + assert res.returncode == 0, f"make -n failed: {res.stderr}" + + +def check_scripts() -> None: + script_files = [ + "scripts/detect-env.sh", + "scripts/anode-apply-scale", + "scripts/anode-apply-theme", + "scripts/anode-sync-gtk-theme", + "scripts/anode-sync-dunst-theme", + "scripts/anode-session", + "scripts/anode-launcher", + "data/env.sh", + "src/dmenu/dmenu_path", + "src/dmenu/dmenu_run", + ] + bad_patterns = [ + (r"\[\[\s", "bash [[ conditional"), + (r"\becho\s+-e\b", "non-portable echo -e"), + (r"\blocal\s+", "non-POSIX local keyword"), + (r"\bpidof\b", "Linux-only pidof"), + (r"\bsed\s+-i\b", "non-POSIX sed -i"), + (r"\bxargs\s+-r\b", "GNU xargs -r"), + (r"\bcp\s+-a\b", "GNU cp -a"), + (r"\bln\s+-sfn\b", "GNU ln -sfn"), + (r"\bmktemp\s+-p\b", "GNU mktemp -p"), + ] + for rel in script_files: + p = os.path.join(ROOT, rel) + assert os.path.isfile(p), f"Missing script: {rel}" + st = subprocess.run(["sh", "-n", p], capture_output=True, text=True) + assert st.returncode == 0, f"sh -n failed on {rel}: {st.stderr}" + + with open(p, "r", encoding="utf-8") as f: + content = f.read() + for lineno, line in enumerate(content.splitlines(), 1): + # Skip comments + code = line.split("#", 1)[0] + if not code.strip(): + continue + # Allow '#!/bin/sh' + for pat, desc in bad_patterns: + assert not re.search(pat, code), f"{rel}:{lineno}: {desc}: {line}" + + +if __name__ == "__main__": + check_makefile() + check_scripts() + print("test_posix_make: OK") diff --git a/tests/test_theme_scale.py b/tests/test_theme_scale.py new file mode 100755 index 0000000..bb06a4f --- /dev/null +++ b/tests/test_theme_scale.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Verify .xth theme switching and fractional DPI scaling across toolkits without double-scaling.""" + +import glob +import os +import re +import subprocess +import tempfile + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +THEMES_DIR = os.path.join(ROOT, "data", "themes") +APPLY_SCALE = os.path.join(ROOT, "scripts", "anode-apply-scale") +APPLY_THEME = os.path.join(ROOT, "scripts", "anode-apply-theme") + + +def run_env(env, cmd): + res = subprocess.run(cmd, env=env, capture_output=True, text=True) + assert res.returncode == 0, f"Command failed: {cmd}\nstdout={res.stdout}\nstderr={res.stderr}" + return res + + +def parse_xres(path): + out = {} + with open(path, "r", encoding="utf-8") as f: + for line in f: + s = line.strip() + if not s or s.startswith("!") or s.startswith("#"): + continue + if ":" in s: + k, v = s.split(":", 1) + out[k.strip()] = v.strip() + return out + + +def test_fractional_scales(): + scales = [ + ("0.75", 72, "1", 11), + ("1.00", 96, "1", 15), + ("1.25", 120, "1", 19), + ("1.50", 144, "1", 23), + ("1.75", 168, "2", 26), + ("2.00", 192, "2", 30), + ("2.50", 240, "3", 38), + ] + with tempfile.TemporaryDirectory() as tmp: + env = dict(os.environ) + env.pop("DISPLAY", None) + env["HOME"] = tmp + env["XDG_CONFIG_HOME"] = os.path.join(tmp, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + + for s_str, exp_dpi, exp_gdk, exp_px in scales: + run_env(env, [APPLY_SCALE, s_str, "--touch=1"]) + scale_env_p = os.path.join(tmp, ".config", "anode", "scale.env") + with open(scale_env_p, "r", encoding="utf-8") as f: + senv = f.read() + assert f'export GDK_SCALE="{exp_gdk}"' in senv, senv + assert 'export GDK_DPI_SCALE="1.0"' in senv, senv + assert f'export QT_SCALE_FACTOR="{s_str}"' in senv, senv + assert 'export QT_FONT_DPI="96"' in senv, senv + assert 'export QT_AUTO_SCREEN_SCALE_FACTOR="0"' in senv, senv + assert 'export QT_SCALE_FACTOR_ROUNDING_POLICY="PassThrough"' in senv, senv + + xres = parse_xres(os.path.join(tmp, ".Xresources")) + assert int(xres["Xft.dpi"]) == exp_dpi, f"scale={s_str} dpi={xres['Xft.dpi']}" + assert int(xres["theme.baseFontSize"]) == exp_px, f"scale={s_str} base={xres['theme.baseFontSize']}" + assert xres["theme.fontFace"] == "Fira Code" + assert "Fira Code" in xres["st.font"] and f"pixelsize={exp_px}" in xres["st.font"] + assert "Fira Code" in xres["dwm.font"] and f"{exp_px}px" in xres["dwm.font"] + assert xres["*TkTheme"] == "gtkTtk" + assert xres["theme.touchMode"] == "1" + + # Verify xsettingsd omits Xft/DPI so GTK3 does not double-scale + xs_p = os.path.join(tmp, ".config", "xsettingsd", "xsettingsd.conf") + with open(xs_p, "r", encoding="utf-8") as f: + xs = f.read() + assert "Xft/DPI" not in xs, f"Xft/DPI must not exist in xsettingsd.conf:\n{xs}" + assert f"Gdk/WindowScalingFactor {exp_gdk}" in xs, xs + + # Verify Qt5 + Qt6 + Kvantum + Dunst + GTK2/3/4 files + for p in [ + ".gtkrc-2.0", + ".config/gtk-3.0/gtk.css", + ".config/gtk-3.0/settings.ini", + ".config/gtk-4.0/gtk.css", + ".config/gtk-4.0/settings.ini", + ".config/qt5ct/qt5ct.conf", + ".config/qt6ct/qt6ct.conf", + ".config/Kvantum/kvantum.kvconfig", + ".config/dunst/dunstrc", + ]: + full = os.path.join(tmp, p) + assert os.path.isfile(full) and os.path.getsize(full) > 20, f"Missing/empty {p}" + + +def test_all_22_themes_and_legacy_192dpi_import(): + themes = sorted(glob.glob(os.path.join(THEMES_DIR, "*.xth"))) + assert len(themes) == 22, f"Expected 22 .xth themes, got {len(themes)}" + + with tempfile.TemporaryDirectory() as tmp: + env = dict(os.environ) + env.pop("DISPLAY", None) + env["HOME"] = tmp + env["XDG_CONFIG_HOME"] = os.path.join(tmp, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + run_env(env, [APPLY_SCALE, "1.00", "--touch=0", "--no-apply"]) + + for th in themes: + run_env(env, [APPLY_THEME, th]) + xres = parse_xres(os.path.join(tmp, ".Xresources")) + tname = xres["theme.name"] + assert xres["Xft.dpi"] == "96" + assert xres["theme.baseFontSize"] == "15" + assert xres["theme.fontFace"] == "Fira Code" + assert os.path.isfile(os.path.join(tmp, ".config", "qt6ct", "colors", f"ANODE-{tname}.conf")) + assert os.path.isfile(os.path.join(tmp, ".config", "qt5ct", "colors", f"ANODE-{tname}.conf")) + + # Legacy 192-DPI import must normalize back to 96 DPI / 15px at 1.00x scale + legacy_xth = os.path.join(tmp, "LegacyHiDpi.xth") + with open(legacy_xth, "w", encoding="utf-8") as f: + f.write( + "theme.name: LegacyHiDpi\n" + "Xft.dpi: 192\n" + "Xcursor.size: 64\n" + "theme.fontFace: Fira Code\n" + "theme.baseFontSize: 32\n" + "dwm.borderpx: 4\n" + "theme.bgMain: #101010\n" + "theme.fgMain: #eeeeee\n" + "theme.accent: #55aaff\n" + ) + run_env(env, [APPLY_THEME, legacy_xth]) + xres = parse_xres(os.path.join(tmp, ".Xresources")) + assert xres["Xft.dpi"] == "96" + assert int(xres["theme.baseFontSize"]) == 16, xres["theme.baseFontSize"] + assert int(xres["dwm.borderpx"]) == 2, xres["dwm.borderpx"] + + +if __name__ == "__main__": + test_fractional_scales() + test_all_22_themes_and_legacy_192dpi_import() + print("test_theme_scale: ALL PASSED (7 fractional scales, 22 themes, legacy 192-DPI import)") diff --git a/tests/test_units.c b/tests/test_units.c new file mode 100644 index 0000000..7933709 --- /dev/null +++ b/tests/test_units.c @@ -0,0 +1,207 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include + +#include "anode_scale.h" +#include "anode_plat.h" +#include "anode_dns_valid.h" +#include "anode_tz_valid.h" +#include "anode_audio_parse.h" +#include "anode_wifi_list.h" +#include "anode_bt_list.h" +#include "anode_power_policy.h" +#include "anode-touch-gesture.h" + +static void test_scale_math(void) { + assert(anode_clamp_scale(0.1) == 0.5); + assert(anode_clamp_scale(9.0) == 4.0); + assert(anode_clamp_scale(1.25) == 1.25); + assert(anode_clamp_dpi(12.0) == 48.0); + assert(anode_clamp_dpi(600.0) == 384.0); + assert(anode_scale_from_dpi(144.0) == 1.5); + assert(anode_scale_from_dpi(192.0) == 2.0); + assert(anode_scale_px(15, 1.0) == 15); + assert(anode_scale_px(15, 1.5) == 23); + assert(anode_scale_px(15, 2.0) == 30); + assert(anode_scale_px(15, 0.75) == 11); + assert(anode_parse_bool_str("true", 0) == 1); + assert(anode_parse_bool_str("yes", 0) == 1); + assert(anode_parse_bool_str("1", 0) == 1); + assert(anode_parse_bool_str("false", 1) == 0); + assert(anode_parse_bool_str("0", 1) == 0); + assert(anode_parse_bool_str("unknown", 1) == 1); +} + +static void test_dns_validation(void) { + char v4[ANODE_DNS_MAX_SERVERS][16]; + char v6[ANODE_DNS_MAX_SERVERS][46]; + int n4 = 0, n6 = 0; + char csv[256] = {0}; + + int tot = anode_parse_dns_servers("1.1.1.1, 8.8.8.8, 1.1.1.1, 2606:4700:4700::1111", + v4, &n4, ANODE_DNS_MAX_SERVERS, + v6, &n6, ANODE_DNS_MAX_SERVERS, + csv, sizeof(csv)); + assert(tot == 3); + assert(n4 == 2); + assert(n6 == 1); + assert(strcmp(csv, "1.1.1.1,8.8.8.8,2606:4700:4700::1111") == 0); + + assert(anode_parse_dns_servers("0.0.0.0", v4, &n4, 6, v6, &n6, 6, csv, sizeof(csv)) == -1); + assert(anode_parse_dns_servers("224.0.0.1", v4, &n4, 6, v6, &n6, 6, csv, sizeof(csv)) == -1); + assert(anode_parse_dns_servers("1.1.1.1; rm -rf /", v4, &n4, 6, v6, &n6, 6, csv, sizeof(csv)) == -1); + assert(anode_dns_mode_valid("cloudflare")); + assert(!anode_dns_mode_valid("evil")); + + char sum[128] = {0}; + int c = anode_parse_resolv_conf("# comment\nnameserver 9.9.9.9\nnameserver 1.1.1.1\n", sum, sizeof(sum)); + assert(c == 2); + assert(strcmp(sum, "9.9.9.9, 1.1.1.1") == 0); +} + +static void test_tz_validation(void) { + assert(anode_tz_name_valid("UTC")); + assert(anode_tz_name_valid("America/New_York")); + assert(anode_tz_name_valid("Etc/GMT+2")); + assert(!anode_tz_name_valid("")); + assert(!anode_tz_name_valid("../etc/passwd")); + assert(!anode_tz_name_valid("/America/New_York")); + assert(!anode_tz_name_valid("America//New_York")); + assert(!anode_tz_name_valid("UTC;id")); + if (access("/usr/share/zoneinfo/UTC", R_OK) == 0) { + assert(anode_tz_file_valid("/usr/share/zoneinfo", "UTC")); + assert(!anode_tz_file_valid("/usr/share/zoneinfo", "No/SuchZone")); + } +} + +static void test_audio_parsers(void) { + int vol = 0; + bool muted = false; + assert(anode_parse_wpctl_volume("Volume: 0.65 [MUTED]", &vol, &muted)); + assert(vol == 65 && muted == true); + assert(anode_parse_wpctl_volume("Volume: 1.00", &vol, &muted)); + assert(vol == 100 && muted == false); + + char sink[128], src[128]; + anode_parse_pactl_defaults("Server Name: Pulse\nDefault Sink: alsa_out.pci\nDefault Source: alsa_in.pci\n", + sink, sizeof(sink), src, sizeof(src)); + assert(strcmp(sink, "alsa_out.pci") == 0); + assert(strcmp(src, "alsa_in.pci") == 0); + + const char *sinks_txt = + "Sink #3\n" + "\tState: RUNNING\n" + "\tName: alsa_out.pci\n" + "\tDescription: Built-in Analog\n" + "\tMute: no\n" + "\tVolume: front-left: 52428 / 80%\n"; + anode_audio_node_t nodes[8]; + int nn = anode_parse_pactl_nodes(sinks_txt, "Sink #", "alsa_out.pci", false, nodes, 8); + assert(nn == 1); + assert(nodes[0].index == 3); + assert(nodes[0].is_default == true); + assert(nodes[0].vol_pct == 80); + assert(nodes[0].muted == false); + + const char *am_txt = "Simple mixer control 'Master',0\nSimple mixer control 'Capture',0\n"; + int na = anode_parse_amixer_scontrols(am_txt, nodes, 8); + assert(na == 2 && strcmp(nodes[0].name, "Master") == 0 && nodes[0].is_default); + + const char *sn_txt = "output.level=0.72\noutput.mute=0\ninput.level=0.40\n"; + int ns = anode_parse_sndioctl(sn_txt, false, nodes, 8); + assert(ns == 1 && nodes[0].vol_pct == 72); +} + +static void test_wifi_and_bt_parsers(void) { + const char *nm = + " :11\\:22\\:33\\:44\\:55\\:66:HomeNet:6:45:WPA2\n" + "*:AA\\:BB\\:CC\\:DD\\:EE\\:FF:HomeNet:36:85:WPA2\n" + " :00\\:11\\:22\\:33\\:44\\:55:CafeFree:11:60:--\n"; + anode_wifi_group_t grp[8]; + int ng = anode_parse_wifi_scan(nm, grp, 8); + assert(ng == 2); + assert(strcmp(grp[0].ssid, "HomeNet") == 0); + assert(grp[0].in_use == true); + assert(grp[0].best_chan == 36); + assert(grp[0].ap_count == 2); + assert(strcmp(grp[1].security, "Open") == 0); + + const char *iw = "Connected to aa:bb:cc:dd:ee:ff\n\tSSID: LabWiFi\n\tfreq: 5180\n\tsignal: -55 dBm\n"; + char bssid[32], ssid[64]; + int ch = 0, sig = 0; + assert(anode_parse_iw_link(iw, bssid, sizeof(bssid), ssid, sizeof(ssid), &ch, &sig)); + assert(strcmp(ssid, "LabWiFi") == 0 && ch == 36 && sig == 90); + + anode_bt_dev_t devs[8]; + int nb = anode_parse_bt_devices("Device aa:bb:cc:dd:ee:ff Keyboard\nDevice 11:22:33:44:55:66 Speaker\n", + "Device 11:22:33:44:55:66 Speaker\n", + "Device 11:22:33:44:55:66 Speaker\n", + devs, 8); + assert(nb == 2); + assert(devs[0].connected && strcmp(devs[0].name, "Speaker") == 0); +} + +static void test_power_policy_and_gestures(void) { + anode_power_cfg_t cfg = anode_power_cfg_default(); + anode_pwr_state_t st = ANODE_PWR_ACTIVE; + anode_power_actions_t act; + + anode_power_policy_step(&cfg, &st, 10000, false, 80, true, false, &act); + assert(st == ANODE_PWR_ACTIVE && !act.dim_now); + + anode_power_policy_step(&cfg, &st, 65000, false, 80, true, false, &act); + assert(st == ANODE_PWR_DIMMED && act.dim_now); + + anode_power_policy_step(&cfg, &st, 1000, false, 80, true, false, &act); + assert(st == ANODE_PWR_ACTIVE && act.restore_brightness); + + anode_power_policy_step(&cfg, &st, 190000, false, 80, true, false, &act); + assert(st == ANODE_PWR_LOCKED && act.lock_now); + + anode_power_policy_step(&cfg, &st, 610000, false, 80, true, true, &act); + assert(st == ANODE_PWR_SUSPENDED && act.suspend_now); + + /* Critical low battery override on battery */ + st = ANODE_PWR_ACTIVE; + anode_power_policy_step(&cfg, &st, 1000, false, 2, true, false, &act); + assert(act.warn_low_batt && act.suspend_now); + + /* Gestures at 1.0x and 2.0x scales */ + anode_touch_track_t tr = {0}; + anode_touch_begin(&tr, 1, 500, 1070, 1000); + assert(anode_touch_finish(&tr, 500, 900, 1200, 1920, 1080, 1.0) == ANODE_GEST_VKBD_TOGGLE); + + anode_touch_begin(&tr, 2, 1000, 15, 2000); + assert(anode_touch_finish(&tr, 1000, 220, 2250, 3840, 2160, 2.0) == ANODE_GEST_LAUNCHER); + + anode_touch_begin(&tr, 3, 1910, 500, 3000); + assert(anode_touch_finish(&tr, 1750, 500, 3200, 1920, 1080, 1.0) == ANODE_GEST_CONTROL); +} + +static void test_platform_probe(void) { + anode_net_iface_t ifs[ANODE_MAX_IFACES]; + int n = anode_list_net_ifaces(ifs, ANODE_MAX_IFACES); + assert(n >= 0); + anode_battery_info_t bat; + anode_read_battery(&bat); + (void)anode_detect_audio_backend(); + char buf[256]; + anode_runtime_dir(buf, sizeof(buf)); + assert(buf[0] == '/'); + anode_config_dir(buf, sizeof(buf)); + assert(buf[0] == '/'); +} + +int main(void) { + test_scale_math(); + test_dns_validation(); + test_tz_validation(); + test_audio_parsers(); + test_wifi_and_bt_parsers(); + test_power_policy_and_gestures(); + test_platform_probe(); + printf("test_units: ALL PASSED\n"); + return 0; +} diff --git a/tests/test_x11_xvfb.py b/tests/test_x11_xvfb.py new file mode 100755 index 0000000..c8f8aa4 --- /dev/null +++ b/tests/test_x11_xvfb.py @@ -0,0 +1,334 @@ +#!/usr/bin/env python3 +"""Headless Xvfb E2E integration tests across 1024x600, 1920x1080, and 3840x2160.""" + +import ctypes +import ctypes.util +import os +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import time + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +BUILD = os.path.join(ROOT, "build") + +libx11_name = ctypes.util.find_library("X11") or "libX11.so.6" +X11 = ctypes.CDLL(libx11_name) + +Window = ctypes.c_ulong +Atom = ctypes.c_ulong +Display_p = ctypes.c_void_p + + +class XWindowAttributes(ctypes.Structure): + _fields_ = [ + ("x", ctypes.c_int), ("y", ctypes.c_int), + ("width", ctypes.c_int), ("height", ctypes.c_int), + ("border_width", ctypes.c_int), ("depth", ctypes.c_int), + ("visual", ctypes.c_void_p), ("root", Window), + ("class", ctypes.c_int), ("bit_gravity", ctypes.c_int), + ("win_gravity", ctypes.c_int), ("backing_store", ctypes.c_int), + ("backing_planes", ctypes.c_ulong), ("backing_pixel", ctypes.c_ulong), + ("save_under", ctypes.c_int), ("colormap", ctypes.c_ulong), + ("map_installed", ctypes.c_int), ("map_state", ctypes.c_int), + ("all_event_masks", ctypes.c_long), ("your_event_mask", ctypes.c_long), + ("do_not_propagate_mask", ctypes.c_long), ("override_redirect", ctypes.c_int), + ("screen", ctypes.c_void_p), + ] + + +class XClientMessageData(ctypes.Union): + _fields_ = [("b", ctypes.c_char * 20), ("s", ctypes.c_short * 10), ("l", ctypes.c_long * 5)] + + +class XClientMessageEvent(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", XClientMessageData), + ] + + +class XWMHints(ctypes.Structure): + _fields_ = [ + ("flags", ctypes.c_long), ("input", ctypes.c_int), ("initial_state", ctypes.c_int), + ("icon_pixmap", ctypes.c_ulong), ("icon_window", Window), + ("icon_x", ctypes.c_int), ("icon_y", ctypes.c_int), + ("icon_mask", ctypes.c_ulong), ("window_group", Window), + ] + + +X11.XOpenDisplay.argtypes = [ctypes.c_char_p] +X11.XOpenDisplay.restype = Display_p +X11.XCloseDisplay.argtypes = [Display_p] +X11.XDefaultRootWindow.argtypes = [Display_p] +X11.XDefaultRootWindow.restype = Window +X11.XInternAtom.argtypes = [Display_p, ctypes.c_char_p, ctypes.c_int] +X11.XInternAtom.restype = Atom +X11.XGetSelectionOwner.argtypes = [Display_p, Atom] +X11.XGetSelectionOwner.restype = Window +X11.XGetWindowProperty.argtypes = [ + Display_p, Window, Atom, ctypes.c_long, ctypes.c_long, ctypes.c_int, Atom, + ctypes.POINTER(Atom), ctypes.POINTER(ctypes.c_int), + ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), +] +X11.XGetWindowProperty.restype = ctypes.c_int +X11.XFree.argtypes = [ctypes.c_void_p] +X11.XCreateSimpleWindow.argtypes = [ + Display_p, Window, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint, + ctypes.c_uint, ctypes.c_ulong, ctypes.c_ulong, +] +X11.XCreateSimpleWindow.restype = Window +X11.XDestroyWindow.argtypes = [Display_p, Window] +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.XFlush.argtypes = [Display_p] +X11.XSync.argtypes = [Display_p, ctypes.c_int] +X11.XQueryTree.argtypes = [ + Display_p, Window, ctypes.POINTER(Window), ctypes.POINTER(Window), + ctypes.POINTER(ctypes.POINTER(Window)), ctypes.POINTER(ctypes.c_uint), +] +X11.XQueryTree.restype = ctypes.c_int +X11.XGetWindowAttributes.argtypes = [Display_p, Window, ctypes.POINTER(XWindowAttributes)] +X11.XGetWindowAttributes.restype = ctypes.c_int +X11.XGetWMHints.argtypes = [Display_p, Window] +X11.XGetWMHints.restype = ctypes.POINTER(XWMHints) +X11.XFetchName.argtypes = [Display_p, Window, ctypes.POINTER(ctypes.c_char_p)] +X11.XFetchName.restype = ctypes.c_int + + +def pick_display(): + for d in range(70, 120): + if not os.path.exists(f"/tmp/.X{d}-lock") and not os.path.exists(f"/tmp/.X11-unix/X{d}"): + return f":{d}" + return ":99" + + +def get_cardinal_prop(dpy, win, atom_name): + atom = X11.XInternAtom(dpy, atom_name.encode(), 0) + da = Atom() + di = ctypes.c_int() + n = ctypes.c_ulong() + dl = ctypes.c_ulong() + prop = ctypes.POINTER(ctypes.c_ubyte)() + rc = X11.XGetWindowProperty(dpy, win, atom, 0, 16, 0, 0, + ctypes.byref(da), ctypes.byref(di), + ctypes.byref(n), ctypes.byref(dl), ctypes.byref(prop)) + if rc != 0 or not prop: + return [] + vals = [] + if di.value == 32 and n.value > 0: + arr = ctypes.cast(prop, ctypes.POINTER(ctypes.c_ulong)) + vals = [int(arr[i]) for i in range(n.value)] + X11.XFree(prop) + return vals + + +def query_children(dpy, parent): + r = Window() + p = Window() + ch = ctypes.POINTER(Window)() + n = ctypes.c_uint() + if X11.XQueryTree(dpy, parent, ctypes.byref(r), ctypes.byref(p), ctypes.byref(ch), ctypes.byref(n)): + out = [int(ch[i]) for i in range(n.value)] + if ch: + X11.XFree(ch) + return out + return [] + + +def wait_until(pred, timeout=5.0): + end = time.monotonic() + timeout + while time.monotonic() < end: + res = pred() + if res: + return res + time.sleep(0.05) + return None + + +def terminate(proc): + if proc and proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=3) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait(timeout=2) + + +def test_resolution(res_str, scale_str, width, height): + disp = pick_display() + with tempfile.TemporaryDirectory() as home: + env = dict(os.environ) + env["DISPLAY"] = disp + env["HOME"] = home + env["XDG_CONFIG_HOME"] = os.path.join(home, ".config") + env["ANODE_PREFIX"] = ROOT + env["ANODE_NO_SIGNAL"] = "1" + env["LD_LIBRARY_PATH"] = os.path.join(BUILD, "libgemui") + (":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "") + env["PATH"] = ( + os.path.join(BUILD, "dwm") + ":" + + os.path.join(BUILD, "dmenu") + ":" + + os.path.join(BUILD, "st") + ":" + + os.path.join(BUILD, "apps") + ":" + + os.path.join(BUILD, "daemons") + ":" + + os.path.join(ROOT, "scripts") + ":" + + env.get("PATH", "") + ) + + # Configure theme + scale in sandbox + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), scale_str, "--touch=1"], env=env, check=True) + + xvfb = subprocess.Popen( + ["Xvfb", disp, "-screen", "0", f"{res_str}x24", "-nolisten", "tcp"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + dwm = None + dpy = None + procs = [] + try: + dpy = wait_until(lambda: X11.XOpenDisplay(disp.encode())) + assert dpy, f"Failed to open Xvfb {disp}" + root = X11.XDefaultRootWindow(dpy) + + dwm = subprocess.Popen([os.path.join(BUILD, "dwm", "dwm")], env=env) + procs.append(dwm) + + tray_atom = X11.XInternAtom(dpy, b"_NET_SYSTEM_TRAY_S0", 0) + tray_win = wait_until(lambda: X11.XGetSelectionOwner(dpy, tray_atom)) + assert tray_win, f"DWM failed to acquire _NET_SYSTEM_TRAY_S0 on {res_str}" + + # Check initial _NET_WORKAREA and empty systray must be unmapped + wa0 = wait_until(lambda: get_cardinal_prop(dpy, root, "_NET_WORKAREA")) + assert len(wa0) >= 4 and wa0[2] == width and wa0[3] < height, f"Bad initial workarea: {wa0}" + tray_attr = XWindowAttributes() + X11.XGetWindowAttributes(dpy, tray_win, ctypes.byref(tray_attr)) + assert tray_attr.map_state == 0, "Empty systray should stay unmapped!" + + # Test XEmbed systray docking + _XEMBED_INFO unmap/remap + SIGUSR1 resize + undock + icon = X11.XCreateSimpleWindow(dpy, root, 0, 0, 24, 24, 0, 0, 0xffffff) + xembed_info = X11.XInternAtom(dpy, b"_XEMBED_INFO", 0) + info_arr = (ctypes.c_ulong * 2)(0, 1) # version=0, XEMBED_MAPPED=1 + X11.XChangeProperty(dpy, icon, xembed_info, xembed_info, 32, 0, info_arr, 2) + op_atom = X11.XInternAtom(dpy, b"_NET_SYSTEM_TRAY_OPCODE", 0) + ev = XClientMessageEvent() + ev.type = 33 # ClientMessage + ev.display = dpy + ev.window = tray_win + ev.message_type = op_atom + ev.format = 32 + ev.data.l[0] = 0 + ev.data.l[1] = 0 # SYSTEM_TRAY_REQUEST_DOCK + ev.data.l[2] = icon + X11.XSendEvent(dpy, tray_win, 0, 0, ctypes.byref(ev)) + X11.XSync(dpy, 0) + + assert wait_until(lambda: icon in query_children(dpy, tray_win)), "Icon was not reparented into systray!" + X11.XGetWindowAttributes(dpy, tray_win, ctypes.byref(tray_attr)) + assert tray_attr.map_state == 2, "Non-empty systray must be mapped (IsViewable)" + + # Toggle _XEMBED_INFO unmapped -> tray unmaps + info_unmap = (ctypes.c_ulong * 2)(0, 0) + X11.XChangeProperty(dpy, icon, xembed_info, xembed_info, 32, 0, info_unmap, 2) + X11.XSync(dpy, 0) + assert wait_until(lambda: (X11.XGetWindowAttributes(dpy, tray_win, ctypes.byref(tray_attr)) or True) and tray_attr.map_state == 0), "Tray did not unmap when icon withdrew!" + + # Remap via _XEMBED_INFO, reload scale via SIGUSR1, then destroy cleanly + X11.XChangeProperty(dpy, icon, xembed_info, xembed_info, 32, 0, info_arr, 2) + X11.XSync(dpy, 0) + assert wait_until(lambda: (X11.XGetWindowAttributes(dpy, tray_win, ctypes.byref(tray_attr)) or True) and tray_attr.map_state == 2) + pre_h = tray_attr.height + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), "2.00", "--touch=1"], env=env, check=True) + dwm.send_signal(signal.SIGUSR1) + time.sleep(0.25) + X11.XGetWindowAttributes(dpy, tray_win, ctypes.byref(tray_attr)) + assert tray_attr.height >= pre_h, f"Tray height did not preserve/scale after SIGUSR1: {tray_attr.height} vs {pre_h}" + subprocess.run([os.path.join(ROOT, "scripts", "anode-apply-scale"), scale_str, "--touch=1"], env=env, check=True) + dwm.send_signal(signal.SIGUSR1) + time.sleep(0.2) + X11.XDestroyWindow(dpy, icon) + X11.XSync(dpy, 0) + assert wait_until(lambda: icon not in query_children(dpy, tray_win)) + + # Refresh wa0 after scale restore before testing anode-vkbd dock strut + wa0 = wait_until(lambda: get_cardinal_prop(dpy, root, "_NET_WORKAREA")) + vkbd = subprocess.Popen([os.path.join(BUILD, "apps", "anode-vkbd")], env=env) + procs.append(vkbd) + wa_vk = wait_until(lambda: (lambda w: w if w and len(w) >= 4 and w[3] < wa0[3] else None)(get_cardinal_prop(dpy, root, "_NET_WORKAREA"))) + assert wa_vk, f"anode-vkbd did not reserve workarea strut on {res_str} (wa0={wa0})" + # Hide via SIGUSR1 -> workarea restores, then re-show via SIGUSR1 -> strut reserves again + vkbd.send_signal(signal.SIGUSR1) + assert wait_until(lambda: get_cardinal_prop(dpy, root, "_NET_WORKAREA") == wa0), "Workarea did not restore on vkbd hide" + vkbd.send_signal(signal.SIGUSR1) + assert wait_until(lambda: (lambda w: w if w and len(w) >= 4 and w[3] < wa0[3] else None)(get_cardinal_prop(dpy, root, "_NET_WORKAREA"))), "Workarea did not re-reserve on vkbd show" + terminate(vkbd) + + # Test anode-statusd updates root WM_NAME + sd = subprocess.Popen([os.path.join(BUILD, "daemons", "anode-statusd")], env=env) + procs.append(sd) + def has_status(): + nm = ctypes.c_char_p() + if X11.XFetchName(dpy, root, ctypes.byref(nm)) and nm.value: + s = nm.value.decode("utf-8", errors="ignore") + X11.XFree(nm) + if "|" in s: + return s + return None + assert wait_until(has_status), "anode-statusd did not publish status to root WM_NAME" + terminate(sd) + + # Test core + GemUI utilities launch, map cleanly inside screen, and exit cleanly + for bin_path, extra_stdin in [ + (os.path.join(BUILD, "st", "st"), None), + (os.path.join(BUILD, "dmenu", "dmenu"), b"alpha\nbeta\n"), + (os.path.join(BUILD, "apps", "anode-themes"), None), + (os.path.join(BUILD, "apps", "anode-power"), None), + (os.path.join(BUILD, "apps", "anode-display"), None), + (os.path.join(BUILD, "apps", "anode-audio"), None), + (os.path.join(BUILD, "apps", "anode-datetime"), None), + (os.path.join(BUILD, "apps", "anode-net"), None), + ]: + before = set(query_children(dpy, root)) + if extra_stdin: + p = subprocess.Popen([bin_path], env=env, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + p.stdin.write(extra_stdin) + p.stdin.close() + else: + p = subprocess.Popen([bin_path], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + procs.append(p) + time.sleep(0.35) + assert p.poll() is None, f"{os.path.basename(bin_path)} exited prematurely on {res_str} with code {p.returncode}" + terminate(p) + + finally: + for p in reversed(procs): + terminate(p) + if dpy: + X11.XCloseDisplay(dpy) + terminate(xvfb) + + +def main(): + if not shutil.which("Xvfb"): + print("test_x11_xvfb: Xvfb not installed (skipping)") + return 0 + cases = [ + ("1024x600", "1.00", 1024, 600), + ("1920x1080", "1.25", 1920, 1080), + ("3840x2160", "2.00", 3840, 2160), + ] + for res, sc, w, h in cases: + test_resolution(res, sc, w, h) + print(f"test_x11_xvfb: {res} @ {sc}x OK") + return 0 + + +if __name__ == "__main__": + sys.exit(main())