diff --git a/overlay/rootfs/etc/skel/.xthemes/Anodized.xth b/overlay/rootfs/etc/skel/.xthemes/Anodized.xth new file mode 100644 index 0000000..d59a60d --- /dev/null +++ b/overlay/rootfs/etc/skel/.xthemes/Anodized.xth @@ -0,0 +1,96 @@ +! Geminux Unified Theme: Anodized (Obsidian & brushed silver, brass-amber highlight, Fira Code + Nerd Fonts) +theme.name: Anodized +theme.isDark: 1 +theme.fontFace: Fira Code +theme.uiFontFace: Roboto +theme.iconFontFace: DejaVuSansM Nerd Font +theme.baseFontSize: 32 +theme.gtkTheme: Geminux-Anodized +theme.qtTheme: Fusion +theme.iconTheme: Adwaita +*TkTheme: gtkTtk + +Xft.dpi: 192 +Xft.antialias: 1 +Xft.hinting: 1 +Xft.hintstyle: hintslight +Xft.rgba: rgb +Xcursor.theme: default +Xcursor.size: 64 + +theme.bgMain: #08090b +theme.bgBar: #0e1014 +theme.bgHeader: #12151a +theme.bgFooter: #0b0d11 +theme.bgOverlay: #171b22 +theme.bgAltEven: #101318 +theme.bgAltOdd: #14181f +theme.bgInput: #161a21 +theme.bgInputFocus: #1e232c +theme.bgButton: #1c212a +theme.bgSearch: #191e27 +theme.bgBubbleIn: #181d25 +theme.bgBubbleOut: #252c38 +theme.bgToast: #1c222b +theme.fgMain: #e4e8ee +theme.fgBright: #f5f7fa +theme.fgMuted: #89929f +theme.selBg: #38414f +theme.selFg: #f5f7fa +theme.accent: #cfd6e0 +theme.accentAlt: #e5eaf0 +theme.highlight: #e2bc72 +theme.border: #2d3440 +theme.divider: #20252f +theme.success: #79cf9c +theme.info: #9eb3c8 +theme.warning: #e2bc72 +theme.danger: #e07a7a +theme.dangerBg: #3f1d20 + +dwm.borderpx: 4 +dwm.font: Fira Code, DejaVuSansM Nerd Font 38px +dwm.background: #0e1014 +dwm.foreground: #e4e8ee +dwm.border: #2d3440 +dwm.selbackground: #38414f +dwm.selforeground: #f5f7fa +dwm.selborder: #cfd6e0 +dwm.normbgcolor: #0e1014 +dwm.normfgcolor: #e4e8ee +dwm.normbordercolor: #2d3440 +dwm.selbgcolor: #38414f +dwm.selfgcolor: #f5f7fa +dwm.selbordercolor: #cfd6e0 + +dmenu.font: Fira Code, DejaVuSansM Nerd Font 40px +dmenu.background: #12151a +dmenu.foreground: #e4e8ee +dmenu.selbackground: #38414f +dmenu.selforeground: #f5f7fa +dmenu.outbackground: #191e27 +dmenu.outforeground: #cfd6e0 +dmenu.highlight: #e2bc72 + +st.font: Fira Code:pixelsize=44:style=Regular:antialias=true:autohint=true +st.termname: xterm-256color +st.background: #08090b +st.foreground: #e4e8ee +st.cursorColor: #cfd6e0 +st.revCursorColor: #08090b +st.color0: #08090b +st.color1: #d97878 +st.color2: #79cf9c +st.color3: #e2bc72 +st.color4: #8ba6c4 +st.color5: #b39bc8 +st.color6: #84b8be +st.color7: #d5dce4 +st.color8: #5b6370 +st.color9: #eb9494 +st.color10: #96deb3 +st.color11: #edd092 +st.color12: #a6bdd6 +st.color13: #cab5dc +st.color14: #a2cdd2 +st.color15: #f5f7fa diff --git a/overlay/rootfs/usr/bin/geminux-apply-theme b/overlay/rootfs/usr/bin/geminux-apply-theme index 5eaec67..6f86903 100755 --- a/overlay/rootfs/usr/bin/geminux-apply-theme +++ b/overlay/rootfs/usr/bin/geminux-apply-theme @@ -1,27 +1,103 @@ #!/bin/sh -# Apply a Geminux .xth theme across .Xresources, xrdb, dunst, GTK2/3/4, Qt, Tk, dwm, st, and libgemui apps. +# Apply or install a Geminux .xth theme across .Xresources, xrdb, dunst, GTK2/3/4, Qt, Tk, dwm, st, and libgemui apps. set -eu HOME_DIR="${HOME:-/home/user}" THEME_DIR="$HOME_DIR/.xthemes" -TARGET="${1:-}" +USER_THEME_DIR="${XDG_CONFIG_HOME:-$HOME_DIR/.config}/geminux/themes" +INSTALL_SRC="" +INSTALL_NAME="" +TARGET="" + +if [ "${1:-}" = "--install" ]; then + if [ $# -lt 2 ] || [ -z "${2:-}" ]; then + echo "Error: --install requires a .xth file path" >&2 + exit 1 + fi + INSTALL_SRC="$2" + INSTALL_NAME="${3:-}" +else + TARGET="${1:-}" +fi + +sanitize_theme_name() { + printf '%s' "$1" | tr -c 'A-Za-z0-9_-' '_' | sed 's/^_*//; s/_*$//' +} + +if [ -n "$INSTALL_SRC" ]; then + if [ ! -f "$INSTALL_SRC" ] || [ ! -r "$INSTALL_SRC" ]; then + echo "Error: cannot read theme file '$INSTALL_SRC'" >&2 + exit 1 + fi + if ! awk ' + { + s = $0 + gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", s) + if (s == "" || substr(s, 1, 1) == "!" || substr(s, 1, 1) == "#") next + if (index(s, ":") > 1) { ok = 1; exit } + } + END { exit(ok ? 0 : 1) } + ' "$INSTALL_SRC"; then + echo "Error: invalid .xth theme file '$INSTALL_SRC'" >&2 + exit 1 + fi + if [ -z "$INSTALL_NAME" ]; then + INSTALL_NAME="$(awk -F: '/^theme\.name[[:space:]]*:/ { sub(/^[[:space:]]+/, "", $2); sub(/[ \t\r\n]+$/, "", $2); print $2; exit }' "$INSTALL_SRC" || true)" + fi + if [ -z "$INSTALL_NAME" ]; then + INSTALL_NAME="$(basename "$INSTALL_SRC" .xth)" + fi + SAFE_NAME="$(sanitize_theme_name "$INSTALL_NAME")" + if [ -z "$SAFE_NAME" ] || [ "$SAFE_NAME" = "." ] || [ "$SAFE_NAME" = ".." ]; then + echo "Error: invalid target theme name" >&2 + exit 1 + fi + mkdir -p "$USER_THEME_DIR" + DEST_XTH="$USER_THEME_DIR/$SAFE_NAME.xth" + TMP_INST="$DEST_XTH.tmp.$$" + awk -v tname="$SAFE_NAME" ' + BEGIN { had_name = 0 } + /^theme\.name[[:space:]]*:/ { + if (!had_name) { + printf "theme.name: %s\n", tname + had_name = 1 + } + next + } + { print $0 } + END { + if (!had_name) printf "theme.name: %s\n", tname + } + ' "$INSTALL_SRC" > "$TMP_INST" + mv -f "$TMP_INST" "$DEST_XTH" + TARGET="$DEST_XTH" +fi if [ -z "$TARGET" ]; then - if [ -d "$THEME_DIR" ]; then - ls -1 "$THEME_DIR"/*.xth 2>/dev/null | xargs -r -n1 basename | sed 's/\.xth$//' - fi + for _dir in "$USER_THEME_DIR" "$THEME_DIR" "/etc/skel/.xthemes"; do + if [ -d "$_dir" ]; then + ls -1 "$_dir"/*.xth 2>/dev/null || true + fi + done | xargs -r -n1 basename | sed 's/\.xth$//' | awk '!seen[$0]++' | sort exit 0 fi if [ -f "$TARGET" ]; then THEME_FILE="$TARGET" -elif [ -f "$THEME_DIR/$TARGET.xth" ]; then - THEME_FILE="$THEME_DIR/$TARGET.xth" -elif [ -f "/etc/skel/.xthemes/$TARGET.xth" ]; then - THEME_FILE="/etc/skel/.xthemes/$TARGET.xth" +elif [ -f "$TARGET.xth" ]; then + THEME_FILE="$TARGET.xth" else - echo "Error: theme '$TARGET' not found in $THEME_DIR" >&2 - exit 1 + _base="$(basename "$TARGET" .xth)" + if [ -f "$USER_THEME_DIR/$_base.xth" ]; then + THEME_FILE="$USER_THEME_DIR/$_base.xth" + elif [ -f "$THEME_DIR/$_base.xth" ]; then + THEME_FILE="$THEME_DIR/$_base.xth" + elif [ -f "/etc/skel/.xthemes/$_base.xth" ]; then + THEME_FILE="/etc/skel/.xthemes/$_base.xth" + else + echo "Error: theme '$TARGET' not found in $USER_THEME_DIR or $THEME_DIR" >&2 + exit 1 + fi fi cp -f "$THEME_FILE" "$HOME_DIR/.Xresources" @@ -29,7 +105,27 @@ cp -f "$THEME_FILE" "$HOME_DIR/.Xresources" /usr/bin/geminux-sync-gtk-theme --skip-xrdb if [ -n "${DISPLAY:-}" ] && command -v xrdb >/dev/null 2>&1; then - xrdb -nocpp -merge "$HOME_DIR/.Xresources" >/dev/null 2>&1 || true + xrdb -nocpp -load "$HOME_DIR/.Xresources" >/dev/null 2>&1 || true +fi + +if [ -n "${DISPLAY:-}" ] && [ "${GEMINUX_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 == "geminux-statusd" || + cmd == "geminux-themes" || cmd == "geminux-control" || + cmd == "geminux-net" || cmd == "geminux-audio" || + cmd == "geminux-datetime" || cmd == "geminux-lock") { + print "USR1 " 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 # Signal live applications (dwm, st, webarchy, libgemui apps) to reload .Xresources via SIGUSR1 diff --git a/overlay/rootfs/usr/bin/geminux-session b/overlay/rootfs/usr/bin/geminux-session index 6ba1f8d..1d8c136 100755 --- a/overlay/rootfs/usr/bin/geminux-session +++ b/overlay/rootfs/usr/bin/geminux-session @@ -18,10 +18,16 @@ if [ ! -f "$HOME_DIR/.Xresources" ] || \ [ -d /etc/skel/.xthemes ] && rm -rf "$HOME_DIR/.xthemes" && cp -a /etc/skel/.xthemes "$HOME_DIR/.xthemes" elif [ ! -d "$HOME_DIR/.xthemes" ] && [ -d /etc/skel/.xthemes ]; then cp -a /etc/skel/.xthemes "$HOME_DIR/.xthemes" +elif [ -d /etc/skel/.xthemes ]; then + for _xth in /etc/skel/.xthemes/*.xth; do + [ -f "$_xth" ] || continue + _base="$(basename "$_xth")" + [ -f "$HOME_DIR/.xthemes/$_base" ] || cp -f "$_xth" "$HOME_DIR/.xthemes/$_base" + done fi if [ -f "$HOME_DIR/.Xresources" ] && command -v xrdb >/dev/null 2>&1; then - xrdb -merge "$HOME_DIR/.Xresources" 2>/dev/null || true + xrdb -nocpp -load "$HOME_DIR/.Xresources" 2>/dev/null || true fi if command -v xrandr >/dev/null 2>&1; then diff --git a/patches/kernel/0013-gemini-pmic-wake-and-spm-safety.patch b/patches/kernel/0013-gemini-pmic-wake-and-spm-safety.patch new file mode 100644 index 0000000..ca4de17 --- /dev/null +++ b/patches/kernel/0013-gemini-pmic-wake-and-spm-safety.patch @@ -0,0 +1,309 @@ +--- a/include/linux/mfd/mt6397/core.h ++++ b/include/linux/mfd/mt6397/core.h +@@ -8,7 +8,6 @@ + #define __MFD_MT6397_CORE_H__ + + #include +-#include + + enum chip_id { + MT6323_CHIP_ID = 0x23, +@@ -63,7 +62,6 @@ + struct mt6397_chip { + struct device *dev; + struct regmap *regmap; +- struct notifier_block pm_nb; + int irq; + struct irq_domain *irq_domain; + struct mutex irqlock; +@@ -79,5 +77,7 @@ + + int mt6358_irq_init(struct mt6397_chip *chip); + int mt6397_irq_init(struct mt6397_chip *chip); ++int mt6397_irq_suspend(struct mt6397_chip *chip); ++int mt6397_irq_resume(struct mt6397_chip *chip); + + #endif /* __MFD_MT6397_CORE_H__ */ +--- a/drivers/mfd/mt6397-irq.c ++++ b/drivers/mfd/mt6397-irq.c +@@ -8,7 +8,6 @@ + #include + #include + #include +-#include + #include + #include + #include +@@ -131,34 +130,42 @@ + .map = mt6397_irq_domain_map, + }; + +-static int mt6397_irq_pm_notifier(struct notifier_block *notifier, +- unsigned long pm_event, void *unused) ++int mt6397_irq_suspend(struct mt6397_chip *chip) + { +- struct mt6397_chip *chip = +- container_of(notifier, struct mt6397_chip, pm_nb); + unsigned int i; + +- switch (pm_event) { +- case PM_SUSPEND_PREPARE: +- for (i = 0; i < chip->num_irq_regs; i++) +- regmap_write(chip->regmap, chip->int_con[i], +- chip->wake_mask[i]); +- enable_irq_wake(chip->irq); +- break; ++ if (!chip || !chip->num_irq_regs) ++ return 0; + +- case PM_POST_SUSPEND: +- for (i = 0; i < chip->num_irq_regs; i++) +- regmap_write(chip->regmap, chip->int_con[i], +- chip->irq_masks_cur[i]); +- disable_irq_wake(chip->irq); +- break; ++ /* Apply wake_mask in suspend_late after all child .suspend() hooks arm IRQs */ ++ mutex_lock(&chip->irqlock); ++ for (i = 0; i < chip->num_irq_regs; i++) ++ regmap_write(chip->regmap, chip->int_con[i], ++ chip->wake_mask[i]); ++ mutex_unlock(&chip->irqlock); ++ enable_irq_wake(chip->irq); + +- default: +- break; +- } ++ return 0; ++} ++EXPORT_SYMBOL_GPL(mt6397_irq_suspend); + +- return NOTIFY_DONE; ++int mt6397_irq_resume(struct mt6397_chip *chip) ++{ ++ unsigned int i; ++ ++ if (!chip || !chip->num_irq_regs) ++ return 0; ++ ++ disable_irq_wake(chip->irq); ++ mutex_lock(&chip->irqlock); ++ for (i = 0; i < chip->num_irq_regs; i++) ++ regmap_write(chip->regmap, chip->int_con[i], ++ chip->irq_masks_cur[i]); ++ mutex_unlock(&chip->irqlock); ++ ++ return 0; + } ++EXPORT_SYMBOL_GPL(mt6397_irq_resume); + + int mt6397_irq_init(struct mt6397_chip *chip) + { +@@ -220,7 +227,6 @@ + for (i = 0; i < chip->num_irq_regs; i++) + regmap_write(chip->regmap, chip->int_con[i], 0x0); + +- chip->pm_nb.notifier_call = mt6397_irq_pm_notifier; + chip->irq_domain = irq_domain_create_linear(dev_fwnode(chip->dev), + chip->num_irq_regs * 16, + &mt6397_irq_domain_ops, chip); +@@ -239,6 +245,5 @@ + return ret; + } + +- register_pm_notifier(&chip->pm_nb); + return 0; + } +--- a/drivers/mfd/mt6397-core.c ++++ b/drivers/mfd/mt6397-core.c +@@ -10,6 +10,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -512,11 +513,30 @@ + }; + MODULE_DEVICE_TABLE(platform, mt6397_id); + ++static int mt6397_suspend_late(struct device *dev) ++{ ++ struct mt6397_chip *chip = dev_get_drvdata(dev); ++ ++ return mt6397_irq_suspend(chip); ++} ++ ++static int mt6397_resume_early(struct device *dev) ++{ ++ struct mt6397_chip *chip = dev_get_drvdata(dev); ++ ++ return mt6397_irq_resume(chip); ++} ++ ++static const struct dev_pm_ops mt6397_pm_ops = { ++ LATE_SYSTEM_SLEEP_PM_OPS(mt6397_suspend_late, mt6397_resume_early) ++}; ++ + static struct platform_driver mt6397_driver = { + .probe = mt6397_probe, + .driver = { + .name = "mt6397", + .of_match_table = mt6397_of_match, ++ .pm = pm_sleep_ptr(&mt6397_pm_ops), + }, + .id_table = mt6397_id, + }; +--- a/drivers/soc/mediatek/mt6797-spm-sleep.c ++++ b/drivers/soc/mediatek/mt6797-spm-sleep.c +@@ -161,6 +161,7 @@ + #define PCM_FSM_IM_STATE(v) (((v) >> 7) & 7) + /* How long the IM fetch may take before the PCM kick (D5q) */ + #define SODI_IM_WAIT_US 200 ++#define SLEEP_IM_WAIT_US 1000 + #define PCM_RF_SYNC_R0 BIT(16) + #define PCM_RF_SYNC_R7 BIT(23) + #define PCM_PWRIO_R0_R7 0x81 +@@ -179,8 +180,8 @@ + #define S1_FLAGS 0x000902b1 + #define FLAG_EN_SEGMENT2 BIT(18) + +-/* Wake sources: PCM timer and EINT */ +-#define S1_WAKE_SRC (BIT(0) | BIT(6)) ++/* Wake sources: PCM timer, EINT, and PCM watchdog safety wake */ ++#define S1_WAKE_SRC (BIT(0) | BIT(6) | WAKE_PCM_WDT) + + /* + * The vendor's MT6797 SODI wake sources (WAKE_SRC_FOR_SODI, D4): PCM timer, +@@ -410,6 +411,8 @@ + bool im_reuse; /* IM slave mode when the program is resident (D5q) */ + bool r7_vendor; /* r7 starts from SPM_R7_VENDOR (D5r) */ + bool vec_clear; /* PCM_EVENT_VECTOR_EN 0 before the kick (D5r) */ ++ u32 im_wait_us; /* wait budget for IM fetch settle */ ++ u32 backstop_ms; /* CPU0 physical timer backstop margin */ + bool ready; + }; + +@@ -1027,7 +1030,8 @@ + v = PCM_TIMER_EN; + if (sc->pcm_wdt) { + wdt_val = spm_rd(PCM_WDT_VAL); +- spm_wr(PCM_WDT_VAL, sc->ticks + SODI_PCM_WDT_MARGIN); ++ spm_wr(PCM_WDT_VAL, ++ min_t(u64, (u64)sc->ticks + SODI_PCM_WDT_MARGIN, U32_MAX)); + v |= PCM_WDT_BITS; + } + spm_wr(PCM_CON1, spm_rd(PCM_CON1) | SPM_KEY | v); +@@ -1053,26 +1057,31 @@ + spm_wr(SPM_CLK_CON, spm_rd(SPM_CLK_CON) | SPM_LOCK_INFRA_DCM); + + /* D5q: has the IM fetch settled? Refuse the period if not */ +- for (i = 0; ; i++) { +- s.wake.im_fsm1 = spm_rd(PCM_FSM_STA); +- if (!sc->im_wait || i >= SODI_IM_WAIT_US || +- PCM_FSM_IM_STATE(s.wake.im_fsm1) == +- PCM_FSM_IM_STATE(PCM_FSM_STA_DEF)) +- break; +- udelay(1); +- } +- s.wake.im_us = i; +- if (sc->im_wait && i >= SODI_IM_WAIT_US) { +- s.wake.im_stuck = true; +- spm_restore(); +- if (sc->pcm_wdt) { +- spm_wr(PCM_CON1, SPM_KEY | (spm_rd(PCM_CON1) & ~PCM_WDT_BITS) | con1); +- spm_wr(PCM_WDT_VAL, wdt_val); ++ { ++ u32 im_lim = sc->im_wait_us ? sc->im_wait_us : SODI_IM_WAIT_US; ++ ++ for (i = 0; ; i++) { ++ s.wake.im_fsm1 = spm_rd(PCM_FSM_STA); ++ if (!sc->im_wait || i >= im_lim || ++ PCM_FSM_IM_STATE(s.wake.im_fsm1) == ++ PCM_FSM_IM_STATE(PCM_FSM_STA_DEF)) ++ break; ++ udelay(1); ++ } ++ s.wake.im_us = i; ++ if (sc->im_wait && i >= im_lim) { ++ s.wake.im_stuck = true; ++ spm_restore(); ++ if (sc->pcm_wdt) { ++ spm_wr(PCM_CON1, ++ SPM_KEY | (spm_rd(PCM_CON1) & ~PCM_WDT_BITS) | con1); ++ spm_wr(PCM_WDT_VAL, wdt_val); ++ } ++ writel(axi[0], s.mcucfg + MP0_AXI_CONFIG); ++ writel(axi[1], s.mcucfg + MP1_AXI_CONFIG); ++ writel(axi[2], s.mcucfg + MP2_AXI_CONFIG); ++ return -ETIMEDOUT; + } +- writel(axi[0], s.mcucfg + MP0_AXI_CONFIG); +- writel(axi[1], s.mcucfg + MP1_AXI_CONFIG); +- writel(axi[2], s.mcucfg + MP2_AXI_CONFIG); +- return -ETIMEDOUT; + } + + if (sc->vec_clear) +@@ -1111,17 +1120,18 @@ + s.gicd + GICD_ISENABLER + 4 * (SPM_GIC_INTID / 32)); + + /* +- * SODI: CPU0's physical timer is a backstop, 100 ms after the PCM timer +- * should end the period, so a program that never returns leaves CPU0 +- * able to record its state instead of waiting for ever (D5i). Its PPI +- * stays enabled through the GIC mask. ++ * CPU0's physical timer is a backstop after when the PCM timer should ++ * end the period (100 ms for SODI, 5 s for mem suspend), so a program ++ * that never returns leaves CPU0 able to record its state instead of ++ * waiting for ever (D5i). Its PPI stays enabled through the GIC mask. + */ +- if (sc->cirq) { ++ if (sc->backstop_ms) { + cntp_cval = read_sysreg(cntp_cval_el0); + cntp_ctl = read_sysreg(cntp_ctl_el0); + write_sysreg(__arch_counter_get_cntpct() + + mul_u64_u64_div_u64(sc->ticks, arch_timer_get_cntfrq(), 32768) + +- arch_timer_get_cntfrq() / 10, cntp_cval_el0); ++ mul_u64_u64_div_u64(sc->backstop_ms, arch_timer_get_cntfrq(), MSEC_PER_SEC), ++ cntp_cval_el0); + write_sysreg(ARCH_TIMER_CTRL_ENABLE, cntp_ctl_el0); + isb(); + } +@@ -1139,14 +1149,14 @@ + s.im_resident = sc->im_ptr; + break; + } +- if (sc->cirq && (read_sysreg(cntp_ctl_el0) & ARCH_TIMER_CTRL_IT_STAT)) { ++ if (sc->backstop_ms && (read_sysreg(cntp_ctl_el0) & ARCH_TIMER_CTRL_IT_STAT)) { + s.wake.backstop = true; + break; + } + } + if (sc->idle) + ct_cpuidle_exit(); +- if (sc->cirq) { ++ if (sc->backstop_ms) { + write_sysreg(cntp_ctl, cntp_ctl_el0); + write_sysreg(cntp_cval, cntp_cval_el0); + isb(); +@@ -2093,6 +2103,10 @@ + s.sleep.flags = s.flags; + s.sleep.wake_src = S1_WAKE_SRC; + s.sleep.slots = true; ++ s.sleep.pcm_wdt = true; ++ s.sleep.im_wait = true; ++ s.sleep.im_wait_us = SLEEP_IM_WAIT_US; ++ s.sleep.backstop_ms = 5000; + ret = spm_load_program(&s.pdev->dev, SPM_FW_NAME, spm_fw_sha256, 0, &s.sleep); + if (ret) + goto err; +@@ -2102,6 +2116,8 @@ + s.sodi.src2_mask = 0x08ff009f; + s.sodi.wfi_count = 8; + s.sodi.cirq = true; ++ s.sodi.im_wait_us = SODI_IM_WAIT_US; ++ s.sodi.backstop_ms = 100; + s.cirq = ioremap(CIRQ_PHYS, 0x400); + s.afe = ioremap(AFE_PHYS, 0x1000); + np = of_find_compatible_node(NULL, NULL, "mediatek,mt6797-audio"); diff --git a/patches/kernel/series b/patches/kernel/series index 5bed576..df7f3ce 100644 --- a/patches/kernel/series +++ b/patches/kernel/series @@ -10,3 +10,4 @@ 0010-mt6797-ccci-md1-boot-hs-v2-and-rpc.patch 0011-gemini-lid-sync-filter-and-debounce.patch 0012-gemini-lid-wake-and-fg-taper-fix.patch +0013-gemini-pmic-wake-and-spm-safety.patch diff --git a/prebuilt/geminux/usr/bin/geminux-camera b/prebuilt/geminux/usr/bin/geminux-camera index 1d2daa4..98d0852 100755 Binary files a/prebuilt/geminux/usr/bin/geminux-camera and b/prebuilt/geminux/usr/bin/geminux-camera differ diff --git a/prebuilt/geminux/usr/bin/geminux-themes b/prebuilt/geminux/usr/bin/geminux-themes index 64df8f6..5958bb4 100755 Binary files a/prebuilt/geminux/usr/bin/geminux-themes and b/prebuilt/geminux/usr/bin/geminux-themes differ diff --git a/prebuilt/geminux/usr/include/gemui.h b/prebuilt/geminux/usr/include/gemui.h index 5fd95dd..6e18405 100644 --- a/prebuilt/geminux/usr/include/gemui.h +++ b/prebuilt/geminux/usr/include/gemui.h @@ -26,7 +26,7 @@ extern "C" { #define GEMUI_PTR_SCROLL_UP 3 #define GEMUI_PTR_SCROLL_DOWN 4 -#define GEMUI_MAX_HITS 192 +#define GEMUI_MAX_HITS 256 #define GEMUI_MAX_FDS 16 typedef struct { @@ -115,6 +115,7 @@ 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); +bool gemui_clipboard_get(gemui_app_t *app, char *out, size_t out_sz); int gemui_scale_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); diff --git a/prebuilt/geminux/usr/lib/libgemui.so b/prebuilt/geminux/usr/lib/libgemui.so index 599de9b..41ce05d 100755 Binary files a/prebuilt/geminux/usr/lib/libgemui.so and b/prebuilt/geminux/usr/lib/libgemui.so differ diff --git a/prebuilt/geminux/usr/sbin/geminux-powerd b/prebuilt/geminux/usr/sbin/geminux-powerd index 3f17098..ca073bb 100755 Binary files a/prebuilt/geminux/usr/sbin/geminux-powerd and b/prebuilt/geminux/usr/sbin/geminux-powerd differ diff --git a/prebuilt/kernel/boot/Image.gz b/prebuilt/kernel/boot/Image.gz index 6f12bcb..0bba978 100644 Binary files a/prebuilt/kernel/boot/Image.gz and b/prebuilt/kernel/boot/Image.gz differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-spm-sleep.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-spm-sleep.ko.zst index 3b4bbab..08db4ed 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-spm-sleep.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/soc/mediatek/mt6797-spm-sleep.ko.zst differ diff --git a/prebuilt/suckless/usr/bin/dmenu b/prebuilt/suckless/usr/bin/dmenu index 23eede0..acf916d 100755 Binary files a/prebuilt/suckless/usr/bin/dmenu and b/prebuilt/suckless/usr/bin/dmenu differ diff --git a/prebuilt/suckless/usr/bin/dwm b/prebuilt/suckless/usr/bin/dwm index 4ba7aa3..cf01f15 100755 Binary files a/prebuilt/suckless/usr/bin/dwm and b/prebuilt/suckless/usr/bin/dwm differ diff --git a/prebuilt/suckless/usr/bin/st b/prebuilt/suckless/usr/bin/st index 3c13f27..bfdfe53 100755 Binary files a/prebuilt/suckless/usr/bin/st and b/prebuilt/suckless/usr/bin/st differ diff --git a/scripts/package-local-apks.sh b/scripts/package-local-apks.sh index 96622b0..93e0d21 100755 --- a/scripts/package-local-apks.sh +++ b/scripts/package-local-apks.sh @@ -306,7 +306,7 @@ for rel in ("etc/os-release", "usr/lib/os-release", "etc/issue", "etc/motd"): f.write(txt) make_pkg( "geminux-config", pkg_ver, - "Geminux system configs, OpenRC units, ALSA UCM2, XKB layout, 21 themes, and udev/power rules", + "Geminux system configs, OpenRC units, ALSA UCM2, XKB layout, 22 themes, and udev/power rules", cstage, depends=[ f"geminux-kernel-modules=7.3.5-r0", diff --git a/scripts/test-power-policy.py b/scripts/test-power-policy.py index ba4a13e..9fd0457 100755 --- a/scripts/test-power-policy.py +++ b/scripts/test-power-policy.py @@ -683,6 +683,7 @@ def main(): os.path.join(BASE_DIR, "patches", "kernel", "series"): ( "0009-mt6797-wlan-drop-free-stability.patch", "0012-gemini-lid-wake-and-fg-taper-fix.patch", + "0013-gemini-pmic-wake-and-spm-safety.patch", ), os.path.join(overlay_dir, "etc", "profile.d", "10-geminux-env.sh"): ( "export NO_AT_BRIDGE=1", diff --git a/scripts/test-theme-dunst-sync.py b/scripts/test-theme-dunst-sync.py index b12b220..32dd532 100755 --- a/scripts/test-theme-dunst-sync.py +++ b/scripts/test-theme-dunst-sync.py @@ -42,7 +42,8 @@ def parse_xres(path): def main(): themes = sorted(glob.glob(os.path.join(THEMES_DIR, "*.xth"))) - assert len(themes) >= 20, f"Expected >= 20 themes, found {len(themes)}" + assert len(themes) >= 22, f"Expected >= 22 themes, found {len(themes)}" + assert any(os.path.basename(th) == "Anodized.xth" for th in themes), "Missing Anodized.xth" with tempfile.TemporaryDirectory(prefix="geminux-dunst-test-") as tmp: for idx, th in enumerate(themes): @@ -224,7 +225,62 @@ def main(): first_name = f"Geminux-{parse_xres(themes[0])['theme.name']}" assert f"color_scheme_path=/home/user/.config/qt6ct/colors/{first_name}.conf" in skel_qt - print(f"[PASS] Verified {len(themes)} .xth themes, dunst synchronization, and GTK2/3/4/Qt/Tk theme generation") + xth_hdr = os.path.join(BASE_DIR, "src", "geminux-apps", "geminux-xth.h") + xth_c = os.path.join(tmp, "test_xth.c") + xth_bin = os.path.join(tmp, "test_xth") + xth_out = os.path.join(tmp, "Custom_Test.xth") + imp_dir = os.path.join(tmp, "imp_themes") + os.makedirs(imp_dir, exist_ok=True) + with open(xth_c, "w", encoding="utf-8") as cf: + cf.write( + '#include \n' + '#include \n' + '#include \n' + f'#include "{xth_hdr}"\n' + 'int main(void) {\n' + ' geminux_xth_t x, y;\n' + ' geminux_xth_init_anodized(&x);\n' + ' assert(x.base_font_size == 32 && x.dwm_borderpx == 4 && x.is_dark == 1);\n' + ' assert(strcmp(x.name, "Anodized") == 0);\n' + ' snprintf(x.name, sizeof(x.name), "Custom Test");\n' + ' snprintf(x.colors[GEMINUX_XTH_BG_BAR], 16, "#112233");\n' + ' geminux_xth_sync_derived(&x);\n' + ' assert(strcmp(x.colors[GEMINUX_XTH_DWM_NORM_BG], "#112233") == 0);\n' + ' assert(geminux_xth_contrast_ratio("#ffffff", "#000000") > 20.0);\n' + ' char clean[64];\n' + ' geminux_xth_sanitize_name(" My Theme..!! ", clean, sizeof(clean));\n' + ' assert(strcmp(clean, "My_Theme") == 0);\n' + f' assert(geminux_xth_save_file("{xth_out}", &x));\n' + f' assert(geminux_xth_load_file("{xth_out}", &y));\n' + ' assert(y.base_font_size == 32 && y.dwm_borderpx == 4);\n' + ' assert(strcmp(y.name, "Custom_Test") == 0);\n' + ' assert(strcmp(y.colors[GEMINUX_XTH_DWM_NORM_BG], "#112233") == 0);\n' + ' char dest[600];\n' + f' assert(geminux_xth_import_file("{xth_out}", "{imp_dir}", "Imported One", dest, sizeof(dest)));\n' + ' geminux_xth_t z;\n' + ' assert(geminux_xth_load_file(dest, &z));\n' + ' assert(strcmp(z.name, "Imported_One") == 0);\n' + ' return 0;\n' + '}\n' + ) + subprocess.run(["cc", "-std=gnu99", "-Wall", "-Wextra", "-Werror", xth_c, "-o", xth_bin, "-lm"], check=True) + subprocess.run([xth_bin], check=True) + + saved_vals = parse_xres(xth_out) + assert saved_vals.get("Xft.dpi") == "192" + assert saved_vals.get("Xcursor.size") == "64" + assert saved_vals.get("dwm.borderpx") == "4" + assert saved_vals.get("dwm.normbgcolor") == "#112233" + xth_home = os.path.join(tmp, "xth_home") + os.makedirs(xth_home, exist_ok=True) + xth_dunstrc = os.path.join(tmp, "Custom_Test.dunstrc") + xth_env = dict(gtk_env, HOME=xth_home, GEMINUX_XRESOURCES=xth_out, GEMINUX_DUNSTRC=xth_dunstrc) + subprocess.run([SYNC_SCRIPT, "--no-restart"], env=xth_env, check=True) + subprocess.run([GTK_SYNC_SCRIPT, "--no-reload"], env=xth_env, check=True) + assert os.path.isfile(xth_dunstrc) + assert os.path.isfile(os.path.join(xth_home, ".themes/Geminux-Custom_Test/gtk-3.0/gtk.css")) + + print(f"[PASS] Verified {len(themes)} .xth themes, geminux-xth.h, dunst synchronization, and GTK2/3/4/Qt/Tk theme generation") return 0 diff --git a/src/dmenu/drw.c b/src/dmenu/drw.c index 0a7a653..e91910c 100644 --- a/src/dmenu/drw.c +++ b/src/dmenu/drw.c @@ -116,6 +116,8 @@ void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled 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 orig_x = x; + unsigned int orig_w = w; int ty, render = x || y || w || h; unsigned int ew, eh; XftDraw *d = NULL; @@ -132,7 +134,7 @@ int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, DefaultVisual(drw->dpy, drw->screen), DefaultColormap(drw->dpy, drw->screen)); x += (int)lpad; - if (w > lpad) w -= lpad; + w = (w > lpad) ? (w - lpad) : 0; } size_t len = strlen(text); @@ -149,6 +151,10 @@ int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, buf[len] = '\0'; drw_font_getexts(drw->fonts, buf, (unsigned int)len, &ew, &eh); } + if (ew > w) { + len = 0; + buf[0] = '\0'; + } if (render && d) { pango_layout_set_text(drw->fonts->layout, buf, -1); ty = y + (int)(h - eh) / 2; @@ -160,7 +166,7 @@ int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, } if (d) XftDrawDestroy(d); - return x + (render ? (int)w : 0); + return render ? (orig_x + (int)orig_w) : x; } int drw_text_align(Drw *drw, int x, int y, unsigned int w, unsigned int h, diff --git a/src/dwm/drw.c b/src/dwm/drw.c index 2b3cd21..862610e 100644 --- a/src/dwm/drw.c +++ b/src/dwm/drw.c @@ -111,6 +111,8 @@ void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled 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 orig_x = x; + unsigned int orig_w = w; int ty, render = x || y || w || h; unsigned int ew, eh; XftDraw *d = NULL; @@ -127,7 +129,7 @@ int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, DefaultVisual(drw->dpy, drw->screen), DefaultColormap(drw->dpy, drw->screen)); x += (int)lpad; - if (w > lpad) w -= lpad; + w = (w > lpad) ? (w - lpad) : 0; } size_t len = strlen(text); @@ -144,6 +146,10 @@ int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, buf[len] = '\0'; drw_font_getexts(drw->font, buf, (unsigned int)len, &ew, &eh, markup); } + if (ew > w) { + len = 0; + buf[0] = '\0'; + } if (render && d) { if (markup) @@ -161,7 +167,7 @@ int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, } if (d) XftDrawDestroy(d); - return x + (render ? (int)w : 0); + return render ? (orig_x + (int)orig_w) : x; } void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h) { diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c index 362a6a8..b949cea 100644 --- a/src/dwm/dwm.c +++ b/src/dwm/dwm.c @@ -1,7 +1,8 @@ /* See LICENSE file for copyright and license details. */ -/* Geminux DWM - Pango/HarfBuzz + Systray + .Xresources + SIGUSR1 + HiDPI Touch + Gemini Mod4 */ +/* Geminux DWM - Pango/HarfBuzz + Systray + EWMH Struts + .Xresources + SIGUSR1 + HiDPI Touch + Gemini Mod4 */ #include #include +#include #include #include #include @@ -44,10 +45,10 @@ #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_WINDOW_ACTIVATE_BIT 1 #define XEMBED_EMBEDDED_VERSION 0 #define VERSION_MAJOR 0 #define VERSION_MINOR 0 @@ -60,10 +61,14 @@ enum { CurNormal, CurResize, CurMove, CurLast }; enum { SchemeNorm, SchemeSel }; enum { NetSupported, NetWMName, NetWMState, NetWMCheck, NetSystemTray, NetSystemTrayOP, NetSystemTrayOrientation, - NetSystemTrayOrientationHorz, NetWMFullscreen, NetActiveWindow, - NetWMWindowType, NetWMWindowTypeDialog, NetClientList, NetLast }; + NetSystemTrayOrientationHorz, NetSystemTrayVisual, + NetWMFullscreen, NetWMFocused, NetWMStateSticky, NetWMStateAbove, NetWMStateHidden, + NetActiveWindow, NetWorkarea, + NetNumberOfDesktops, NetCurrentDesktop, NetDesktopNames, NetWMDesktop, + NetWMWindowType, NetWMWindowTypeDialog, NetWMWindowTypeDock, + NetWMStrutPartial, NetWMStrut, NetClientList, NetWMPid, NetLast }; enum { Manager, Xembed, XembedInfo, XLast }; -enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; +enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMChangeState, WMLast }; enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkLauncher, ClkCloseBtn, ClkClientWin, ClkRootWin, ClkLast }; @@ -92,7 +97,7 @@ struct Client { int basew, baseh, incw, inch, maxw, maxh, minw, minh, hintsvalid; int bw, oldbw; unsigned int tags; - int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen; + int isfixed, isfloating, isurgent, neverfocus, oldstate, isfullscreen, isiconic; Client *next; Client *snext; Monitor *mon; @@ -145,9 +150,21 @@ 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 addwmstate(Client *c, Atom state); 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); @@ -163,32 +180,43 @@ static void configure(Client *c); static void configurenotify(XEvent *e); static void configurerequest(XEvent *e); static Monitor *createmon(void); +static unsigned int desktop_to_tags(unsigned long d); static void destroynotify(XEvent *e); static void detach(Client *c); static void detachstack(Client *c); static Monitor *dirtomon(int dir); +static void dockadd(Window w); +static int dockremove(Window w); +static void dockupdate(Window w); static void drawbar(Monitor *m); static void drawbars(void); static void enternotify(XEvent *e); static void expose(XEvent *e); +static int extracteventtime(const XEvent *e, Time *out); static void focus(Client *c); +static void focusarranged(Monitor *m); 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 Time getfocustime(void); static int getrootptr(int *x, int *y); +static Time getservertime(Window w); static long getstate(Window w); static unsigned int getsystraywidth(void); static int gettextprop(Window w, Atom atom, char *text, unsigned int size); +static int getxembedflags(Window w, long *flags_out); static void grabbuttons(Client *c, int focused); static void grabkeys(void); static void grid(Monitor *m); +static int hasatomprop(Client *c, Atom prop, Atom target); static void incnmaster(const Arg *arg); +static int isdockwin(Window w); 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 mapnotify(XEvent *e); static void mappingnotify(XEvent *e); static void maprequest(XEvent *e); static void monocle(Monitor *m); @@ -198,10 +226,18 @@ static Client *nexttiled(Client *c); static unsigned long long now_ms(void); static void pop(Client *c); static void propertynotify(XEvent *e); +static void publish_desktop_names(void); static void quit(const Arg *arg); +static unsigned long read_cardinal_prop(Window w, Atom prop, unsigned long *out, unsigned long max_items); +static unsigned long readatomlist(Client *c, Atom prop, Atom *out, unsigned long max_atoms); +static void readdocks_strut(Window w, unsigned long strut[12]); +static void recalcworkareas(void); static Monitor *recttomon(int x, int y, int w, int h); +static void refreshwmstate(Client *c); static void reloadxres(const Arg *arg); static void removesystrayicon(Client *i); +static void removewmstate(Client *c, Atom state); +static void reparentnotify(XEvent *e); 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); @@ -217,16 +253,22 @@ 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 setnofocus(void); 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 sigterm_handler(int sig); static void sigusr1_handler(int sig); static void spawn(const Arg *arg); +static void sync_client_props(Client *c); +static void sync_root_desktop_props(void); +static unsigned long systray_bg_pixel(void); static Monitor *systraytomon(Monitor *m); static void tag(const Arg *arg); static void tagmon(const Arg *arg); +static unsigned long tags_to_desktop(unsigned int t); static void tile(Monitor *m); static void togglebar(const Arg *arg); static void togglefloating(const Arg *arg); @@ -248,6 +290,7 @@ static void updatesystrayiconstate(Client *i, XPropertyEvent *ev); static void updatetitle(Client *c); static void updatewindowtype(Client *c); static void updatewmhints(Client *c); +static void updateworkarea(void); static void view(const Arg *arg); static Client *wintoclient(Window w); static Monitor *wintomon(Window w); @@ -259,6 +302,7 @@ 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] = ""; @@ -287,14 +331,17 @@ static void (*handler[LASTEvent])(XEvent *) = { [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 Atom utf8string = None; static int running = 1; static Cur *cursor[CurLast]; static Clr **scheme; @@ -302,7 +349,8 @@ static Display *dpy; static Drw *drw; static Fnt *dwmfont = NULL; static Monitor *mons, *selmon; -static Window root, wmcheckwin; +static Window root, wmcheckwin, nofocuswin = None; +static Time last_event_time = CurrentTime; #include "config.h" @@ -399,7 +447,7 @@ static void arrange(Monitor *m) { } static void arrangemon(Monitor *m) { - strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof m->ltsymbol); + snprintf(m->ltsymbol, sizeof m->ltsymbol, "%s", m->lt[m->sellt]->symbol); if (m->lt[m->sellt]->arrange) m->lt[m->sellt]->arrange(m); } @@ -428,7 +476,8 @@ static void buttonpress(XEvent *e) { focus(NULL); } if (ev->window == selmon->barwin) { - int stw = getsystraywidth(); + int stw = (showsystray && selmon == systraytomon(selmon) && !systrayonleft) + ? (int)getsystraywidth() : 0; int tw = (int)TEXTW(stext) - lrpad + 4; if (ev->x < LAUNCHER_W) { click = ClkLauncher; @@ -495,17 +544,31 @@ static void cleanup(void) { } 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); + XSelectInput(dpy, root, 0); + XDeleteProperty(dpy, root, netatom[NetWMCheck]); + XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime); + if (nofocuswin != None) { + XDestroyWindow(dpy, nofocuswin); + nofocuswin = None; + } XDestroyWindow(dpy, wmcheckwin); + wmcheckwin = None; drw_free(drw); XSync(dpy, False); - XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime); XDeleteProperty(dpy, root, netatom[NetActiveWindow]); } @@ -530,54 +593,101 @@ static void clientmessage(XEvent *e) { 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]; + long flags = 0; + if (!iw || wintosystrayicon(iw)) + return; + if (!XGetWindowAttributes(dpy, iw, &wa)) + return; if (!(c = (Client *)calloc(1, sizeof(Client)))) die("fatal: could not malloc() %zu bytes\n", sizeof(Client)); - if (!(c->win = (Window)cme->data.l[2])) { - free(c); - return; - } - c->mon = selmon; + 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; - } 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; - c->tags = 1; + XAddToSaveSet(dpy, c->win); + XReparentWindow(dpy, c->win, systray->win, 0, 0); + XSelectInput(dpy, c->win, StructureNotifyMask | SubstructureNotifyMask | PropertyChangeMask | ResizeRedirectMask); + 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 | PropertyChangeMask | ResizeRedirectMask); - XReparentWindow(dpy, c->win, systray->win, 0, 0); - swa.background_pixel = scheme[SchemeNorm][ColBg].pixel; - XChangeWindowAttributes(dpy, c->win, CWBackPixel, &swa); + 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 { + XUnmapWindow(dpy, c->win); + setclientstate(c, WithdrawnState); + } XSync(dpy, False); - resizebarwin(selmon); - updatesystray(0); - setclientstate(c, NormalState); + updatesystray(1); + drawbars(); } return; } + if (cme->window == root && cme->message_type == netatom[NetCurrentDesktop]) { + Arg a = {.ui = desktop_to_tags((unsigned long)cme->data.l[0])}; + view(&a); + return; + } + if (!c) return; + if (cme->message_type == netatom[NetWMDesktop]) { + c->tags = desktop_to_tags((unsigned long)cme->data.l[0]); + sync_client_props(c); + focusarranged(c->mon); + return; + } if (cme->message_type == netatom[NetWMState]) { + int was_fs = c->isfullscreen; if ((Atom)cme->data.l[1] == netatom[NetWMFullscreen] || (Atom)cme->data.l[2] == netatom[NetWMFullscreen]) { setfullscreen(c, (cme->data.l[0] == 1 || (cme->data.l[0] == 2 && !c->isfullscreen))); } + if (c->isfullscreen == was_fs) + refreshwmstate(c); + } else if (cme->message_type == wmatom[WMChangeState]) { + if (cme->data.l[0] == IconicState) { + if (!ISVISIBLE(c)) { + c->isiconic = 1; + setclientstate(c, IconicState); + } else { + c->isiconic = 0; + setclientstate(c, NormalState); + } + } else if (cme->data.l[0] == NormalState && c->isiconic) { + c->isiconic = 0; + setclientstate(c, NormalState); + } } else if (cme->message_type == netatom[NetActiveWindow]) { - if (c != selmon->sel && !c->isurgent) + if (ISVISIBLE(c) && c->mon == selmon) { + if (c->isiconic) { + c->isiconic = 0; + setclientstate(c, NormalState); + } + if (c != selmon->sel) + focus(c); + else + setfocus(c); + restack(selmon); + } else if (c != selmon->sel && !c->isurgent) { seturgent(c, 1); + } } } @@ -611,13 +721,31 @@ static void configurenotify(XEvent *e) { 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); + for (c = m->clients; c; c = c->next) { + if (c->isfullscreen) { + if (ISVISIBLE(c)) { + resizeclient(c, m->mx, m->my, m->mw, m->mh); + } else { + c->oldx = c->x; c->oldy = c->y; + c->oldw = c->w; c->oldh = c->h; + c->x = m->mx; c->y = m->my; + c->w = m->mw; c->h = m->mh; + } + } else if (c->isfloating) { + if (c->x + c->w > m->wx + m->ww) c->x = m->wx + MAX(0, m->ww - WIDTH(c)); + if (c->y + c->h > m->wy + m->wh) c->y = m->wy + MAX(0, m->wh - HEIGHT(c)); + if (c->x < m->wx) c->x = m->wx; + if (c->y < m->wy) c->y = m->wy; + } + } resizebarwin(m); } - updatesystray(0); - focus(NULL); + updatesystray(1); + updateworkarea(); arrange(NULL); + for (m = mons; m; m = m->next) + restack(m); + focus(NULL); } } } @@ -629,9 +757,13 @@ static void configurerequest(XEvent *e) { XWindowChanges wc; if ((c = wintoclient(ev->window))) { - if (ev->value_mask & CWBorderWidth) + if (c->isfullscreen) { + configure(c); + } else if (ev->value_mask & CWBorderWidth) { c->bw = ev->border_width; - else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) { + configure(c); + } else if (c->isfloating || !selmon->lt[selmon->sellt]->arrange) { + int ox = c->x, oy = c->y, ow = c->w, oh = c->h; m = c->mon; if (ev->value_mask & CWX) { c->oldx = c->x; c->x = m->mx + ev->x; } if (ev->value_mask & CWY) { c->oldy = c->y; c->y = m->my + ev->y; } @@ -641,10 +773,13 @@ static void configurerequest(XEvent *e) { 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)) + if (ISVISIBLE(c) && (c->x != ox || c->y != oy || c->w != ow || c->h != oh)) { XMoveResizeWindow(dpy, c->win, c->x, c->y, (unsigned int)c->w, (unsigned int)c->h); + if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight))) + configure(c); + } else { + configure(c); + } } else { configure(c); } @@ -681,8 +816,10 @@ static void destroynotify(XEvent *e) { unmanage(c, 1); else if ((c = wintosystrayicon(ev->window))) { removesystrayicon(c); - resizebarwin(selmon); - updatesystray(0); + updatesystray(1); + drawbars(); + } else if (dockremove(ev->window)) { + recalcworkareas(); } } @@ -726,6 +863,9 @@ static void drawbar(Monitor *m) { if (showsystray && m == systraytomon(m) && !systrayonleft) stw = (int)getsystraywidth(); + drw_setscheme(drw, scheme[SchemeNorm]); + drw_rect(drw, 0, 0, (unsigned int)m->ww, (unsigned int)bh, 1, 1); + if (m == selmon) { drw_setscheme(drw, scheme[SchemeNorm]); tw = (int)TEXTW(stext) - lrpad / 2 + 2; @@ -793,8 +933,14 @@ static void enternotify(XEvent *e) { 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; } @@ -822,19 +968,51 @@ static void focus(Client *c) { attachstack(c); grabbuttons(c, 1); XSetWindowBorder(dpy, c->win, scheme[SchemeSel][ColBorder].pixel); + addwmstate(c, netatom[NetWMFocused]); setfocus(c); } else { - XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime); - XDeleteProperty(dpy, root, netatom[NetActiveWindow]); + Window none = None; + setnofocus(); + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&none, 1); } selmon->sel = c; drawbars(); } +static void focusarranged(Monitor *m) { + Client *c; + if (!m) m = selmon; + for (c = m->stack; c && !ISVISIBLE(c); c = c->snext) ; + if (m->sel && m->sel != c) + unfocus(m->sel, (m == selmon && !c) ? 1 : 0); + if (m == selmon) { + if (m->sel != c) + setnofocus(); + XUngrabKeyboard(dpy, CurrentTime); + } + m->sel = c; + if (c) { + detachstack(c); + attachstack(c); + } + arrange(m); + if (m == selmon) + focus(c); + else + drawbar(m); +} + static void focusin(XEvent *e) { + Client *c; XFocusChangeEvent *ev = &e->xfocus; if (ev->mode == NotifyGrab || ev->mode == NotifyWhileGrabbed) return; + if (ev->detail == NotifyPointer || ev->detail == NotifyInferior || + ev->detail == NotifyDetailNone || ev->window == root) + return; + if (!(c = wintoclient(ev->window)) || !ISVISIBLE(c)) + return; if (selmon->sel && ev->window != selmon->sel->win) setfocus(selmon->sel); } @@ -843,8 +1021,16 @@ 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); + setnofocus(); + XUngrabKeyboard(dpy, CurrentTime); selmon = m; + if (showsystray && !systraypinning) { + resizebarwin(oldm); + resizebarwin(m); + updatesystray(1); + } focus(NULL); } @@ -864,22 +1050,183 @@ static void focusstack(const Arg *arg) { if (ISVISIBLE(i)) c = i; } if (c) { + if (c != selmon->sel) + setnofocus(); + XUngrabKeyboard(dpy, CurrentTime); focus(c); restack(selmon); } } -static Atom getatomprop(Client *c, Atom prop) { +static int extracteventtime(const XEvent *e, Time *out) { + switch (e->type) { + case KeyPress: + case KeyRelease: *out = e->xkey.time; return 1; + case ButtonPress: + case ButtonRelease: *out = e->xbutton.time; return 1; + case MotionNotify: *out = e->xmotion.time; return 1; + case EnterNotify: + case LeaveNotify: *out = e->xcrossing.time; return 1; + case PropertyNotify: *out = e->xproperty.time; return 1; + case SelectionClear: *out = e->xselectionclear.time; return 1; + default: return 0; + } +} + +static Time getservertime(Window w) { + XEvent ev; + XSelectInput(dpy, w, PropertyChangeMask); + XChangeProperty(dpy, w, netatom[NetWMName], utf8string, 8, + PropModeAppend, (unsigned char *)"", 0); + XWindowEvent(dpy, w, PropertyChangeMask, &ev); + XSelectInput(dpy, w, 0); + return ev.xproperty.time; +} + +static Time getfocustime(void) { + if (wmcheckwin != None) { + Time t = getservertime(wmcheckwin); + if (t != CurrentTime) + last_event_time = t; + } + return last_event_time; +} + +static unsigned long read_cardinal_prop(Window w, Atom prop, unsigned long *out, unsigned long max_items) { int di; - unsigned long dl; + unsigned long dl, n = 0, copied = 0; 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; + Atom da = None; + if (!dpy || w == None || prop == None || !out || max_items == 0) + return 0; + if (XGetWindowProperty(dpy, w, prop, 0L, (long)max_items, False, AnyPropertyType, + &da, &di, &n, &dl, &p) == Success && p) { + if (di == 32 && n > 0) { + unsigned long *vals = (unsigned long *)p; + copied = MIN(n, max_items); + for (unsigned long i = 0; i < copied; i++) + out[i] = vals[i]; + } XFree(p); } - return atom; + return copied; +} + +static unsigned long tags_to_desktop(unsigned int t) { + if ((t & TAGMASK) == TAGMASK) return 0xFFFFFFFFUL; + for (unsigned int i = 0; i < LENGTH(tags); i++) { + if (t & (1U << i)) return (unsigned long)i; + } + return 0UL; +} + +static unsigned int desktop_to_tags(unsigned long d) { + if ((uint32_t)d == 0xFFFFFFFFU) return TAGMASK; + if (d >= LENGTH(tags)) d = LENGTH(tags) - 1; + return 1U << d; +} + +static void sync_client_props(Client *c) { + if (!dpy || !c) return; + if (netatom[NetWMDesktop] != None) { + unsigned long desk = tags_to_desktop(c->tags); + XChangeProperty(dpy, c->win, netatom[NetWMDesktop], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&desk, 1); + } +} + +static void sync_root_desktop_props(void) { + if (!dpy || !selmon) return; + if (netatom[NetNumberOfDesktops] != None) { + unsigned long ndesk = (unsigned long)LENGTH(tags); + XChangeProperty(dpy, root, netatom[NetNumberOfDesktops], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&ndesk, 1); + } + if (netatom[NetCurrentDesktop] != None) { + unsigned long cur = tags_to_desktop(selmon->tagset[selmon->seltags] & TAGMASK); + if ((uint32_t)cur == 0xFFFFFFFFU) cur = 0UL; + XChangeProperty(dpy, root, netatom[NetCurrentDesktop], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&cur, 1); + } +} + +static void publish_desktop_names(void) { + if (!dpy || netatom[NetDesktopNames] == None || utf8string == None) return; + char buf[256]; + size_t pos = 0; + for (unsigned int i = 0; i < LENGTH(tags); i++) { + size_t tl = strlen(tags[i]); + if (pos + tl + 1 >= sizeof(buf)) break; + memcpy(buf + pos, tags[i], tl + 1); + pos += tl + 1; + } + XChangeProperty(dpy, root, netatom[NetDesktopNames], utf8string, 8, + PropModeReplace, (unsigned char *)buf, (int)pos); +} + +static unsigned long readatomlist(Client *c, Atom prop, Atom *out, unsigned long max_atoms) { + int di; + unsigned long dl, n = 0, copied = 0; + unsigned char *p = NULL; + Atom da = None; + if (XGetWindowProperty(dpy, c->win, prop, 0L, (long)max_atoms, False, XA_ATOM, + &da, &di, &n, &dl, &p) == Success && p) { + if (di == 32 && da == XA_ATOM) { + Atom *atoms = (Atom *)p; + copied = MIN(n, max_atoms); + for (unsigned long i = 0; i < copied; i++) + out[i] = atoms[i]; + } + XFree(p); + } + return copied; +} + +static int hasatomprop(Client *c, Atom prop, Atom target) { + Atom atoms[64]; + unsigned long n = readatomlist(c, prop, atoms, LENGTH(atoms)); + for (unsigned long i = 0; i < n; i++) + if (atoms[i] == target) + return 1; + return 0; +} + +static void addwmstate(Client *c, Atom state) { + Atom atoms[64]; + unsigned long n = readatomlist(c, netatom[NetWMState], atoms, LENGTH(atoms) - 1); + for (unsigned long i = 0; i < n; i++) + if (atoms[i] == state) + return; + atoms[n++] = state; + XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, + PropModeReplace, (unsigned char *)atoms, (int)n); +} + +static void removewmstate(Client *c, Atom state) { + Atom atoms[64], out[64]; + unsigned long n = readatomlist(c, netatom[NetWMState], atoms, LENGTH(atoms)); + unsigned long m = 0; + int removed = 0; + for (unsigned long i = 0; i < n; i++) { + if (atoms[i] == state) + removed = 1; + else + out[m++] = atoms[i]; + } + if (!removed) + return; + if (m > 0) + XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, + PropModeReplace, (unsigned char *)out, (int)m); + else + XDeleteProperty(dpy, c->win, netatom[NetWMState]); +} + +static void refreshwmstate(Client *c) { + Atom atoms[64]; + unsigned long n = readatomlist(c, netatom[NetWMState], atoms, LENGTH(atoms)); + XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, + PropModeReplace, (unsigned char *)atoms, (int)n); } static int getrootptr(int *x, int *y) { @@ -907,7 +1254,8 @@ static unsigned int getsystraywidth(void) { unsigned int w = 0; Client *i; if (showsystray && systray) { - for (i = systray->icons; i; w += (unsigned int)i->w + systrayspacing, i = i->next) ; + for (i = systray->icons; i; i = i->next) + if (i->tags) w += (unsigned int)i->w + systrayspacing; } return w ? w + systrayspacing : 0; } @@ -961,14 +1309,14 @@ static void grabkeys(void) { XUngrabKey(dpy, AnyKey, AnyModifier, root); - /* Monitor Super_L (Fn+Alt) for comfortable one-shot tap-latch fallback */ + /* Monitor Super_L (Fn+Alt) for comfortable one-shot tap-latch fallback without freezing pointer */ 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); + XGrabKey(dpy, super_kc, modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod1Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); + XGrabKey(dpy, super_kc, Mod1Mask | Mod5Mask | modifiers[j], root, True, GrabModeAsync, GrabModeAsync); } } @@ -1052,7 +1400,6 @@ static void keypress(XEvent *e) { super_down = 1; super_dirty = 0; super_down_ms = t; - XAllowEvents(dpy, ReplayKeyboard, ev->time); return; } @@ -1091,7 +1438,12 @@ static void keypress(XEvent *e) { matched = 1; } if (matched && keys[i].func) { + if (super_down) { + super_down = 0; + super_dirty = 1; + } keys[i].func(&(keys[i].arg)); + XUngrabKeyboard(dpy, CurrentTime); return; } } @@ -1144,15 +1496,66 @@ static const char *xrm_lookup(XrmDatabase db, const char *k1, const char *k2, co return NULL; } +static int xres_defaults_saved = 0; +static char def_font[256]; +static char def_normbgcolor[64], def_normfgcolor[64], def_normbordercolor[64]; +static char def_selbgcolor[64], def_selfgcolor[64], def_selbordercolor[64]; +static unsigned int def_borderpx; + static void loadxres(void) { + if (!xres_defaults_saved) { + snprintf(def_font, sizeof(def_font), "%s", font ? font : "Fira Code 32px"); + snprintf(def_normbgcolor, sizeof(def_normbgcolor), "%s", normbgcolor); + snprintf(def_normfgcolor, sizeof(def_normfgcolor), "%s", normfgcolor); + snprintf(def_normbordercolor, sizeof(def_normbordercolor), "%s", normbordercolor); + snprintf(def_selbgcolor, sizeof(def_selbgcolor), "%s", selbgcolor); + snprintf(def_selfgcolor, sizeof(def_selfgcolor), "%s", selfgcolor); + snprintf(def_selbordercolor, sizeof(def_selbordercolor), "%s", selbordercolor); + def_borderpx = borderpx; + xres_defaults_saved = 1; + } else { + snprintf(xres_font, sizeof(xres_font), "%s", def_font); + font = xres_font; + snprintf(normbgcolor, sizeof(normbgcolor), "%s", def_normbgcolor); + snprintf(normfgcolor, sizeof(normfgcolor), "%s", def_normfgcolor); + snprintf(normbordercolor, sizeof(normbordercolor), "%s", def_normbordercolor); + snprintf(selbgcolor, sizeof(selbgcolor), "%s", def_selbgcolor); + snprintf(selfgcolor, sizeof(selfgcolor), "%s", def_selfgcolor); + snprintf(selbordercolor, sizeof(selbordercolor), "%s", def_selbordercolor); + borderpx = def_borderpx; + } + XrmInitialize(); const char *home = getenv("HOME"); char path[512]; snprintf(path, sizeof(path), "%s/.Xresources", (home && home[0]) ? home : "/home/user"); XrmDatabase db = XrmGetFileDatabase(path); - if (!db) { - char *resm = XResourceManagerString(dpy); - if (resm) db = XrmGetStringDatabase(resm); + XrmDatabase mdb = NULL; + { + 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, 262144L, False, XA_STRING, &actual_type, + &actual_format, &nitems, &bytes_after, &prop) == Success && prop) { + if (actual_type == XA_STRING && actual_format == 8 && nitems > 0) { + char *buf = malloc(nitems + 1); + if (buf) { + memcpy(buf, prop, nitems); + buf[nitems] = '\0'; + mdb = XrmGetStringDatabase(buf); + free(buf); + } + } + XFree(prop); + } + } + if (mdb) { + if (db) + XrmMergeDatabases(mdb, &db); + else + db = mdb; } if (!db) return; @@ -1190,7 +1593,6 @@ static void loadxres(void) { } static void reloadxres(const Arg *arg) { - (void)arg; Monitor *m; Client *c; loadxres(); @@ -1204,8 +1606,22 @@ static void reloadxres(const Arg *arg) { bh = MAX((int)dwmfont->h + 24, 78); drw_resize(drw, (unsigned int)sw, (unsigned int)bh); - free(scheme[SchemeNorm]); - free(scheme[SchemeSel]); + if (cursor[CurNormal]) { drw_cur_free(drw, cursor[CurNormal]); cursor[CurNormal] = NULL; } + if (cursor[CurResize]) { drw_cur_free(drw, cursor[CurResize]); cursor[CurResize] = NULL; } + if (cursor[CurMove]) { drw_cur_free(drw, cursor[CurMove]); cursor[CurMove] = NULL; } + cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr); + cursor[CurResize] = drw_cur_create(drw, XC_sizing); + cursor[CurMove] = drw_cur_create(drw, XC_fleur); + if (cursor[CurNormal]) + XDefineCursor(dpy, root, cursor[CurNormal]->cursor); + + for (int si = 0; si < 2; si++) { + if (scheme[si]) { + for (int ci = 0; ci < 3; ci++) + XftColorFree(dpy, DefaultVisual(dpy, screen), DefaultColormap(dpy, screen), &scheme[si][ci]); + free(scheme[si]); + } + } scheme[SchemeNorm] = drw_scm_create(drw, (const char **)colors[SchemeNorm], 3); scheme[SchemeSel] = drw_scm_create(drw, (const char **)colors[SchemeSel], 3); @@ -1214,21 +1630,65 @@ static void reloadxres(const Arg *arg) { updatebarpos(m); resizebarwin(m); for (c = m->clients; c; c = c->next) { - c->bw = (int)borderpx; + if (!c->isfullscreen) + c->bw = (int)borderpx; + else + c->oldbw = (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); + if (!systray->use_argb) + XSetWindowBackground(dpy, c->win, scheme[SchemeNorm][ColBg].pixel); + } + } updatesystray(1); + updateworkarea(); arrange(NULL); drawbars(); XSync(dpy, False); + if (arg) { + static const char *reloadcmd[] = { + "/bin/sh", "-c", + "xr=\"${GEMINUX_XRESOURCES:-$HOME/.Xresources}\"; " + "if [ -r \"$xr\" ] && command -v xrdb >/dev/null 2>&1; then " + " xrdb -nocpp -load \"$xr\" >/dev/null 2>&1 || true; " + "fi; " + "/usr/bin/geminux-sync-dunst-theme >/dev/null 2>&1 || true; " + "/usr/bin/geminux-sync-gtk-theme --skip-xrdb >/dev/null 2>&1 || true; " + "if [ \"${GEMINUX_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 == \"st\" || cmd == \"geminux-statusd\" || " + " cmd == \"geminux-themes\" || cmd == \"geminux-control\" || " + " cmd == \"geminux-net\" || cmd == \"geminux-audio\" || " + " cmd == \"geminux-datetime\" || cmd == \"geminux-lock\") print \"USR1 \" 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", + NULL + }; + Arg a = {.v = reloadcmd}; + spawn(&a); + } } static void manage(Window w, XWindowAttributes *wa) { Client *c, *t = NULL; Window trans = None; XWindowChanges wc; + unsigned long desk = 0; + int has_desk = 0; + + if (read_cardinal_prop(w, netatom[NetWMDesktop], &desk, 1) >= 1) + has_desk = 1; c = ecalloc(1, sizeof(Client)); c->win = w; @@ -1246,14 +1706,18 @@ static void manage(Window w, XWindowAttributes *wa) { c->mon = selmon; applyrules(c); } + if (has_desk) + c->tags = desktop_to_tags(desk); - if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) - c->x = c->mon->wx + c->mon->ww - WIDTH(c); - if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh) - c->y = c->mon->wy + c->mon->wh - HEIGHT(c); - c->x = MAX(c->x, c->mon->wx); - c->y = MAX(c->y, c->mon->wy); c->bw = (int)borderpx; + if (!c->isfullscreen) { + if (c->x + WIDTH(c) > c->mon->wx + c->mon->ww) + c->x = c->mon->wx + MAX(0, c->mon->ww - WIDTH(c)); + if (c->y + HEIGHT(c) > c->mon->wy + c->mon->wh) + c->y = c->mon->wy + MAX(0, c->mon->wh - HEIGHT(c)); + c->x = MAX(c->x, c->mon->wx); + c->y = MAX(c->y, c->mon->wy); + } wc.border_width = c->bw; XConfigureWindow(dpy, w, CWBorderWidth, &wc); @@ -1280,6 +1744,7 @@ static void manage(Window w, XWindowAttributes *wa) { XRaiseWindow(dpy, c->win); attach(c); attachstack(c); + sync_client_props(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); @@ -1291,6 +1756,37 @@ static void manage(Window w, XWindowAttributes *wa) { focus(NULL); } +static void mapnotify(XEvent *e) { + Client *i; + XMapEvent *ev = &e->xmap; + if (ev->window == root || (systray && ev->window == systray->win)) + return; + if ((i = wintosystrayicon(ev->window))) { + long flags = 0; + if (!i->tags && (!getxembedflags(i->win, &flags) || (flags & XEMBED_MAPPED))) { + i->tags = 1; + setclientstate(i, NormalState); + updatesystray(1); + drawbars(); + } + return; + } + if (!wintoclient(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 mappingnotify(XEvent *e) { XMappingEvent *ev = &e->xmapping; XRefreshKeyboardMapping(ev); @@ -1302,10 +1798,23 @@ static void maprequest(XEvent *e) { XMapRequestEvent *ev = &e->xmaprequest; Client *i; if ((i = wintosystrayicon(ev->window))) { - sendevent(i->win, xatom[Xembed], StructureNotifyMask, CurrentTime, - XEMBED_WINDOW_ACTIVATE, 0, (long)systray->win, 0); - resizebarwin(selmon); - updatesystray(0); + 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) @@ -1331,8 +1840,14 @@ static void motionnotify(XEvent *e) { 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; @@ -1413,8 +1928,24 @@ static void propertynotify(XEvent *e) { } else { updatesystrayiconstate(c, ev); } - resizebarwin(selmon); - updatesystray(0); + 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)) { @@ -1549,7 +2080,7 @@ static void resizerequest(XEvent *e) { Client *i; if ((i = wintosystrayicon(ev->window))) { updatesystrayicongeom(i, ev->width, ev->height); - resizebarwin(selmon); + resizebarwin(systraytomon(NULL)); updatesystray(0); } } @@ -1590,7 +2121,10 @@ static void run(void) { grabkeys(); } while (XPending(dpy) > 0) { + Time evtime = CurrentTime; XNextEvent(dpy, &ev); + if (extracteventtime(&ev, &evtime) && evtime != CurrentTime) + last_event_time = evtime; if (handler[ev.type]) handler[ev.type](&ev); } @@ -1607,15 +2141,21 @@ static void scan(void) { XWindowAttributes wa; if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) { for (i = 0; i < num; i++) { - if (!XGetWindowAttributes(dpy, wins[i], &wa) || - wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1)) + 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 (XGetTransientForHint(dpy, wins[i], &d1) && + if (!wa.override_redirect && XGetTransientForHint(dpy, wins[i], &d1) && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)) manage(wins[i], &wa); } @@ -1624,16 +2164,46 @@ static void scan(void) { } static void sendmon(Client *c, Monitor *m) { + Monitor *oldm; if (c->mon == m) return; + oldm = c->mon; unfocus(c, 1); detach(c); detachstack(c); c->mon = m; c->tags = m->tagset[m->seltags]; + if (c->isfullscreen) { + int ox_rel = c->oldx - oldm->mx; + int oy_rel = c->oldy - oldm->my; + int nw = MIN(c->oldw, MAX(64, m->ww - 2 * c->oldbw)); + int nh = MIN(c->oldh, MAX(64, m->wh - 2 * c->oldbw)); + c->oldx = m->wx + MAX(0, MIN(ox_rel, MAX(0, m->ww - nw))); + c->oldy = m->wy + MAX(0, MIN(oy_rel, MAX(0, m->wh - nh))); + c->oldw = nw; + c->oldh = nh; + c->x = m->mx; + c->y = m->my; + c->w = m->mw; + c->h = m->mh; + } else if (c->isfloating) { + int rx = c->x - oldm->mx; + int ry = c->y - oldm->my; + int nx = m->mx + rx; + int ny = m->my + ry; + if (nx + WIDTH(c) > m->wx + m->ww) nx = m->wx + MAX(0, m->ww - WIDTH(c)); + if (ny + HEIGHT(c) > m->wy + m->wh) ny = m->wy + MAX(0, m->wh - HEIGHT(c)); + if (nx < m->wx) nx = m->wx; + if (ny < m->wy) ny = m->wy; + c->x = nx; + c->y = ny; + } attach(c); attachstack(c); - focus(NULL); - arrange(NULL); + sync_client_props(c); + focusarranged(oldm); + focusarranged(m); + if (ISVISIBLE(c) && (c->isfullscreen || c->isfloating)) + resizeclient(c, c->x, c->y, c->w, c->h); } static void setclientstate(Client *c, long state) { @@ -1674,36 +2244,50 @@ static int sendevent(Window w, Atom proto, int mask, long d0, long d1, long d2, } static void setfocus(Client *c) { - if (!c->neverfocus) { + Time ts; + 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); + ts = getfocustime(); + sendevent(c->win, wmatom[WMTakeFocus], NoEventMask, + (long)wmatom[WMTakeFocus], (long)ts, 0, 0, 0); + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&(c->win), 1); +} + +static void setnofocus(void) { + XSetInputFocus(dpy, nofocuswin != None ? nofocuswin : root, + RevertToPointerRoot, CurrentTime); } 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); + addwmstate(c, netatom[NetWMFullscreen]); 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); + if (ISVISIBLE(c)) { + resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh); + XRaiseWindow(dpy, c->win); + } else { + c->oldx = c->x; c->oldy = c->y; + c->oldw = c->w; c->oldh = c->h; + c->x = c->mon->mx; c->y = c->mon->my; + c->w = c->mon->mw; c->h = c->mon->mh; + } } else if (!fullscreen && c->isfullscreen) { - XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, - PropModeReplace, (unsigned char *)0, 0); + removewmstate(c, netatom[NetWMFullscreen]); 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); + if (ISVISIBLE(c)) + resizeclient(c, c->x, c->y, c->w, c->h); arrange(c->mon); } + sync_client_props(c); } static void setlayout(const Arg *arg) { @@ -1711,9 +2295,10 @@ static void setlayout(const Arg *arg) { selmon->sellt ^= 1; if (arg && arg->v) selmon->lt[selmon->sellt] = (const Layout *)arg->v; - strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol); + snprintf(selmon->ltsymbol, sizeof selmon->ltsymbol, "%s", selmon->lt[selmon->sellt]->symbol); if (selmon->sel) arrange(selmon); else drawbar(selmon); + sync_root_desktop_props(); } static void setmfact(const Arg *arg) { @@ -1723,11 +2308,11 @@ static void setmfact(const Arg *arg) { if (f < 0.05 || f > 0.95) return; selmon->mfact = f; arrange(selmon); + sync_root_desktop_props(); } static void setup(void) { XSetWindowAttributes wa; - Atom utf8string; struct sigaction sa; sigemptyset(&sa.sa_mask); @@ -1746,6 +2331,12 @@ static void setup(void) { sa.sa_handler = sighup_handler; sigaction(SIGHUP, &sa, NULL); + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = sigterm_handler; + sigaction(SIGTERM, &sa, NULL); + sigaction(SIGINT, &sa, NULL); + loadxres(); screen = DefaultScreen(dpy); @@ -1759,24 +2350,43 @@ static void setup(void) { bh = MAX((int)dwmfont->h + 24, 78); 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); + wmatom[WMChangeState] = XInternAtom(dpy, "WM_CHANGE_STATE", False); netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False); netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False); - netatom[NetSystemTray] = XInternAtom(dpy, "_NET_SYSTEM_TRAY_S0", 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[NetWMFocused] = XInternAtom(dpy, "_NET_WM_STATE_FOCUSED", False); + netatom[NetWMStateSticky] = XInternAtom(dpy, "_NET_WM_STATE_STICKY", False); + netatom[NetWMStateAbove] = XInternAtom(dpy, "_NET_WM_STATE_ABOVE", False); + netatom[NetWMStateHidden] = XInternAtom(dpy, "_NET_WM_STATE_HIDDEN", False); + netatom[NetWorkarea] = XInternAtom(dpy, "_NET_WORKAREA", False); + netatom[NetNumberOfDesktops] = XInternAtom(dpy, "_NET_NUMBER_OF_DESKTOPS", False); + netatom[NetCurrentDesktop] = XInternAtom(dpy, "_NET_CURRENT_DESKTOP", False); + netatom[NetDesktopNames] = XInternAtom(dpy, "_NET_DESKTOP_NAMES", False); + netatom[NetWMDesktop] = XInternAtom(dpy, "_NET_WM_DESKTOP", False); netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False); netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False); + netatom[NetWMWindowTypeDock] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DOCK", False); + 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); + netatom[NetWMPid] = XInternAtom(dpy, "_NET_WM_PID", False); xatom[Manager] = XInternAtom(dpy, "MANAGER", False); xatom[Xembed] = XInternAtom(dpy, "_XEMBED", False); xatom[XembedInfo] = XInternAtom(dpy, "_XEMBED_INFO", False); @@ -1791,13 +2401,31 @@ static void setup(void) { updatesystray(0); updatebars(); + updateworkarea(); updatestatus(); + publish_desktop_names(); + sync_root_desktop_props(); + + { + XSetWindowAttributes nwa; + nwa.override_redirect = True; + nwa.event_mask = NoEventMask; + nofocuswin = XCreateWindow(dpy, root, -10, -10, 1, 1, 0, + 0, InputOnly, CopyFromParent, + CWOverrideRedirect | CWEventMask, &nwa); + XMapWindow(dpy, nofocuswin); + } 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); + PropModeReplace, (unsigned char *)"Geminux", 7); + { + unsigned long pid = (unsigned long)getpid(); + XChangeProperty(dpy, wmcheckwin, netatom[NetWMPid], XA_CARDINAL, 32, + PropModeReplace, (unsigned char *)&pid, 1); + } XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32, PropModeReplace, (unsigned char *)&wmcheckwin, 1); XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32, @@ -1827,9 +2455,23 @@ static void seturgent(Client *c, int urg) { 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); + if (c->isfullscreen) { + c->bw = 0; + c->x = c->mon->mx; + c->y = c->mon->my; + c->w = c->mon->mw; + c->h = c->mon->mh; + XMoveResizeWindow(dpy, c->win, c->x, c->y, (unsigned int)c->w, (unsigned int)c->h); + configure(c); + } else { + XMoveWindow(dpy, c->win, c->x, c->y); + if (!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) + resize(c, c->x, c->y, c->w, c->h, 0); + } + if (c->isiconic) { + c->isiconic = 0; + setclientstate(c, NormalState); + } showhide(c->snext); } else { showhide(c->snext); @@ -1853,6 +2495,11 @@ static void sighup_handler(int sig) { running = 0; } +static void sigterm_handler(int sig) { + (void)sig; + running = 0; +} + static void spawn(const Arg *arg) { struct sigaction sa; if (fork() == 0) { @@ -1883,8 +2530,8 @@ static Monitor *systraytomon(Monitor *m) { static void tag(const Arg *arg) { if (selmon->sel && (arg->ui & TAGMASK)) { selmon->sel->tags = arg->ui & TAGMASK; - focus(NULL); - arrange(selmon); + sync_client_props(selmon->sel); + focusarranged(selmon); } } @@ -1923,16 +2570,13 @@ static void togglebar(const Arg *arg) { selmon->showbar = !selmon->showbar; updatebarpos(selmon); resizebarwin(selmon); - if (showsystray && systray) { + if (showsystray && systray && selmon == systraytomon(selmon)) { XWindowChanges wc; - if (!selmon->showbar) wc.y = -bh; - else if (selmon->showbar) { - wc.y = 0; - if (!selmon->topbar) wc.y = selmon->mh - bh; - } + wc.y = selmon->showbar ? selmon->by : -bh; XConfigureWindow(dpy, systray->win, CWY, &wc); } arrange(selmon); + sync_root_desktop_props(); } static void togglefloating(const Arg *arg) { @@ -1941,6 +2585,7 @@ static void togglefloating(const Arg *arg) { selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed; if (selmon->sel->isfloating) resize(selmon->sel, selmon->sel->x, selmon->sel->y, selmon->sel->w, selmon->sel->h, 0); + sync_client_props(selmon->sel); arrange(selmon); } @@ -1950,8 +2595,8 @@ static void toggletag(const Arg *arg) { newtags = selmon->sel->tags ^ (arg->ui & TAGMASK); if (newtags) { selmon->sel->tags = newtags; - focus(NULL); - arrange(selmon); + sync_client_props(selmon->sel); + focusarranged(selmon); } } @@ -1959,8 +2604,8 @@ 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); + sync_root_desktop_props(); + focusarranged(selmon); } } @@ -1968,9 +2613,12 @@ static void unfocus(Client *c, int setfocus) { if (!c) return; grabbuttons(c, 0); XSetWindowBorder(dpy, c->win, scheme[SchemeNorm][ColBorder].pixel); + removewmstate(c, netatom[NetWMFocused]); if (setfocus) { - XSetInputFocus(dpy, root, RevertToPointerRoot, CurrentTime); - XDeleteProperty(dpy, root, netatom[NetActiveWindow]); + Window none = None; + setnofocus(); + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *)&none, 1); } } @@ -2004,9 +2652,14 @@ static void unmapnotify(XEvent *e) { if (ev->send_event) setclientstate(c, WithdrawnState); else unmanage(c, 0); } else if ((c = wintosystrayicon(ev->window))) { - removesystrayicon(c); - resizebarwin(selmon); - updatesystray(0); + if (c->tags) { + c->tags = 0; + setclientstate(c, WithdrawnState); + updatesystray(1); + drawbars(); + } + } else if (dockremove(ev->window)) { + recalcworkareas(); } } @@ -2022,21 +2675,29 @@ static void updatebars(void) { for (m = mons; m; m = m->next) { if (m->barwin) continue; w = (unsigned int)m->ww; - if (showsystray && m == systraytomon(m)) w -= getsystraywidth(); + 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) - XMapRaised(dpy, systray->win); - XMapRaised(dpy, m->barwin); + if (showsystray && m == systraytomon(m) && systray && getsystraywidth() > 0) + XMapWindow(dpy, systray->win); + XMapWindow(dpy, m->barwin); + if (showsystray && m == systraytomon(m) && systray && getsystraywidth() > 0) { + XWindowChanges wc; + wc.stack_mode = Above; + wc.sibling = m->barwin; + XConfigureWindow(dpy, systray->win, CWSibling | CWStackMode, &wc); + } 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; @@ -2045,6 +2706,42 @@ static void updatebarpos(Monitor *m) { } 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) { @@ -2109,6 +2806,7 @@ static int updategeom(void) { c->mon = mons; attach(c); attachstack(c); + sync_client_props(c); } if (m == selmon) selmon = mons; cleanupmon(m); @@ -2129,6 +2827,7 @@ static int updategeom(void) { if (dirty) { selmon = mons; selmon = wintomon(root); + sync_root_desktop_props(); } return dirty; } @@ -2182,6 +2881,144 @@ static void updatestatus(void) { 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; @@ -2189,23 +3026,42 @@ static void updatesystray(int updatebar) { 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 = 1; + 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)); - systray->win = XCreateSimpleWindow(dpy, root, (int)x, m->by, w, (unsigned int)bh, 0, 0, - scheme[SchemeNorm][ColBg].pixel); - wa.event_mask = ButtonPressMask | ExposureMask; + 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.background_pixel = scheme[SchemeNorm][ColBg].pixel; - XSelectInput(dpy, systray->win, SubstructureNotifyMask); + 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 *)&netatom[NetSystemTrayOrientationHorz], 1); - XChangeWindowAttributes(dpy, systray->win, CWEventMask | CWOverrideRedirect | CWBackPixel, &wa); - XMapRaised(dpy, systray->win); + 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, @@ -2213,6 +3069,9 @@ static void updatesystray(int updatebar) { 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; @@ -2220,48 +3079,60 @@ static void updatesystray(int updatebar) { } for (w = 0, i = systray->icons; i; i = i->next) { - wa.background_pixel = scheme[SchemeNorm][ColBg].pixel; - XChangeWindowAttributes(dpy, i->win, CWBackPixel, &wa); - XMapRaised(dpy, i->win); + if (!i->tags) continue; + int iy = MAX(0, (bh - i->h) / 2); w += systrayspacing; i->x = (int)w; - XMoveResizeWindow(dpy, i->win, i->x, 0, (unsigned int)i->w, (unsigned int)i->h); + 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; } - w = w ? w + systrayspacing : 1; - x = (unsigned int)(m->mx + m->mw) - w; + + 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); + XSetWindowBackground(dpy, systray->win, systray_bg_pixel()); + XClearWindow(dpy, systray->win); + XMapWindow(dpy, systray->win); 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); - XMapWindow(dpy, systray->win); - XMapSubwindows(dpy, systray->win); - XSetWindowBackground(dpy, systray->win, scheme[SchemeNorm][ColBg].pixel); - XClearWindow(dpy, systray->win); if (updatebar) resizebarwin(m); XSync(dpy, False); } static void updatesystrayicongeom(Client *i, int w, int h) { if (i) { - i->h = bh; - if (w == h) i->w = bh; - else if (h == bh) i->w = w; - else i->w = (int)((float)bh * ((float)w / (float)(h ? h : 1))); + int pad = 4; + int target_h = MAX(16, 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(16, (int)((float)target_h * ((float)w / (float)h))); applysizehints(i, &i->x, &i->y, &i->w, &i->h, False); - if (i->h > bh) { - if (i->w == i->h) i->w = bh; - else i->w = (int)((float)bh * ((float)i->w / (float)(i->h ? i->h : 1))); - i->h = bh; + if (i->h > target_h || i->h < 16) { + i->w = (i->w == i->h) ? target_h : MAX(16, (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; + long flags = 0; int code = 0; - if (!showsystray || !i || ev->atom != xatom[XembedInfo] || !(flags = getatomprop(i, xatom[XembedInfo]))) + if (!showsystray || !i || ev->atom != xatom[XembedInfo]) + return; + if (!getxembedflags(i->win, &flags)) return; if ((flags & XEMBED_MAPPED) && !i->tags) { i->tags = 1; @@ -2270,7 +3141,7 @@ static void updatesystrayiconstate(Client *i, XPropertyEvent *ev) { setclientstate(i, NormalState); } else if (!(flags & XEMBED_MAPPED) && i->tags) { i->tags = 0; - code = XEMBED_WINDOW_ACTIVATE_BIT; + code = XEMBED_WINDOW_DEACTIVATE; XUnmapWindow(dpy, i->win); setclientstate(i, WithdrawnState); } else { @@ -2286,10 +3157,14 @@ static void updatetitle(Client *c) { } 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; + if (hasatomprop(c, netatom[NetWMState], netatom[NetWMFullscreen])) + setfullscreen(c, 1); + if (hasatomprop(c, netatom[NetWMWindowType], netatom[NetWMWindowTypeDialog])) + c->isfloating = 1; + if (hasatomprop(c, netatom[NetWMState], netatom[NetWMStateSticky])) + c->tags = TAGMASK; + if (hasatomprop(c, netatom[NetWMState], netatom[NetWMStateAbove])) + c->isfloating = 1; } static void updatewmhints(Client *c) { @@ -2313,8 +3188,8 @@ static void view(const Arg *arg) { selmon->seltags ^= 1; if (arg->ui & TAGMASK) selmon->tagset[selmon->seltags] = arg->ui & TAGMASK; - focus(NULL); - arrange(selmon); + sync_root_desktop_props(); + focusarranged(selmon); } static Client *wintoclient(Window w) { diff --git a/src/geminux-apps/Makefile b/src/geminux-apps/Makefile index db21f16..26cd3ad 100644 --- a/src/geminux-apps/Makefile +++ b/src/geminux-apps/Makefile @@ -38,6 +38,9 @@ geminux-net: geminux-net.c geminux-wifi-list.h geminux-bt-list.h ../geminux-daem geminux-audio: geminux-audio.c geminux-audio-parse.h ../libgemui/gemui.h $(CC) $(CFLAGS) -o $@ $< $(LIBS) +geminux-themes: geminux-themes.c geminux-xth.h ../libgemui/gemui.h + $(CC) $(CFLAGS) -o $@ $< $(LIBS) -lm + geminux-%: geminux-%.c ../libgemui/gemui.h $(CC) $(CFLAGS) -o $@ $< $(LIBS) diff --git a/src/geminux-apps/geminux-themes.c b/src/geminux-apps/geminux-themes.c index 97a62be..05a6b5f 100644 --- a/src/geminux-apps/geminux-themes.c +++ b/src/geminux-apps/geminux-themes.c @@ -1,186 +1,1418 @@ +/* Geminux Unified Theme Browser, Live Preview, Importer & .xth Editor */ #define _POSIX_C_SOURCE 200809L -#include "gemui.h" +#include "../libgemui/gemui.h" +#include "geminux-xth.h" +#include #include #include #include #include +#include +#include -#define HIT_ITEM 1 -#define HIT_APPLY 2 +#define MAX_THEMES 128 +#define MAX_DIR_ITEMS 256 + +enum { VIEW_BROWSE = 0, VIEW_EDITOR = 1, VIEW_IMPORT = 2 }; +enum { ED_TAB_GEN = 0, ED_TAB_UI = 1, ED_TAB_WM = 2, ED_TAB_TERM = 3 }; typedef struct { char name[64]; char path[512]; - gemui_theme_t parsed; -} xth_entry_t; + gemui_theme_t preview; + bool is_user; + bool has_sys; +} theme_entry_t; + +typedef struct { + char name[260]; + bool is_dir; +} dir_item_t; typedef struct { gemui_app_t *app; - xth_entry_t items[48]; - int num_items; + int view; + + /* Browse view */ + theme_entry_t themes[MAX_THEMES]; + int count; int sel; + int scroll; + char active_name[64]; + char filter[64]; + + /* Active text input */ + int focus_id; + char *focus_buf; + size_t focus_cap; + + /* Editor view */ + geminux_xth_t ed_xth; + geminux_xth_t ed_orig; + int ed_tab; + int ed_color_idx; + int ed_scroll; + int ed_r, ed_g, ed_b; + char ed_hex[16]; + bool ed_auto_sync; + bool ed_is_new; + int ed_drag_chan; /* 0=none, 1=R, 2=G, 3=B */ + gemui_rect_t ed_slider_rect[3]; + + /* Import view */ + char imp_dir[512]; + char imp_path[800]; + char imp_name[64]; + bool imp_show_all; + dir_item_t imp_items[MAX_DIR_ITEMS]; + int imp_count; + int imp_sel; + int imp_scroll; + geminux_xth_t imp_preview; + bool imp_valid; } themes_state_t; -static int cmp_xth(const void *a, const void *b) { - const xth_entry_t *xa = a; - const xth_entry_t *xb = b; - return strcmp(xa->name, xb->name); +enum { + HIT_FILTER = 1, + HIT_ROW, + HIT_APPLY, + HIT_EDIT, + HIT_DUPLICATE, + HIT_NEW, + HIT_OPEN_IMPORT, + HIT_DELETE, + HIT_QUIT, + + HIT_ED_TAB, + HIT_ED_FIELD, + HIT_ED_DARK, + HIT_ED_FONTSZ, + HIT_ED_BORDERPX, + HIT_ED_AUTOSYNC, + HIT_ED_SLOT, + HIT_ED_HEX, + HIT_ED_PASTE_HEX, + HIT_ED_SLIDER_R, + HIT_ED_SLIDER_G, + HIT_ED_SLIDER_B, + HIT_ED_SAVE, + HIT_ED_SAVE_APPLY, + HIT_ED_REVERT, + HIT_ED_BACK, + + HIT_IMP_PATH, + HIT_IMP_PASTE_PATH, + HIT_IMP_QUICK_DIR, + HIT_IMP_TOGGLE_ALL, + HIT_IMP_ITEM, + HIT_IMP_NAME, + HIT_IMP_DO, + HIT_IMP_DO_APPLY, + HIT_IMP_BACK +}; + +static int cmp_theme_entry(const void *a, const void *b) { + const theme_entry_t *ta = (const theme_entry_t *)a; + 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) { +static int cmp_dir_item(const void *a, const void *b) { + const dir_item_t *da = (const dir_item_t *)a; + const dir_item_t *db = (const dir_item_t *)b; + if (da->is_dir != db->is_dir) return da->is_dir ? -1 : 1; + return strcmp(da->name, db->name); +} + +static bool ci_contains(const char *hay, const char *needle) { + if (!needle || !needle[0]) return true; + if (!hay || !hay[0]) return false; + size_t nlen = strlen(needle); + for (const char *p = hay; *p; p++) { + size_t i = 0; + while (i < nlen && p[i] && tolower((unsigned char)p[i]) == tolower((unsigned char)needle[i])) { + i++; + } + if (i == nlen) return true; + } + return false; +} + +static void mkdir_p_user(const char *dir) { + char tmp[512]; + snprintf(tmp, sizeof(tmp), "%s", dir); + size_t n = strlen(tmp); + if (n > 1 && tmp[n - 1] == '/') tmp[n - 1] = '\0'; + for (char *p = tmp + 1; *p; p++) { + if (*p == '/') { + *p = '\0'; + mkdir(tmp, 0755); + *p = '/'; + } + } + mkdir(tmp, 0755); +} + +static void user_themes_dir(char *out, size_t sz) { + const char *xdg = getenv("XDG_CONFIG_HOME"); + const char *home = getenv("HOME"); + if (xdg && xdg[0]) { + snprintf(out, sz, "%s/geminux/themes", xdg); + } else { + snprintf(out, sz, "%s/.config/geminux/themes", (home && home[0]) ? home : "/tmp"); + } +} + +static void set_focus_input(themes_state_t *st, int hit_id, char *buf, size_t cap) { + st->focus_id = hit_id; + st->focus_buf = buf; + st->focus_cap = cap; +} + +static void build_preview_from_xth(const geminux_xth_t *x, gemui_theme_t *p) { + gemui_theme_defaults(p); + if (!x) return; + snprintf(p->name, sizeof(p->name), "%s", x->name[0] ? x->name : "Preview"); + snprintf(p->font_face, sizeof(p->font_face), "%s", x->font_face[0] ? x->font_face : "Fira Code"); + snprintf(p->icon_font_face, sizeof(p->icon_font_face), "%s", + x->icon_font_face[0] ? x->icon_font_face : "DejaVuSansM Nerd Font"); + p->base_font_size = (x->base_font_size >= 16 && x->base_font_size <= 64) ? x->base_font_size : 32; + + gemui_color_parse(x->colors[GEMINUX_XTH_BG_MAIN], &p->bg_main); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_BAR], &p->bg_bar); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_HEADER], &p->bg_header); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_FOOTER], &p->bg_footer); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_OVERLAY], &p->bg_overlay); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_ALT_EVEN], &p->bg_alt_even); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_ALT_ODD], &p->bg_alt_odd); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_INPUT], &p->bg_input); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_INPUT_FOCUS], &p->bg_input_focus); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_BUTTON], &p->bg_button); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_SEARCH], &p->bg_search); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_BUBBLE_IN], &p->bg_bubble_in); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_BUBBLE_OUT], &p->bg_bubble_out); + gemui_color_parse(x->colors[GEMINUX_XTH_BG_TOAST], &p->bg_toast); + gemui_color_parse(x->colors[GEMINUX_XTH_FG_MAIN], &p->fg_main); + gemui_color_parse(x->colors[GEMINUX_XTH_FG_BRIGHT], &p->fg_bright); + gemui_color_parse(x->colors[GEMINUX_XTH_FG_MUTED], &p->fg_muted); + gemui_color_parse(x->colors[GEMINUX_XTH_SEL_BG], &p->sel_bg); + gemui_color_parse(x->colors[GEMINUX_XTH_SEL_FG], &p->sel_fg); + gemui_color_parse(x->colors[GEMINUX_XTH_ACCENT], &p->accent); + gemui_color_parse(x->colors[GEMINUX_XTH_ACCENT_ALT], &p->accent_alt); + gemui_color_parse(x->colors[GEMINUX_XTH_HIGHLIGHT], &p->highlight); + gemui_color_parse(x->colors[GEMINUX_XTH_BORDER], &p->border); + gemui_color_parse(x->colors[GEMINUX_XTH_DIVIDER], &p->divider); + gemui_color_parse(x->colors[GEMINUX_XTH_SUCCESS], &p->success); + gemui_color_parse(x->colors[GEMINUX_XTH_INFO], &p->info); + gemui_color_parse(x->colors[GEMINUX_XTH_WARNING], &p->warning); + gemui_color_parse(x->colors[GEMINUX_XTH_DANGER], &p->danger); + gemui_color_parse(x->colors[GEMINUX_XTH_DANGER_BG], &p->danger_bg); +} + +static void scan_dir(themes_state_t *st, const char *dir, int mode) { + /* mode: 0 = system read-only, 1 = user dir (~/.config/geminux/themes), + 2 = ~/.xthemes (user only if not already registered as sys) */ + if (!dir || !dir[0]) return; DIR *d = opendir(dir); if (!d) return; struct dirent *de; - while ((de = readdir(d)) != NULL && st->num_items < 48) { + while ((de = readdir(d)) != NULL) { size_t len = strlen(de->d_name); if (len < 5 || strcmp(de->d_name + len - 4, ".xth") != 0) continue; - char short_name[64]; - snprintf(short_name, sizeof(short_name), "%.*s", (int)(len - 4), de->d_name); - bool dup = false; - for (int i = 0; i < st->num_items; i++) { - if (strcmp(st->items[i].name, short_name) == 0) { - dup = true; + + char full[512]; + if (snprintf(full, sizeof(full), "%s/%s", dir, de->d_name) >= (int)sizeof(full)) continue; + 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; } } - if (dup) continue; - xth_entry_t *e = &st->items[st->num_items++]; - snprintf(e->name, sizeof(e->name), "%s", short_name); - snprintf(e->path, sizeof(e->path), "%s/%s", dir, de->d_name); - gemui_theme_load_file(e->path, &e->parsed); + if (existing < 0 && st->count >= MAX_THEMES) continue; + theme_entry_t *e = (existing >= 0) ? &st->themes[existing] : &st->themes[st->count++]; + if (existing < 0) memset(e, 0, sizeof(*e)); + snprintf(e->name, sizeof(e->name), "%s", tname); + snprintf(e->path, sizeof(e->path), "%s", full); + e->preview = prev; + if (mode == 1) { + e->is_user = true; + } else if (mode == 2) { + if (!e->has_sys) e->is_user = true; + } else { + e->has_sys = true; + } } closedir(d); } -static void load_themes(themes_state_t *st) { - st->num_items = 0; +static void reload_themes(themes_state_t *st, const char *prefer_select) { + st->count = 0; + char udir[512]; + user_themes_dir(udir, sizeof(udir)); + + scan_dir(st, "/etc/skel/.xthemes", 0); + scan_dir(st, "overlay/rootfs/etc/skel/.xthemes", 0); const char *home = getenv("HOME"); if (home && home[0]) { - char p[512]; - snprintf(p, sizeof(p), "%s/.xthemes", home); - scan_dir(st, p); + char xdir[544]; + if (snprintf(xdir, sizeof(xdir), "%s/.xthemes", home) < (int)sizeof(xdir)) { + scan_dir(st, xdir, 2); + } } - scan_dir(st, "/etc/skel/.xthemes"); - if (st->num_items > 1) qsort(st->items, (size_t)st->num_items, sizeof(st->items[0]), cmp_xth); + scan_dir(st, udir, 1); + 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); - st->sel = 0; - for (int i = 0; i < st->num_items; i++) { - if (cur && strcmp(st->items[i].name, cur->name) == 0) { + snprintf(st->active_name, sizeof(st->active_name), "%s", cur ? cur->name : ""); + const char *target = (prefer_select && prefer_select[0]) ? prefer_select : st->active_name; + for (int i = 0; i < st->count; i++) { + if (strcmp(st->themes[i].name, target) == 0) { st->sel = i; break; } } + if (st->sel >= st->count) st->sel = st->count > 0 ? st->count - 1 : 0; + if (st->sel < 0) st->sel = 0; +} + +static int apply_path_now(themes_state_t *st, const char *path) { + const char *av[] = {"/usr/bin/geminux-apply-theme", path, NULL}; + if (gemui_run_cmd_timeout(av, NULL, 0, 5000) == 0) { + gemui_theme_reload(st->app); + const gemui_theme_t *cur = gemui_theme(st->app); + snprintf(st->active_name, sizeof(st->active_name), "%s", cur ? cur->name : ""); + return 0; + } + return -1; } static void apply_selected(themes_state_t *st) { - if (st->sel < 0 || st->sel >= st->num_items) return; - const char *argv[] = {"/usr/bin/geminux-apply-theme", st->items[st->sel].name, NULL}; - int rc = gemui_run_cmd_timeout(argv, NULL, 0, 10000); - gemui_theme_reload(st->app); - gemui_show_toast(st->app, rc == 0 ? "Applied .Xresources, GTK2/3/4, Qt, Tk & dunst theme" : "Theme apply failed", 2000); + if (st->sel < 0 || st->sel >= st->count) return; + if (apply_path_now(st, st->themes[st->sel].path) == 0) { + char msg[128]; + snprintf(msg, sizeof(msg), "Applied %s across Geminux", 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 = ud; - const gemui_theme_t *t = gemui_theme(app); +static void ed_sync_picker_from_slot(themes_state_t *st) { + if (st->ed_color_idx < 0 || st->ed_color_idx >= GEMINUX_XTH_COLOR_COUNT) st->ed_color_idx = 0; + const char *hex = st->ed_xth.colors[st->ed_color_idx]; + geminux_xth_parse_hex(hex, &st->ed_r, &st->ed_g, &st->ed_b); + snprintf(st->ed_hex, sizeof(st->ed_hex), "%s", hex); +} - gemui_draw_header(app, cr, "\xee\x88\xab", "Geminux Unified Themes", t->name); +static void ed_commit_rgb_to_slot(themes_state_t *st) { + geminux_xth_format_hex(st->ed_r, st->ed_g, st->ed_b, st->ed_hex, sizeof(st->ed_hex)); + snprintf(st->ed_xth.colors[st->ed_color_idx], 16, "%s", st->ed_hex); + if (st->ed_auto_sync && st->ed_tab == ED_TAB_UI) { + geminux_xth_sync_derived(&st->ed_xth); + } +} + +static void ed_tab_slot_range(int tab, int *first, int *last) { + if (tab == ED_TAB_UI) { *first = 0; *last = GEMINUX_XTH_DANGER_BG; } + else if (tab == ED_TAB_WM) { *first = GEMINUX_XTH_DWM_NORM_BG; *last = GEMINUX_XTH_DMENU_OUT_FG; } + else if (tab == ED_TAB_TERM) { *first = GEMINUX_XTH_ST_BG; *last = GEMINUX_XTH_ST_COLOR15; } + else { *first = 0; *last = -1; } +} + +static bool name_exists(const themes_state_t *st, const char *name) { + for (int i = 0; i < st->count; i++) { + if (strcmp(st->themes[i].name, name) == 0) return true; + } + return false; +} + +static void make_unique_copy_name(const themes_state_t *st, const char *base, char *out, size_t sz) { + char clean[48]; + geminux_xth_sanitize_name(base, clean, sizeof(clean)); + if (!clean[0]) snprintf(clean, sizeof(clean), "Theme"); + snprintf(out, sz, "%s_Copy", clean); + for (int n = 2; name_exists(st, out) && n < 100; n++) { + snprintf(out, sz, "%s_Copy%d", clean, n); + } +} + +static void open_editor(themes_state_t *st, const geminux_xth_t *src, bool is_new) { + st->ed_xth = *src; + st->ed_orig = *src; + st->ed_is_new = is_new; + st->ed_auto_sync = true; + st->ed_tab = is_new ? ED_TAB_GEN : ED_TAB_UI; + st->ed_color_idx = GEMINUX_XTH_BG_MAIN; + st->ed_scroll = 0; + st->ed_drag_chan = 0; + ed_sync_picker_from_slot(st); + st->view = VIEW_EDITOR; + if (is_new) set_focus_input(st, HIT_ED_FIELD, st->ed_xth.name, sizeof(st->ed_xth.name)); + else set_focus_input(st, HIT_ED_HEX, st->ed_hex, sizeof(st->ed_hex)); + gemui_request_redraw(st->app); +} + +static bool editor_save(themes_state_t *st, bool and_apply) { + char clean[64]; + geminux_xth_sanitize_name(st->ed_xth.name, clean, sizeof(clean)); + if (!clean[0]) { + gemui_show_toast(st->app, "Enter a valid alphanumeric theme name", 2200); + set_focus_input(st, HIT_ED_FIELD, st->ed_xth.name, sizeof(st->ed_xth.name)); + gemui_request_redraw(st->app); + return false; + } + snprintf(st->ed_xth.name, sizeof(st->ed_xth.name), "%s", clean); + if (st->ed_auto_sync) geminux_xth_sync_derived(&st->ed_xth); + + char udir[512], path[600]; + user_themes_dir(udir, sizeof(udir)); + mkdir_p_user(udir); + if (snprintf(path, sizeof(path), "%s/%s.xth", udir, clean) >= (int)sizeof(path) || + !geminux_xth_save_file(path, &st->ed_xth)) { + gemui_show_toast(st->app, "Failed to write user .xth file", 2200); + return false; + } + reload_themes(st, clean); + if (and_apply) { + if (apply_path_now(st, path) == 0) { + char msg[128]; + snprintf(msg, sizeof(msg), "Saved & applied %s", clean); + gemui_show_toast(st->app, msg, 2200); + } else { + gemui_show_toast(st->app, "Saved theme, but apply failed", 2200); + } + } else { + char msg[128]; + snprintf(msg, sizeof(msg), "Saved %s to ~/.config/geminux/themes", clean); + gemui_show_toast(st->app, msg, 2200); + } + gemui_request_redraw(st->app); + return true; +} + +static void expand_tilde(const char *in, char *out, size_t sz) { + if (in[0] == '~' && (in[1] == '/' || in[1] == '\0')) { + const char *home = getenv("HOME"); + if (home && home[0]) { + snprintf(out, sz, "%s%s", home, in + 1); + return; + } + } + snprintf(out, sz, "%s", in); +} + +static void imp_scan_dir(themes_state_t *st, const char *dir) { + char exp[800]; + expand_tilde(dir, exp, sizeof(exp)); + DIR *d = opendir(exp); + if (!d) return; + + snprintf(st->imp_dir, sizeof(st->imp_dir), "%.*s", (int)sizeof(st->imp_dir) - 1, exp); + st->imp_count = 0; + if (strcmp(st->imp_dir, "/") != 0) { + snprintf(st->imp_items[st->imp_count].name, sizeof(st->imp_items[0].name), ".."); + st->imp_items[st->imp_count].is_dir = true; + st->imp_count++; + } + + struct dirent *de; + dir_item_t rest[MAX_DIR_ITEMS]; + int rc = 0; + while ((de = readdir(d)) != NULL && rc < MAX_DIR_ITEMS - 1) { + if (de->d_name[0] == '.') continue; + char full[1024]; + if (snprintf(full, sizeof(full), "%s/%s", st->imp_dir, de->d_name) >= (int)sizeof(full)) continue; + struct stat sb; + if (stat(full, &sb) != 0) continue; + bool is_d = S_ISDIR(sb.st_mode); + if (!is_d && !st->imp_show_all) { + size_t nl = strlen(de->d_name); + if (nl < 5 || strcmp(de->d_name + nl - 4, ".xth") != 0) continue; + } + snprintf(rest[rc].name, sizeof(rest[0].name), "%s", de->d_name); + rest[rc].is_dir = is_d; + rc++; + } + closedir(d); + + if (rc > 1) qsort(rest, (size_t)rc, sizeof(rest[0]), cmp_dir_item); + for (int i = 0; i < rc && st->imp_count < MAX_DIR_ITEMS; i++) { + st->imp_items[st->imp_count++] = rest[i]; + } + st->imp_sel = 0; + st->imp_scroll = 0; +} + +static void imp_refresh_preview(themes_state_t *st, bool update_name) { + char exp[800]; + expand_tilde(st->imp_path, exp, sizeof(exp)); + struct stat sb; + st->imp_valid = false; + if (stat(exp, &sb) == 0 && S_ISREG(sb.st_mode)) { + if (geminux_xth_load_file(exp, &st->imp_preview)) { + st->imp_valid = true; + if (update_name) { + snprintf(st->imp_name, sizeof(st->imp_name), "%s", st->imp_preview.name); + } + } + } +} + +static void open_importer(themes_state_t *st) { + const char *home = getenv("HOME"); + if (!st->imp_dir[0]) { + snprintf(st->imp_dir, sizeof(st->imp_dir), "%s", (home && home[0]) ? home : "/"); + } + snprintf(st->imp_path, sizeof(st->imp_path), "%s", st->imp_dir); + st->imp_name[0] = '\0'; + st->imp_valid = false; + imp_scan_dir(st, st->imp_dir); + st->view = VIEW_IMPORT; + set_focus_input(st, HIT_IMP_PATH, st->imp_path, sizeof(st->imp_path)); + gemui_request_redraw(st->app); +} + +static void do_import_now(themes_state_t *st, bool and_apply) { + char exp[800]; + expand_tilde(st->imp_path, exp, sizeof(exp)); + char udir[512], dest[600]; + user_themes_dir(udir, sizeof(udir)); + mkdir_p_user(udir); + + if (!geminux_xth_import_file(exp, udir, st->imp_name, dest, sizeof(dest))) { + gemui_show_toast(st->app, "Invalid or unreadable .xth theme file", 2200); + return; + } + + geminux_xth_t loaded; + char sel_name[64] = ""; + if (geminux_xth_load_file(dest, &loaded)) { + snprintf(sel_name, sizeof(sel_name), "%s", loaded.name); + } + reload_themes(st, sel_name); + if (and_apply) { + if (apply_path_now(st, dest) == 0) { + char msg[128]; + snprintf(msg, sizeof(msg), "Imported & applied %s", sel_name); + gemui_show_toast(st->app, msg, 2200); + } else { + gemui_show_toast(st->app, "Imported theme, apply failed", 2200); + } + } else { + char msg[128]; + snprintf(msg, sizeof(msg), "Imported %s to ~/.config/geminux/themes", sel_name); + gemui_show_toast(st->app, msg, 2200); + } + st->view = VIEW_BROWSE; + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(st->app); +} + +static void draw_mini_preview(themes_state_t *st, cairo_t *cr, gemui_rect_t r, + const gemui_theme_t *p, const geminux_xth_t *xopt) { + const gemui_theme_t *ui = gemui_theme(st->app); + int pad = 20; + gemui_fill_round(cr, r, 14.0, p->bg_main); + gemui_stroke_round(cr, r, 14.0, 2.0, p->accent); + + int iy = r.y + pad; + int bar_h = 46; + + /* Simulated mini DWM bar */ + gemui_fill_round(cr, (gemui_rect_t){r.x + pad, iy, r.w - pad * 2, bar_h}, 8.0, p->bg_bar); + int tag_w = 52; + gemui_fill_round(cr, (gemui_rect_t){r.x + pad, iy, tag_w, bar_h}, 8.0, p->sel_bg); + gemui_draw_text(cr, ui, (gemui_rect_t){r.x + pad, iy, tag_w, bar_h}, + "1", 0, true, GEMUI_ALIGN_CENTER, p->sel_fg); + gemui_draw_text(cr, ui, (gemui_rect_t){r.x + pad + tag_w + 16, iy, r.w - pad * 2 - tag_w - 24, bar_h}, + p->name, 0, true, GEMUI_ALIGN_LEFT, p->fg_bright); + iy += bar_h + 14; + + /* Sample typography line */ + int lh = 44; + gemui_draw_text(cr, ui, (gemui_rect_t){r.x + pad, iy, r.w - pad * 2, lh}, + "Fira Code: -> => != === ::", 0, false, GEMUI_ALIGN_LEFT, p->fg_main); + iy += lh + 10; + + /* Theme accent swatches */ + const gemui_color_t sw[6] = { p->accent, p->sel_bg, p->success, p->warning, p->danger, p->highlight }; + const char *sw_lbl[6] = { "Acc", "Sel", "OK", "Warn", "Err", "Hi" }; + int sw_w = (r.w - pad * 2 - 5 * 12) / 6; + int sw_h = 52; + if (iy + sw_h + 12 < r.y + r.h) { + for (int i = 0; i < 6; i++) { + gemui_rect_t sr = {r.x + pad + i * (sw_w + 12), iy, sw_w, sw_h}; + gemui_fill_round(cr, sr, 8.0, sw[i]); + gemui_stroke_round(cr, sr, 8.0, 1.0, p->border); + double lum = 0.299 * sw[i].r + 0.587 * sw[i].g + 0.114 * sw[i].b; + gemui_color_t lfg = (lum > 0.58) ? p->bg_main : p->fg_bright; + gemui_draw_text(cr, ui, sr, sw_lbl[i], -4, true, GEMUI_ALIGN_CENTER, lfg); + } + iy += sw_h + 14; + } + + /* ANSI 0..15 swatch strip if available */ + if (xopt && iy + 78 < r.y + r.h) { + int cw = (r.w - pad * 2 - 7 * 8) / 8; + int ch = 32; + for (int i = 0; i < 16; i++) { + gemui_color_t ac; + gemui_color_parse(xopt->colors[GEMINUX_XTH_ST_COLOR0 + i], &ac); + int col = i % 8, row = i / 8; + gemui_rect_t ar = {r.x + pad + col * (cw + 8), iy + row * (ch + 8), cw, ch}; + gemui_fill_round(cr, ar, 6.0, ac); + gemui_stroke_round(cr, ar, 6.0, 1.0, p->border); + } + iy += ch * 2 + 22; + } + + /* Sample footer metadata */ + if (iy + 40 <= r.y + r.h - pad / 2) { + char info[128]; + if (xopt) { + snprintf(info, sizeof(info), "%s | %dpx base | border %dpx | GTK: Geminux-%s", + xopt->is_dark ? "Dark" : "Light", xopt->base_font_size, xopt->dwm_borderpx, xopt->name); + } else { + snprintf(info, sizeof(info), "Applies across X11, DWM, dmenu, st, libgemui, GTK2/3/4, Qt, Dunst"); + } + gemui_draw_text(cr, ui, (gemui_rect_t){r.x + pad, iy, r.w - pad * 2, 38}, + info, -4, false, GEMUI_ALIGN_LEFT, p->fg_muted); + } +} + +static void draw_browse_view(themes_state_t *st, cairo_t *cr, int w, int h) { + const gemui_theme_t *t = gemui_theme(st->app); + char badge[96]; + snprintf(badge, sizeof(badge), "Active: %s", st->active_name[0] ? st->active_name : t->name); + gemui_draw_header(st->app, cr, "\xef\x94\xbf", "Geminux Themes & Editor", badge); + + int hdr_h = 76; + int pad = 20; + int btn_h = 56; + int ftr_h = btn_h * 2 + 16; + int body_y = hdr_h + 16; + int body_h = h - body_y - ftr_h - pad - 14; + int list_w = (w * 43) / 100; + if (list_w < 540) list_w = 540; + + /* Filter box */ + int in_h = 56; + gemui_draw_input(st->app, cr, (gemui_rect_t){pad, body_y, list_w, in_h}, + "Filter themes...", st->filter, false, st->focus_id == HIT_FILTER, HIT_FILTER, 0); + + int ly = body_y + in_h + 12; + int lh = body_h - in_h - 12; + gemui_rect_t list_r = {pad, ly, list_w, lh}; + gemui_fill_round(cr, list_r, 12.0, t->bg_alt_even); + gemui_stroke_round(cr, list_r, 12.0, 1.0, t->border); + + int vis_indices[MAX_THEMES]; + int vis_cnt = 0; + int sel_vis_pos = 0; + for (int i = 0; i < st->count; i++) { + if (ci_contains(st->themes[i].name, st->filter)) { + if (i == st->sel) sel_vis_pos = vis_cnt; + vis_indices[vis_cnt++] = i; + } + } + + int row_h = 54; + int vis_rows = (lh - pad) / row_h; + if (vis_rows < 1) vis_rows = 1; + if (sel_vis_pos < st->scroll) st->scroll = sel_vis_pos; + if (sel_vis_pos >= st->scroll + vis_rows) st->scroll = sel_vis_pos - vis_rows + 1; + if (st->scroll > vis_cnt - vis_rows) st->scroll = vis_cnt - vis_rows; + if (st->scroll < 0) st->scroll = 0; + + for (int i = 0; i < vis_rows && (st->scroll + i) < vis_cnt; i++) { + int idx = vis_indices[st->scroll + i]; + gemui_rect_t rr = {list_r.x + 10, list_r.y + 10 + i * row_h, list_r.w - 20, row_h - 6}; + 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, 10.0, t->sel_bg); + + char lbl[96]; + snprintf(lbl, sizeof(lbl), "%s%s", is_act ? "* " : " ", st->themes[idx].name); + const char *tag = st->themes[idx].is_user ? "[User]" : "[Sys]"; + int tag_w = 112; + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 12, rr.y, rr.w - tag_w - 18, rr.h}, + lbl, 0, is_sel || is_act, GEMUI_ALIGN_LEFT, is_sel ? t->sel_fg : t->fg_main); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + rr.w - tag_w - 10, rr.y, tag_w, rr.h}, + tag, -4, false, GEMUI_ALIGN_RIGHT, is_sel ? t->sel_fg : t->fg_muted); + gemui_hit_add(st->app, rr, HIT_ROW, idx); + } + + /* Preview card */ + int px = list_r.x + list_r.w + pad; + int pw = w - px - pad; + if (st->sel >= 0 && st->sel < st->count && pw > 200) { + geminux_xth_t xprev; + bool has_x = geminux_xth_load_file(st->themes[st->sel].path, &xprev); + draw_mini_preview(st, cr, (gemui_rect_t){px, body_y, pw, body_h}, + &st->themes[st->sel].preview, has_x ? &xprev : NULL); + } + + /* Footer actions (2 tidy rows) */ + int cw = w - pad * 2; + int fy1 = h - pad - ftr_h; + int fy2 = fy1 + btn_h + 14; + int gap = 12; + int bw5 = (cw - gap * 4) / 5; + gemui_draw_button(st->app, cr, (gemui_rect_t){pad, fy1, bw5, btn_h}, + "Edit", HIT_EDIT, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (bw5 + gap), fy1, bw5, btn_h}, + "Duplicate", HIT_DUPLICATE, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (bw5 + gap) * 2, fy1, bw5, btn_h}, + "New", HIT_NEW, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (bw5 + gap) * 3, fy1, bw5, btn_h}, + "Import .xth", HIT_OPEN_IMPORT, 0, false, false, false); + const char *del_lbl = (st->sel < st->count && st->themes[st->sel].is_user && st->themes[st->sel].has_sys) + ? "Reset" : "Delete"; + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + (bw5 + gap) * 4, fy1, bw5, btn_h}, + del_lbl, HIT_DELETE, 0, false, false, false); + + int abw = 240; + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - gap - abw * 2, fy2, abw, btn_h}, + "Apply", HIT_APPLY, 0, true, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - abw, fy2, abw, btn_h}, + "Close", HIT_QUIT, 0, false, false, false); +} + +static void draw_editor_view(themes_state_t *st, cairo_t *cr, int w, int h) { + const gemui_theme_t *t = gemui_theme(st->app); + char badge[96]; + snprintf(badge, sizeof(badge), "Editing: %s", st->ed_xth.name[0] ? st->ed_xth.name : "(unnamed)"); + gemui_draw_header(st->app, cr, "\xef\x87\xbc", "Geminux Theme Editor", badge); int pad = 20; - int top = 92; - int left_w = (w - pad * 3) / 2; - int right_x = pad * 2 + left_w; - int right_w = w - right_x - pad; + int y = 76 + 14; + int cw = w - pad * 2; + int btn_h = 56; + int gap = 14; - gemui_rect_t list = {pad, top, left_w, h - top - pad}; - gemui_fill_round(cr, list, 12, t->bg_bar); - gemui_stroke_round(cr, list, 12, 1.5, t->border); + /* Editor sub-tabs */ + static const char *TABS[] = {"General & Fonts", "UI Colors", "WM & Menu", "Terminal"}; + int tw = (cw - gap * 3) / 4; + for (int i = 0; i < 4; i++) { + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + i * (tw + gap), y, tw, btn_h}, + TABS[i], HIT_ED_TAB, i, false, st->ed_tab == i, false); + } + y += btn_h + 14; - int rh = 70; - int cap = (list.h - 16) / rh; - int start = (st->sel >= cap) ? (st->sel - cap + 1) : 0; - for (int i = start; i < st->num_items && (i - start) < cap; i++) { - gemui_rect_t rr = {list.x + 10, list.y + 8 + (i - start) * rh, list.w - 20, rh - 6}; - bool sel = (i == st->sel); - gemui_fill_round(cr, rr, 10, sel ? t->sel_bg : (i % 2 ? t->bg_alt_odd : t->bg_alt_even)); + int fy = h - btn_h - pad; + int body_h = fy - y - 14; + int left_w = (cw * 46) / 100; + int right_x = pad + left_w + pad; + int right_w = cw - left_w - pad; - const gemui_theme_t *pt = &st->items[i].parsed; - gemui_color_t sw[4] = {pt->bg_main, pt->accent, pt->success, pt->danger}; - for (int k = 0; k < 4; k++) { - gemui_fill_round(cr, (gemui_rect_t){rr.x + 12 + k * 30, rr.y + 20, 24, 24}, 6, sw[k]); + /* Left pane */ + gemui_rect_t left_r = {pad, y, left_w, body_h}; + gemui_fill_round(cr, left_r, 12.0, t->bg_alt_even); + gemui_stroke_round(cr, left_r, 12.0, 1.0, t->border); + + if (st->ed_tab == ED_TAB_GEN) { + int ey = y + 14; + int in_h = 54; + int step_y = 66; + int lbl_w = 210; + int fx = pad + 14 + lbl_w; + int fw = left_w - lbl_w - 28; + + const char *flabels[4] = {"Name", "Mono Font", "UI Font", "Icon Font"}; + char *fbufs[4] = {st->ed_xth.name, st->ed_xth.font_face, st->ed_xth.ui_font_face, st->ed_xth.icon_font_face}; + for (int i = 0; i < 4; i++) { + gemui_draw_text(cr, t, (gemui_rect_t){pad + 14, ey, lbl_w - 8, in_h}, + flabels[i], -2, false, GEMUI_ALIGN_LEFT, t->fg_muted); + bool foc = (st->focus_id == HIT_ED_FIELD && st->focus_buf == fbufs[i]); + gemui_draw_input(st->app, cr, (gemui_rect_t){fx, ey, fw, in_h}, flabels[i], fbufs[i], false, foc, HIT_ED_FIELD, i); + ey += step_y; + } + + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad + 14, ey, left_w - 28, in_h}, + "Dark Palette Variant", st->ed_xth.is_dark != 0, HIT_ED_DARK, 0, false); + ey += step_y; + + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad + 14, ey, left_w - 28, in_h}, + "Auto-sync DWM / dmenu / st", st->ed_auto_sync, HIT_ED_AUTOSYNC, 0, false); + ey += step_y; + + /* Steppers: Font size + DWM borderpx */ + int step_w = 72; + char bsz_lbl[48]; + snprintf(bsz_lbl, sizeof(bsz_lbl), "Base Font Size: %dpx", st->ed_xth.base_font_size); + gemui_draw_text(cr, t, (gemui_rect_t){pad + 14, ey, left_w - 28 - step_w * 2 - 16, in_h}, + bsz_lbl, -2, false, GEMUI_ALIGN_LEFT, t->fg_main); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + left_w - 14 - step_w * 2 - 8, ey, step_w, in_h}, + "-", HIT_ED_FONTSZ, -1, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + left_w - 14 - step_w, ey, step_w, in_h}, + "+", HIT_ED_FONTSZ, 1, false, false, false); + ey += step_y; + + char bpx_lbl[48]; + snprintf(bpx_lbl, sizeof(bpx_lbl), "DWM Border Width: %dpx", st->ed_xth.dwm_borderpx); + gemui_draw_text(cr, t, (gemui_rect_t){pad + 14, ey, left_w - 28 - step_w * 2 - 16, in_h}, + bpx_lbl, -2, false, GEMUI_ALIGN_LEFT, t->fg_main); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + left_w - 14 - step_w * 2 - 8, ey, step_w, in_h}, + "-", HIT_ED_BORDERPX, -1, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + left_w - 14 - step_w, ey, step_w, in_h}, + "+", HIT_ED_BORDERPX, 1, false, false, false); + } else { + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + + int ansi_h = 0; + if (st->ed_tab == ED_TAB_TERM) { + /* Draw 2x8 clickable ANSI palette grid at bottom of left pane */ + ansi_h = 148; + int gx = pad + 14; + int gy = y + body_h - ansi_h - 10; + int gw = (left_w - 28 - 7 * 8) / 8; + int gh = 64; + for (int i = 0; i < 16; i++) { + int slot = GEMINUX_XTH_ST_COLOR0 + i; + gemui_color_t sc; + gemui_color_parse(st->ed_xth.colors[slot], &sc); + int col = i % 8, row = i / 8; + gemui_rect_t cr_tile = {gx + col * (gw + 8), gy + row * (gh + 8), gw, gh}; + gemui_fill_round(cr, cr_tile, 8.0, sc); + gemui_stroke_round(cr, cr_tile, 8.0, st->ed_color_idx == slot ? 3.0 : 1.0, + st->ed_color_idx == slot ? t->highlight : t->border); + char num[8]; + snprintf(num, sizeof(num), "%d", i); + gemui_color_t num_fg = geminux_xth_rel_lum(st->ed_xth.colors[slot]) > 0.35 ? t->bg_main : t->fg_bright; + gemui_draw_text(cr, t, cr_tile, num, -4, true, GEMUI_ALIGN_CENTER, num_fg); + gemui_hit_add(st->app, cr_tile, HIT_ED_SLOT, slot); + } + last = GEMINUX_XTH_ST_REVCURSOR; + } + + int list_h = body_h - ansi_h - 16; + int total_slots = (last >= first) ? (last - first + 1) : 0; + int row_h = 52; + int vis_rows = (list_h - 12) / row_h; + if (vis_rows < 1) vis_rows = 1; + + int rel_sel = (st->ed_color_idx >= first && st->ed_color_idx <= last) ? (st->ed_color_idx - first) : 0; + if (rel_sel < st->ed_scroll) st->ed_scroll = rel_sel; + if (rel_sel >= st->ed_scroll + vis_rows) st->ed_scroll = rel_sel - vis_rows + 1; + if (st->ed_scroll > total_slots - vis_rows) st->ed_scroll = total_slots - vis_rows; + if (st->ed_scroll < 0) st->ed_scroll = 0; + + int sw_sz = 36; + for (int i = 0; i < vis_rows && st->ed_scroll + i < total_slots; i++) { + int slot = first + st->ed_scroll + i; + gemui_rect_t rr = {pad + 10, y + 10 + i * row_h, left_w - 20, row_h - 4}; + bool is_sel = (slot == st->ed_color_idx); + if (is_sel) gemui_fill_round(cr, rr, 8.0, t->sel_bg); + + gemui_color_t sc; + gemui_color_parse(st->ed_xth.colors[slot], &sc); + gemui_rect_t sw_r = {rr.x + 10, rr.y + (rr.h - sw_sz) / 2, sw_sz, sw_sz}; + gemui_fill_round(cr, sw_r, 6.0, sc); + gemui_stroke_round(cr, sw_r, 6.0, 1.0, t->border); + + int hex_w = 148; + gemui_draw_text(cr, t, (gemui_rect_t){sw_r.x + sw_sz + 14, rr.y, rr.w - sw_sz - hex_w - 28, rr.h}, + GEMINUX_XTH_SLOTS[slot].label, -2, is_sel, GEMUI_ALIGN_LEFT, + is_sel ? t->sel_fg : t->fg_main); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + rr.w - hex_w - 8, rr.y, hex_w, rr.h}, + st->ed_xth.colors[slot], -4, false, GEMUI_ALIGN_RIGHT, + is_sel ? t->sel_fg : t->fg_muted); + gemui_hit_add(st->app, rr, HIT_ED_SLOT, slot); } - gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 140, rr.y, rr.w - 152, rr.h}, - st->items[i].name, -1, sel, GEMUI_ALIGN_LEFT, - sel ? t->sel_fg : t->fg_bright); - gemui_hit_add(app, rr, HIT_ITEM, i); } - /* Live Preview Card */ - gemui_rect_t prev = {right_x, top, right_w, h - top - 114}; - const gemui_theme_t *pt = (st->sel >= 0 && st->sel < st->num_items) ? &st->items[st->sel].parsed : t; - gemui_fill_round(cr, prev, 14, pt->bg_main); - gemui_stroke_round(cr, prev, 14, 2.0, pt->border); + /* Right pane: Color Picker (top) + Live Preview (bottom) */ + int pick_h = 376; + gemui_rect_t pick_r = {right_x, y, right_w, pick_h}; + gemui_fill_round(cr, pick_r, 12.0, t->bg_alt_even); + gemui_stroke_round(cr, pick_r, 12.0, 1.0, t->border); - gemui_fill_round(cr, (gemui_rect_t){prev.x + 16, prev.y + 16, prev.w - 32, 64}, 10, pt->bg_header); - gemui_draw_text(cr, pt, (gemui_rect_t){prev.x + 32, prev.y + 16, prev.w - 64, 64}, - pt->name, 2, true, GEMUI_ALIGN_LEFT, pt->fg_bright); + int py = y + 14; + int in_h = 56; + int sw_w = 72; + int hex_w = 240; + int paste_w = 136; + gemui_color_t cur_c; + gemui_color_parse(st->ed_xth.colors[st->ed_color_idx], &cur_c); + gemui_rect_t cur_sw = {right_x + pad, py, sw_w, in_h}; + gemui_fill_round(cr, cur_sw, 8.0, cur_c); + gemui_stroke_round(cr, cur_sw, 8.0, 1.5, t->border); - gemui_fill_round(cr, (gemui_rect_t){prev.x + 24, prev.y + 96, prev.w - 48, 80}, 10, pt->bg_bubble_in); - gemui_draw_text(cr, pt, (gemui_rect_t){prev.x + 40, prev.y + 96, prev.w - 80, 80}, - "Fira Code Ligatures: -> => !== <= >=", -1, false, GEMUI_ALIGN_LEFT, pt->fg_main); + int hex_x = cur_sw.x + sw_w + 12; + gemui_draw_input(st->app, cr, (gemui_rect_t){hex_x, py, hex_w, in_h}, + "#RRGGBB", st->ed_hex, false, st->focus_id == HIT_ED_HEX, HIT_ED_HEX, 0); + gemui_draw_button(st->app, cr, (gemui_rect_t){hex_x + hex_w + 10, py, paste_w, in_h}, + "Paste", HIT_ED_PASTE_HEX, 0, false, false, false); - gemui_fill_round(cr, (gemui_rect_t){prev.x + 24, prev.y + 192, prev.w - 48, 80}, 10, pt->sel_bg); - gemui_draw_text(cr, pt, (gemui_rect_t){prev.x + 40, prev.y + 192, prev.w - 80, 80}, - "Selected Item & Accent Highlight", -1, true, GEMUI_ALIGN_LEFT, pt->sel_fg); + double cr_bg = geminux_xth_contrast_ratio(st->ed_xth.colors[st->ed_color_idx], + st->ed_xth.colors[GEMINUX_XTH_BG_MAIN]); + char cr_txt[48]; + snprintf(cr_txt, sizeof(cr_txt), "vs bgMain %.1f:1", cr_bg); + gemui_draw_text(cr, t, (gemui_rect_t){hex_x + hex_w + paste_w + 18, py, + right_x + right_w - pad - (hex_x + hex_w + paste_w + 18), in_h}, + cr_txt, -4, false, GEMUI_ALIGN_RIGHT, cr_bg >= 4.5 ? t->success : t->fg_muted); + py += in_h + 14; - int sw_w = (prev.w - 48 - 4 * 10) / 5; - gemui_color_t badges[5] = {pt->accent, pt->success, pt->info, pt->warning, pt->danger}; - static const char *labels[5] = {"Accent", "Success", "Info", "Warn", "Danger"}; - for (int i = 0; i < 5; i++) { - gemui_rect_t br = {prev.x + 24 + i * (sw_w + 10), prev.y + 294, sw_w, 68}; - gemui_fill_round(cr, br, 8, badges[i]); - gemui_draw_text(cr, pt, br, labels[i], -3, true, GEMUI_ALIGN_CENTER, pt->bg_main); + /* RGB Sliders */ + int sli_h = 84; + const int rgb_vals[3] = {st->ed_r, st->ed_g, st->ed_b}; + const char *rgb_names[3] = {"Red (R)", "Green (G)", "Blue (B)"}; + const int rgb_hits[3] = {HIT_ED_SLIDER_R, HIT_ED_SLIDER_G, HIT_ED_SLIDER_B}; + for (int ci = 0; ci < 3; ci++) { + char vtxt[16]; + snprintf(vtxt, sizeof(vtxt), "%d", rgb_vals[ci]); + gemui_rect_t sr = {right_x + pad, py, right_w - pad * 2, sli_h}; + st->ed_slider_rect[ci] = sr; + gemui_draw_slider(st->app, cr, sr, rgb_names[ci], (double)rgb_vals[ci] / 255.0, vtxt, + rgb_hits[ci], ci + 1, st->ed_drag_chan == ci + 1); + py += sli_h + 10; } - gemui_draw_button(app, cr, (gemui_rect_t){right_x, h - 94, right_w, 74}, - "Apply Across DWM, st, dmenu, dunst, GTK, Qt, Tk & Apps", HIT_APPLY, 0, true, false, false); + /* Live miniature theme preview */ + int prev_y = y + pick_h + 14; + int prev_h = body_h - pick_h - 14; + if (prev_h >= 120) { + gemui_theme_t live_prev; + build_preview_from_xth(&st->ed_xth, &live_prev); + draw_mini_preview(st, cr, (gemui_rect_t){right_x, prev_y, right_w, prev_h}, &live_prev, &st->ed_xth); + } + + /* Editor Footer */ + int bw = 220; + int sbw = 260; + gemui_draw_button(st->app, cr, (gemui_rect_t){pad, fy, bw, btn_h}, + "Back", HIT_ED_BACK, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + bw + 14, fy, bw, btn_h}, + "Revert", HIT_ED_REVERT, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - 14 - bw - sbw, fy, bw, btn_h}, + "Save", HIT_ED_SAVE, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - sbw, fy, sbw, btn_h}, + "Save & Apply", HIT_ED_SAVE_APPLY, 0, true, false, false); +} + +static void draw_import_view(themes_state_t *st, cairo_t *cr, int w, int h) { + const gemui_theme_t *t = gemui_theme(st->app); + gemui_draw_header(st->app, cr, "\xef\x81\xbc", "Import .xth Theme File", + st->imp_valid ? "Valid .xth" : "Browse or paste path"); + + int pad = 20; + int y = 76 + 14; + int cw = w - pad * 2; + int in_h = 56; + + /* Path input + Paste */ + int pw = 200; + gemui_draw_input(st->app, cr, (gemui_rect_t){pad, y, cw - pw - 12, in_h}, + "/path/to/theme.xth", st->imp_path, false, st->focus_id == HIT_IMP_PATH, HIT_IMP_PATH, 0); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - pw, y, pw, in_h}, + "Paste Path", HIT_IMP_PASTE_PATH, 0, false, false, false); + y += in_h + 12; + + /* Quick directory buttons + filter toggle */ + int qbw = 210; + const char *qnames[3] = {"Home", "Root /", "User Themes"}; + for (int i = 0; i < 3; i++) { + gemui_draw_button(st->app, cr, (gemui_rect_t){pad + i * (qbw + 12), y, qbw, in_h}, + qnames[i], HIT_IMP_QUICK_DIR, i, false, false, false); + } + gemui_draw_toggle(st->app, cr, (gemui_rect_t){pad + (qbw + 12) * 3 + 12, y, 400, in_h}, + "Show all files", st->imp_show_all, HIT_IMP_TOGGLE_ALL, 0, false); + y += in_h + 12; + + int fy = h - in_h - pad; + int ny = fy - in_h - 14; + int body_h = ny - y - 14; + int list_w = (cw * 46) / 100; + gemui_rect_t list_r = {pad, y, list_w, body_h}; + gemui_fill_round(cr, list_r, 12.0, t->bg_alt_even); + gemui_stroke_round(cr, list_r, 12.0, 1.0, t->border); + + int row_h = 50; + int vis_rows = (body_h - 16) / row_h; + if (vis_rows < 1) vis_rows = 1; + if (st->imp_sel < st->imp_scroll) st->imp_scroll = st->imp_sel; + if (st->imp_sel >= st->imp_scroll + vis_rows) st->imp_scroll = st->imp_sel - vis_rows + 1; + if (st->imp_scroll > st->imp_count - vis_rows) st->imp_scroll = st->imp_count - vis_rows; + if (st->imp_scroll < 0) st->imp_scroll = 0; + + for (int i = 0; i < vis_rows && st->imp_scroll + i < st->imp_count; i++) { + int idx = st->imp_scroll + i; + gemui_rect_t rr = {pad + 10, y + 10 + i * row_h, list_w - 20, row_h - 4}; + bool is_sel = (idx == st->imp_sel); + if (is_sel) gemui_fill_round(cr, rr, 8.0, t->sel_bg); + char lbl[280]; + snprintf(lbl, sizeof(lbl), "%s%s", st->imp_items[idx].is_dir ? "[DIR] " : "", st->imp_items[idx].name); + gemui_draw_text(cr, t, (gemui_rect_t){rr.x + 12, rr.y, rr.w - 24, rr.h}, + lbl, -2, is_sel || st->imp_items[idx].is_dir, GEMUI_ALIGN_LEFT, + is_sel ? t->sel_fg : (st->imp_items[idx].is_dir ? t->accent : t->fg_main)); + gemui_hit_add(st->app, rr, HIT_IMP_ITEM, idx); + } + + /* Right preview pane */ + int rx = pad + list_w + pad; + int rw = cw - list_w - pad; + gemui_rect_t pr = {rx, y, rw, body_h}; + if (st->imp_valid) { + gemui_theme_t gp; + build_preview_from_xth(&st->imp_preview, &gp); + draw_mini_preview(st, cr, pr, &gp, &st->imp_preview); + } else { + gemui_fill_round(cr, pr, 12.0, t->bg_alt_even); + gemui_stroke_round(cr, pr, 12.0, 1.0, t->border); + gemui_draw_text(cr, t, pr, "Select or paste a .xth file path to preview", 0, false, GEMUI_ALIGN_CENTER, t->fg_muted); + } + + /* Target name input row */ + int nlbl_w = 240; + gemui_draw_text(cr, t, (gemui_rect_t){pad, ny, nlbl_w, in_h}, + "Install as name", -2, false, GEMUI_ALIGN_LEFT, t->fg_muted); + gemui_draw_input(st->app, cr, (gemui_rect_t){pad + nlbl_w, ny, cw - nlbl_w, in_h}, + "Theme name (optional)", st->imp_name, false, st->focus_id == HIT_IMP_NAME, HIT_IMP_NAME, 0); + + /* Footer */ + int bw = 240; + int sbw = 280; + gemui_draw_button(st->app, cr, (gemui_rect_t){pad, fy, bw, in_h}, + "Back", HIT_IMP_BACK, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - 14 - bw - sbw, fy, bw, in_h}, + "Install", HIT_IMP_DO, 0, false, false, false); + gemui_draw_button(st->app, cr, (gemui_rect_t){w - pad - sbw, fy, sbw, in_h}, + "Install & Apply", HIT_IMP_DO_APPLY, 0, true, false, false); +} + +static void on_theme(gemui_app_t *app, void *ud) { + themes_state_t *st = (themes_state_t *)ud; + const gemui_theme_t *cur = gemui_theme(app); + if (cur && cur->name[0]) + snprintf(st->active_name, sizeof(st->active_name), "%s", cur->name); +} + +static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { + (void)app; + themes_state_t *st = (themes_state_t *)ud; + if (st->view == VIEW_EDITOR) draw_editor_view(st, cr, w, h); + else if (st->view == VIEW_IMPORT) draw_import_view(st, cr, w, h); + else draw_browse_view(st, cr, w, h); +} + +static void apply_text_paste(themes_state_t *st) { + if (!st->focus_buf || st->focus_cap < 2) return; + char clip[512]; + if (!gemui_clipboard_get(st->app, clip, sizeof(clip))) return; + size_t len = 0; + for (size_t i = 0; clip[i] && len + 1 < st->focus_cap; i++) { + unsigned char ch = (unsigned char)clip[i]; + if (ch >= 0x20 && ch != 0x7f) st->focus_buf[len++] = (char)ch; + } + st->focus_buf[len] = '\0'; + if (st->focus_id == HIT_ED_HEX) { + int r = 0, g = 0, b = 0; + if (geminux_xth_parse_hex(st->ed_hex, &r, &g, &b)) { + st->ed_r = r; st->ed_g = g; st->ed_b = b; + ed_commit_rgb_to_slot(st); + } + } else if (st->focus_id == HIT_IMP_PATH) { + imp_refresh_preview(st, true); + } + gemui_request_redraw(st->app); } static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char *utf8, void *ud) { - (void)state; - (void)utf8; - themes_state_t *st = ud; - if (ks == XK_Escape || ks == XK_q) gemui_quit(app, 0); - else if (ks == XK_Up && st->sel > 0) { st->sel--; gemui_request_redraw(app); } - else if (ks == XK_Down && st->sel + 1 < st->num_items) { st->sel++; gemui_request_redraw(app); } - else if (ks == XK_Return || ks == XK_KP_Enter) apply_selected(st); -} + themes_state_t *st = (themes_state_t *)ud; -static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { - (void)btn; - themes_state_t *st = ud; - if (type != GEMUI_PTR_DOWN) return; - const gemui_hit_t *hit = gemui_hit_test(app, x, y); - if (!hit) return; - if (hit->id == HIT_ITEM) { - st->sel = hit->val; - gemui_request_redraw(app); - } else if (hit->id == HIT_APPLY) { - apply_selected(st); + if ((state & ControlMask) && (ks == XK_v || ks == XK_V)) { + apply_text_paste(st); + return; + } + if ((state & ControlMask) && (ks == XK_u || ks == XK_U)) { + if (st->focus_buf) { + st->focus_buf[0] = '\0'; + gemui_request_redraw(app); + } + return; + } + if (ks == XK_Escape) { + if (st->view != VIEW_BROWSE) { + st->view = VIEW_BROWSE; + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(app); + } else if (st->focus_buf) { + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(app); + } else { + gemui_quit(app, 0); + } + return; + } + + /* Editable active text box handling */ + if (st->focus_buf) { + if (ks == XK_BackSpace) { + gemui_utf8_pop_char(st->focus_buf); + if (st->focus_id == HIT_ED_HEX) { + int r = 0, g = 0, b = 0; + if (geminux_xth_parse_hex(st->ed_hex, &r, &g, &b)) { + st->ed_r = r; st->ed_g = g; st->ed_b = b; + snprintf(st->ed_xth.colors[st->ed_color_idx], 16, "#%02x%02x%02x", r, g, b); + if (st->ed_auto_sync && st->ed_tab == ED_TAB_UI) geminux_xth_sync_derived(&st->ed_xth); + } + } else if (st->focus_id == HIT_IMP_PATH) { + imp_refresh_preview(st, true); + } + gemui_request_redraw(app); + return; + } + if (ks == XK_Return || ks == XK_KP_Enter) { + if (st->focus_id == HIT_IMP_PATH) { + char exp[800]; + expand_tilde(st->imp_path, exp, sizeof(exp)); + struct stat sb; + if (stat(exp, &sb) == 0 && S_ISDIR(sb.st_mode)) { + imp_scan_dir(st, exp); + } else { + imp_refresh_preview(st, true); + if (st->imp_valid) do_import_now(st, false); + } + gemui_request_redraw(app); + return; + } + if (st->focus_id == HIT_FILTER && st->view == VIEW_BROWSE) { + apply_selected(st); + return; + } + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(app); + return; + } + if (utf8 && utf8[0]) { + size_t cur = strlen(st->focus_buf); + size_t add = strlen(utf8); + if (cur + add + 1 < st->focus_cap) { + memcpy(st->focus_buf + cur, utf8, add); + st->focus_buf[cur + add] = '\0'; + if (st->focus_id == HIT_ED_HEX) { + int r = 0, g = 0, b = 0; + if (geminux_xth_parse_hex(st->ed_hex, &r, &g, &b)) { + st->ed_r = r; st->ed_g = g; st->ed_b = b; + snprintf(st->ed_xth.colors[st->ed_color_idx], 16, "#%02x%02x%02x", r, g, b); + if (st->ed_auto_sync && st->ed_tab == ED_TAB_UI) geminux_xth_sync_derived(&st->ed_xth); + } + } else if (st->focus_id == HIT_IMP_PATH) { + imp_refresh_preview(st, true); + } + gemui_request_redraw(app); + } + return; + } + } + + /* Unfocused navigation shortcuts */ + if (st->view == VIEW_BROWSE) { + if (ks == XK_q) gemui_quit(app, 0); + else if (ks == XK_Down || ks == XK_j) { + if (st->sel + 1 < st->count) st->sel++; + gemui_request_redraw(app); + } else if (ks == XK_Up || ks == XK_k) { + if (st->sel > 0) st->sel--; + gemui_request_redraw(app); + } else if (ks == XK_Return || ks == XK_space) { + apply_selected(st); + } else if (ks == XK_r) { + reload_themes(st, NULL); + gemui_request_redraw(app); + } + } else if (st->view == VIEW_EDITOR && st->ed_tab != ED_TAB_GEN) { + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + if (ks == XK_Down && st->ed_color_idx < last) { + st->ed_color_idx++; + ed_sync_picker_from_slot(st); + gemui_request_redraw(app); + } else if (ks == XK_Up && st->ed_color_idx > first) { + st->ed_color_idx--; + ed_sync_picker_from_slot(st); + gemui_request_redraw(app); + } } } -int main(void) { +static void update_rgb_slider_from_x(themes_state_t *st, int chan, int mx) { + if (chan < 1 || chan > 3) return; + gemui_rect_t sr = st->ed_slider_rect[chan - 1]; + if (sr.w <= 0) return; + double f = (double)(mx - sr.x) / (double)sr.w; + if (f < 0.0) f = 0.0; + if (f > 1.0) f = 1.0; + int val = (int)(f * 255.0 + 0.5); + if (chan == 1) st->ed_r = val; + else if (chan == 2) st->ed_g = val; + else st->ed_b = val; + ed_commit_rgb_to_slot(st); + gemui_request_redraw(st->app); +} + +static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, void *ud) { + themes_state_t *st = (themes_state_t *)ud; + + if (type == GEMUI_PTR_SCROLL_UP || type == GEMUI_PTR_SCROLL_DOWN) { + int delta = (type == GEMUI_PTR_SCROLL_DOWN) ? 1 : -1; + if (st->view == VIEW_BROWSE) { + int next = st->sel + delta; + if (next >= 0 && next < st->count) { st->sel = next; gemui_request_redraw(app); } + } else if (st->view == VIEW_EDITOR && st->ed_tab != ED_TAB_GEN) { + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + int next = st->ed_color_idx + delta; + if (next >= first && next <= last) { + st->ed_color_idx = next; + ed_sync_picker_from_slot(st); + gemui_request_redraw(app); + } + } else if (st->view == VIEW_IMPORT) { + int next = st->imp_sel + delta; + if (next >= 0 && next < st->imp_count) { st->imp_sel = next; gemui_request_redraw(app); } + } + return; + } + + if (type == GEMUI_PTR_UP) { + st->ed_drag_chan = 0; + return; + } + if (type == GEMUI_PTR_MOVE) { + if (st->view == VIEW_EDITOR && st->ed_drag_chan >= 1 && st->ed_drag_chan <= 3) { + update_rgb_slider_from_x(st, st->ed_drag_chan, x); + } + return; + } + + if (type != GEMUI_PTR_DOWN || btn != Button1) return; + const gemui_hit_t *hit = gemui_hit_test(app, x, y); + if (!hit) { + set_focus_input(st, 0, NULL, 0); + gemui_request_redraw(app); + return; + } + + if (hit->id != HIT_FILTER && hit->id != HIT_ED_FIELD && + hit->id != HIT_ED_HEX && hit->id != HIT_IMP_PATH && hit->id != HIT_IMP_NAME) { + set_focus_input(st, 0, NULL, 0); + } + + if (hit->id == HIT_FILTER) { + set_focus_input(st, HIT_FILTER, st->filter, sizeof(st->filter)); + gemui_request_redraw(app); + } else if (hit->id == HIT_ROW) { + if (st->sel == hit->val) apply_selected(st); + else { st->sel = hit->val; gemui_request_redraw(app); } + } else if (hit->id == HIT_APPLY) { + apply_selected(st); + } else if (hit->id == HIT_EDIT && st->sel >= 0 && st->sel < st->count) { + geminux_xth_t xth; + if (!geminux_xth_load_file(st->themes[st->sel].path, &xth)) { + gemui_show_toast(app, "Failed to load selected .xth", 2000); + return; + } + open_editor(st, &xth, false); + } else if (hit->id == HIT_DUPLICATE && st->sel >= 0 && st->sel < st->count) { + geminux_xth_t xth; + if (!geminux_xth_load_file(st->themes[st->sel].path, &xth)) { + geminux_xth_init_anodized(&xth); + } + char cname[64]; + make_unique_copy_name(st, st->themes[st->sel].name, cname, sizeof(cname)); + snprintf(xth.name, sizeof(xth.name), "%s", cname); + open_editor(st, &xth, true); + } else if (hit->id == HIT_NEW) { + geminux_xth_t xth; + geminux_xth_init_anodized(&xth); + snprintf(xth.name, sizeof(xth.name), "Custom"); + for (int n = 2; name_exists(st, xth.name) && n < 100; n++) { + snprintf(xth.name, sizeof(xth.name), "Custom%d", n); + } + open_editor(st, &xth, true); + } else if (hit->id == HIT_OPEN_IMPORT) { + open_importer(st); + } else if (hit->id == HIT_DELETE && st->sel >= 0 && st->sel < st->count) { + theme_entry_t *e = &st->themes[st->sel]; + if (!e->is_user) { + gemui_show_toast(app, "Built-in themes are read-only; Edit to save override", 2200); + gemui_request_redraw(app); + return; + } + bool was_active = (strcmp(e->name, st->active_name) == 0); + bool had_sys = e->has_sys; + char removed_name[64]; + snprintf(removed_name, sizeof(removed_name), "%s", e->name); + if (remove(e->path) == 0) { + reload_themes(st, removed_name); + if (was_active && had_sys && st->sel < st->count) { + apply_path_now(st, st->themes[st->sel].path); + } + gemui_show_toast(app, had_sys ? "Reset theme to system default" : "Deleted user theme", 2000); + } else { + gemui_show_toast(app, "Failed to delete theme file", 2000); + } + gemui_request_redraw(app); + } else if (hit->id == HIT_QUIT) { + gemui_quit(app, 0); + } else if (hit->id == HIT_ED_TAB) { + st->ed_tab = hit->val; + st->ed_scroll = 0; + int first = 0, last = -1; + ed_tab_slot_range(st->ed_tab, &first, &last); + if (last >= first && (st->ed_color_idx < first || st->ed_color_idx > last)) { + st->ed_color_idx = first; + ed_sync_picker_from_slot(st); + } + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_FIELD) { + char *bufs[4] = {st->ed_xth.name, st->ed_xth.font_face, st->ed_xth.ui_font_face, st->ed_xth.icon_font_face}; + size_t caps[4] = {sizeof(st->ed_xth.name), sizeof(st->ed_xth.font_face), + sizeof(st->ed_xth.ui_font_face), sizeof(st->ed_xth.icon_font_face)}; + if (hit->val >= 0 && hit->val < 4) set_focus_input(st, HIT_ED_FIELD, bufs[hit->val], caps[hit->val]); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_DARK) { + st->ed_xth.is_dark = st->ed_xth.is_dark ? 0 : 1; + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_AUTOSYNC) { + st->ed_auto_sync = !st->ed_auto_sync; + if (st->ed_auto_sync) geminux_xth_sync_derived(&st->ed_xth); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_FONTSZ) { + st->ed_xth.base_font_size += hit->val; + if (st->ed_xth.base_font_size < 20) st->ed_xth.base_font_size = 20; + if (st->ed_xth.base_font_size > 48) st->ed_xth.base_font_size = 48; + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_BORDERPX) { + st->ed_xth.dwm_borderpx += hit->val; + if (st->ed_xth.dwm_borderpx < 1) st->ed_xth.dwm_borderpx = 1; + if (st->ed_xth.dwm_borderpx > 10) st->ed_xth.dwm_borderpx = 10; + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_SLOT) { + st->ed_color_idx = hit->val; + ed_sync_picker_from_slot(st); + set_focus_input(st, HIT_ED_HEX, st->ed_hex, sizeof(st->ed_hex)); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_HEX) { + set_focus_input(st, HIT_ED_HEX, st->ed_hex, sizeof(st->ed_hex)); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_PASTE_HEX) { + set_focus_input(st, HIT_ED_HEX, st->ed_hex, sizeof(st->ed_hex)); + apply_text_paste(st); + } else if (hit->id == HIT_ED_SLIDER_R || hit->id == HIT_ED_SLIDER_G || hit->id == HIT_ED_SLIDER_B) { + st->ed_drag_chan = hit->val; + update_rgb_slider_from_x(st, hit->val, x); + } else if (hit->id == HIT_ED_SAVE) { + editor_save(st, false); + } else if (hit->id == HIT_ED_SAVE_APPLY) { + editor_save(st, true); + } else if (hit->id == HIT_ED_REVERT) { + st->ed_xth = st->ed_orig; + ed_sync_picker_from_slot(st); + gemui_show_toast(st->app, "Reverted unsaved changes", 1400); + gemui_request_redraw(app); + } else if (hit->id == HIT_ED_BACK) { + st->view = VIEW_BROWSE; + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_PATH) { + set_focus_input(st, HIT_IMP_PATH, st->imp_path, sizeof(st->imp_path)); + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_PASTE_PATH) { + set_focus_input(st, HIT_IMP_PATH, st->imp_path, sizeof(st->imp_path)); + apply_text_paste(st); + } else if (hit->id == HIT_IMP_QUICK_DIR) { + const char *home = getenv("HOME"); + char target[512]; + if (hit->val == 1) snprintf(target, sizeof(target), "/"); + else if (hit->val == 2) user_themes_dir(target, sizeof(target)); + else snprintf(target, sizeof(target), "%s", (home && home[0]) ? home : "/"); + mkdir_p_user(target); + imp_scan_dir(st, target); + snprintf(st->imp_path, sizeof(st->imp_path), "%s", st->imp_dir); + st->imp_valid = false; + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_TOGGLE_ALL) { + st->imp_show_all = !st->imp_show_all; + imp_scan_dir(st, st->imp_dir); + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_ITEM && hit->val >= 0 && hit->val < st->imp_count) { + st->imp_sel = hit->val; + const dir_item_t *it = &st->imp_items[hit->val]; + if (it->is_dir) { + char next[1024]; + if (strcmp(it->name, "..") == 0) { + snprintf(next, sizeof(next), "%s", st->imp_dir); + char *slash = strrchr(next, '/'); + if (slash && slash != next) *slash = '\0'; + else snprintf(next, sizeof(next), "/"); + } else { + snprintf(next, sizeof(next), "%s/%s", strcmp(st->imp_dir, "/") == 0 ? "" : st->imp_dir, it->name); + } + imp_scan_dir(st, next); + snprintf(st->imp_path, sizeof(st->imp_path), "%s", st->imp_dir); + st->imp_valid = false; + } else { + snprintf(st->imp_path, sizeof(st->imp_path), "%s/%s", + strcmp(st->imp_dir, "/") == 0 ? "" : st->imp_dir, it->name); + imp_refresh_preview(st, true); + } + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_NAME) { + set_focus_input(st, HIT_IMP_NAME, st->imp_name, sizeof(st->imp_name)); + gemui_request_redraw(app); + } else if (hit->id == HIT_IMP_DO) { + do_import_now(st, false); + } else if (hit->id == HIT_IMP_DO_APPLY) { + do_import_now(st, true); + } else if (hit->id == HIT_IMP_BACK) { + st->view = VIEW_BROWSE; + gemui_request_redraw(app); + } +} + +int main(int argc, char **argv) { + if (argc >= 2 && strcmp(argv[1], "--install") == 0) { + if (argc < 3 || !argv[2][0]) { + fprintf(stderr, "Usage: geminux-themes --install /path/to/Theme.xth [Name]\n"); + return 1; + } + const char *ov = (argc >= 4 && argv[3][0]) ? argv[3] : NULL; + char udir[512], dest[600]; + user_themes_dir(udir, sizeof(udir)); + mkdir_p_user(udir); + if (!geminux_xth_import_file(argv[2], udir, ov, dest, sizeof(dest))) { + fprintf(stderr, "geminux-themes: failed to install theme from %s\n", argv[2]); + return 1; + } + printf("Installed theme to %s\n", dest); + return 0; + } + themes_state_t st; memset(&st, 0, sizeof(st)); - st.app = gemui_create("geminux-themes", "Geminux Unified Themes", 1900, 920, false); + st.app = gemui_create("geminux-themes", "Geminux Themes & Editor", 1900, 920, false); if (!st.app) return 1; - load_themes(&st); - - gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr }; + reload_themes(&st, NULL); + gemui_handlers_t h = { .on_draw = on_draw, .on_key = on_key, .on_ptr = on_ptr, .on_theme = on_theme }; gemui_set_handlers(st.app, &h, &st); int rc = gemui_run(st.app); gemui_destroy(st.app); diff --git a/src/geminux-apps/geminux-xth.h b/src/geminux-apps/geminux-xth.h new file mode 100644 index 0000000..3bd5a33 --- /dev/null +++ b/src/geminux-apps/geminux-xth.h @@ -0,0 +1,541 @@ +/* + * Geminux Unified .xth Theme Parser, Validator & Atomic Writer (header-only POSIX C99/C11) + */ +#ifndef GEMINUX_XTH_H +#define GEMINUX_XTH_H + +#include +#include +#include +#include +#include +#include + +enum { + GEMINUX_XTH_BG_MAIN = 0, + GEMINUX_XTH_BG_BAR, + GEMINUX_XTH_BG_HEADER, + GEMINUX_XTH_BG_FOOTER, + GEMINUX_XTH_BG_OVERLAY, + GEMINUX_XTH_BG_ALT_EVEN, + GEMINUX_XTH_BG_ALT_ODD, + GEMINUX_XTH_BG_INPUT, + GEMINUX_XTH_BG_INPUT_FOCUS, + GEMINUX_XTH_BG_BUTTON, + GEMINUX_XTH_BG_SEARCH, + GEMINUX_XTH_BG_BUBBLE_IN, + GEMINUX_XTH_BG_BUBBLE_OUT, + GEMINUX_XTH_BG_TOAST, + GEMINUX_XTH_FG_MAIN, + GEMINUX_XTH_FG_BRIGHT, + GEMINUX_XTH_FG_MUTED, + GEMINUX_XTH_SEL_BG, + GEMINUX_XTH_SEL_FG, + GEMINUX_XTH_ACCENT, + GEMINUX_XTH_ACCENT_ALT, + GEMINUX_XTH_HIGHLIGHT, + GEMINUX_XTH_BORDER, + GEMINUX_XTH_DIVIDER, + GEMINUX_XTH_SUCCESS, + GEMINUX_XTH_INFO, + GEMINUX_XTH_WARNING, + GEMINUX_XTH_DANGER, + GEMINUX_XTH_DANGER_BG, + GEMINUX_XTH_DWM_NORM_BG, + GEMINUX_XTH_DWM_NORM_FG, + GEMINUX_XTH_DWM_NORM_BD, + GEMINUX_XTH_DWM_SEL_BG, + GEMINUX_XTH_DWM_SEL_FG, + GEMINUX_XTH_DWM_SEL_BD, + GEMINUX_XTH_DMENU_BG, + GEMINUX_XTH_DMENU_FG, + GEMINUX_XTH_DMENU_SEL_BG, + GEMINUX_XTH_DMENU_SEL_FG, + GEMINUX_XTH_DMENU_OUT_BG, + GEMINUX_XTH_DMENU_OUT_FG, + GEMINUX_XTH_ST_BG, + GEMINUX_XTH_ST_FG, + GEMINUX_XTH_ST_CURSOR, + GEMINUX_XTH_ST_REVCURSOR, + GEMINUX_XTH_ST_COLOR0, + GEMINUX_XTH_ST_COLOR15 = GEMINUX_XTH_ST_COLOR0 + 15, + GEMINUX_XTH_COLOR_COUNT +}; + +#define GEMINUX_XTH_MAX_EXTRA 64 + +typedef struct { + const char *key; + const char *label; + const char *def_hex; +} geminux_xth_slot_t; + +typedef struct { + char name[64]; + int is_dark; + char font_face[96]; + char ui_font_face[96]; + char icon_font_face[96]; + char icon_theme[64]; + char qt_theme[64]; + int base_font_size; + int dwm_borderpx; + char colors[GEMINUX_XTH_COLOR_COUNT][16]; + char extra_keys[GEMINUX_XTH_MAX_EXTRA][64]; + char extra_vals[GEMINUX_XTH_MAX_EXTRA][256]; + int n_extra; +} geminux_xth_t; + +static const geminux_xth_slot_t GEMINUX_XTH_SLOTS[GEMINUX_XTH_COLOR_COUNT] = { + {"theme.bgMain", "Main background", "#08090b"}, + {"theme.bgBar", "Bar background", "#0e1014"}, + {"theme.bgHeader", "Header background", "#12151a"}, + {"theme.bgFooter", "Footer background", "#0b0d11"}, + {"theme.bgOverlay", "Overlay / Popup", "#171b22"}, + {"theme.bgAltEven", "Row even", "#101318"}, + {"theme.bgAltOdd", "Row odd", "#14181f"}, + {"theme.bgInput", "Input background", "#161a21"}, + {"theme.bgInputFocus", "Input focused bg", "#1e232c"}, + {"theme.bgButton", "Button background", "#1c212a"}, + {"theme.bgSearch", "Search background", "#191e27"}, + {"theme.bgBubbleIn", "Bubble in", "#181d25"}, + {"theme.bgBubbleOut", "Bubble out", "#252c38"}, + {"theme.bgToast", "Toast background", "#1c222b"}, + {"theme.fgMain", "Main text", "#e4e8ee"}, + {"theme.fgBright", "Bright text", "#f5f7fa"}, + {"theme.fgMuted", "Muted text", "#89929f"}, + {"theme.selBg", "Selection bg", "#38414f"}, + {"theme.selFg", "Selection text", "#f5f7fa"}, + {"theme.accent", "Primary accent", "#cfd6e0"}, + {"theme.accentAlt", "Secondary accent", "#e5eaf0"}, + {"theme.highlight", "Focus / Highlight", "#e2bc72"}, + {"theme.border", "Border", "#2d3440"}, + {"theme.divider", "Divider", "#20252f"}, + {"theme.success", "Success", "#79cf9c"}, + {"theme.info", "Info", "#9eb3c8"}, + {"theme.warning", "Warning", "#e2bc72"}, + {"theme.danger", "Danger", "#e07a7a"}, + {"theme.dangerBg", "Danger background", "#3f1d20"}, + {"dwm.normbgcolor", "DWM bar normal bg", "#0e1014"}, + {"dwm.normfgcolor", "DWM bar normal text", "#e4e8ee"}, + {"dwm.normbordercolor", "DWM inactive border", "#2d3440"}, + {"dwm.selbgcolor", "DWM bar selected bg", "#38414f"}, + {"dwm.selfgcolor", "DWM bar selected text", "#f5f7fa"}, + {"dwm.selbordercolor", "DWM active border", "#cfd6e0"}, + {"dmenu.background", "dmenu background", "#12151a"}, + {"dmenu.foreground", "dmenu text", "#e4e8ee"}, + {"dmenu.selbackground", "dmenu selected bg", "#38414f"}, + {"dmenu.selforeground", "dmenu selected text", "#f5f7fa"}, + {"dmenu.outbackground", "dmenu marked bg", "#191e27"}, + {"dmenu.outforeground", "dmenu marked text", "#cfd6e0"}, + {"st.background", "st background", "#08090b"}, + {"st.foreground", "st foreground", "#e4e8ee"}, + {"st.cursorColor", "st cursor", "#cfd6e0"}, + {"st.revCursorColor", "st reverse cursor", "#08090b"}, + {"st.color0", "ANSI 0 (Black)", "#08090b"}, + {"st.color1", "ANSI 1 (Red)", "#d97878"}, + {"st.color2", "ANSI 2 (Green)", "#79cf9c"}, + {"st.color3", "ANSI 3 (Yellow)", "#e2bc72"}, + {"st.color4", "ANSI 4 (Blue)", "#8ba6c4"}, + {"st.color5", "ANSI 5 (Magenta)", "#b39bc8"}, + {"st.color6", "ANSI 6 (Cyan)", "#84b8be"}, + {"st.color7", "ANSI 7 (White)", "#d5dce4"}, + {"st.color8", "ANSI 8 (Bright Black)", "#5b6370"}, + {"st.color9", "ANSI 9 (Bright Red)", "#eb9494"}, + {"st.color10", "ANSI 10 (Bright Green)","#96deb3"}, + {"st.color11", "ANSI 11 (Bright Yel)", "#edd092"}, + {"st.color12", "ANSI 12 (Bright Blue)", "#a6bdd6"}, + {"st.color13", "ANSI 13 (Bright Mag)", "#cab5dc"}, + {"st.color14", "ANSI 14 (Bright Cyan)", "#a2cdd2"}, + {"st.color15", "ANSI 15 (Bright White)","#f5f7fa"} +}; + +static inline int geminux_xth_hex_nibble(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +static inline bool geminux_xth_parse_hex(const char *s, int *r, int *g, int *b) { + if (!s) return false; + while (*s == ' ' || *s == '\t') s++; + if (*s == '#') s++; + size_t len = strlen(s); + while (len > 0 && (s[len - 1] == ' ' || s[len - 1] == '\t' || s[len - 1] == '\r' || s[len - 1] == '\n')) len--; + if (len == 6) { + int d[6]; + for (int i = 0; i < 6; i++) { + d[i] = geminux_xth_hex_nibble(s[i]); + if (d[i] < 0) return false; + } + if (r) *r = (d[0] << 4) | d[1]; + if (g) *g = (d[2] << 4) | d[3]; + if (b) *b = (d[4] << 4) | d[5]; + return true; + } + if (len == 3) { + int d[3]; + for (int i = 0; i < 3; i++) { + d[i] = geminux_xth_hex_nibble(s[i]); + if (d[i] < 0) return false; + } + if (r) *r = (d[0] << 4) | d[0]; + if (g) *g = (d[1] << 4) | d[1]; + if (b) *b = (d[2] << 4) | d[2]; + return true; + } + return false; +} + +static inline void geminux_xth_format_hex(int r, int g, int b, char *out, size_t sz) { + if (r < 0) r = 0; + if (r > 255) r = 255; + if (g < 0) g = 0; + if (g > 255) g = 255; + if (b < 0) b = 0; + if (b > 255) b = 255; + snprintf(out, sz, "#%02x%02x%02x", r, g, b); +} + +static inline double geminux_xth_rel_lum(const char *hex) { + int r = 0, g = 0, b = 0; + if (!geminux_xth_parse_hex(hex, &r, &g, &b)) return 0.0; + double ch[3] = {r / 255.0, g / 255.0, b / 255.0}; + for (int i = 0; i < 3; i++) { + ch[i] = (ch[i] <= 0.03928) ? (ch[i] / 12.92) : pow((ch[i] + 0.055) / 1.055, 2.4); + } + return 0.2126 * ch[0] + 0.7152 * ch[1] + 0.0722 * ch[2]; +} + +static inline double geminux_xth_contrast_ratio(const char *hex_a, const char *hex_b) { + double l1 = geminux_xth_rel_lum(hex_a); + double l2 = geminux_xth_rel_lum(hex_b); + if (l1 < l2) { + double tmp = l1; + l1 = l2; + l2 = tmp; + } + return (l1 + 0.05) / (l2 + 0.05); +} + +static inline void geminux_xth_sanitize_name(const char *raw, char *out, size_t sz) { + if (!out || sz == 0) return; + out[0] = '\0'; + if (!raw) return; + size_t j = 0; + for (const char *p = raw; *p && j + 1 < sz; p++) { + unsigned char ch = (unsigned char)*p; + if (isalnum(ch) || ch == '-' || ch == '_') { + out[j++] = (char)ch; + } else if (ch == ' ' || ch == '.') { + if (j > 0 && out[j - 1] != '_') out[j++] = '_'; + } + } + while (j > 0 && out[j - 1] == '_') j--; + out[j] = '\0'; + if (strcmp(out, ".") == 0 || strcmp(out, "..") == 0) out[0] = '\0'; +} + +static inline void geminux_xth_init_anodized(geminux_xth_t *x) { + if (!x) return; + memset(x, 0, sizeof(*x)); + snprintf(x->name, sizeof(x->name), "Anodized"); + x->is_dark = 1; + snprintf(x->font_face, sizeof(x->font_face), "Fira Code"); + snprintf(x->ui_font_face, sizeof(x->ui_font_face), "Roboto"); + snprintf(x->icon_font_face, sizeof(x->icon_font_face), "DejaVuSansM Nerd Font"); + snprintf(x->icon_theme, sizeof(x->icon_theme), "Adwaita"); + snprintf(x->qt_theme, sizeof(x->qt_theme), "Fusion"); + x->base_font_size = 32; + x->dwm_borderpx = 4; + for (int i = 0; i < GEMINUX_XTH_COLOR_COUNT; i++) { + snprintf(x->colors[i], sizeof(x->colors[i]), "%s", GEMINUX_XTH_SLOTS[i].def_hex); + } +} + +static inline void geminux_xth_sync_derived(geminux_xth_t *x) { + if (!x) return; + snprintf(x->colors[GEMINUX_XTH_DWM_NORM_BG], 16, "%s", x->colors[GEMINUX_XTH_BG_BAR]); + snprintf(x->colors[GEMINUX_XTH_DWM_NORM_FG], 16, "%s", x->colors[GEMINUX_XTH_FG_MAIN]); + snprintf(x->colors[GEMINUX_XTH_DWM_NORM_BD], 16, "%s", x->colors[GEMINUX_XTH_BORDER]); + snprintf(x->colors[GEMINUX_XTH_DWM_SEL_BG], 16, "%s", x->colors[GEMINUX_XTH_SEL_BG]); + snprintf(x->colors[GEMINUX_XTH_DWM_SEL_FG], 16, "%s", x->colors[GEMINUX_XTH_SEL_FG]); + snprintf(x->colors[GEMINUX_XTH_DWM_SEL_BD], 16, "%s", x->colors[GEMINUX_XTH_ACCENT]); + + snprintf(x->colors[GEMINUX_XTH_DMENU_BG], 16, "%s", x->colors[GEMINUX_XTH_BG_HEADER]); + snprintf(x->colors[GEMINUX_XTH_DMENU_FG], 16, "%s", x->colors[GEMINUX_XTH_FG_MAIN]); + snprintf(x->colors[GEMINUX_XTH_DMENU_SEL_BG], 16, "%s", x->colors[GEMINUX_XTH_SEL_BG]); + snprintf(x->colors[GEMINUX_XTH_DMENU_SEL_FG], 16, "%s", x->colors[GEMINUX_XTH_SEL_FG]); + snprintf(x->colors[GEMINUX_XTH_DMENU_OUT_BG], 16, "%s", x->colors[GEMINUX_XTH_BG_SEARCH]); + snprintf(x->colors[GEMINUX_XTH_DMENU_OUT_FG], 16, "%s", x->colors[GEMINUX_XTH_ACCENT]); + + snprintf(x->colors[GEMINUX_XTH_ST_BG], 16, "%s", x->colors[GEMINUX_XTH_BG_MAIN]); + snprintf(x->colors[GEMINUX_XTH_ST_FG], 16, "%s", x->colors[GEMINUX_XTH_FG_MAIN]); + snprintf(x->colors[GEMINUX_XTH_ST_CURSOR], 16, "%s", x->colors[GEMINUX_XTH_ACCENT]); + snprintf(x->colors[GEMINUX_XTH_ST_REVCURSOR], 16, "%s", x->colors[GEMINUX_XTH_BG_MAIN]); +} + +static inline int geminux_xth_find_slot(const char *key) { + if (!key) return -1; + for (int i = 0; i < GEMINUX_XTH_COLOR_COUNT; i++) { + if (strcmp(GEMINUX_XTH_SLOTS[i].key, key) == 0) return i; + } + return -1; +} + +static inline char *geminux_xth_trim(char *s) { + while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n') s++; + size_t len = strlen(s); + while (len > 0 && (s[len - 1] == ' ' || s[len - 1] == '\t' || s[len - 1] == '\r' || s[len - 1] == '\n')) { + s[--len] = '\0'; + } + return s; +} + +static inline bool geminux_xth_load_file(const char *path, geminux_xth_t *out) { + if (!path || !path[0] || !out) return false; + FILE *f = fopen(path, "rb"); + if (!f) return false; + + unsigned char probe[512]; + size_t nread = fread(probe, 1, sizeof(probe), f); + if (nread == 0) { + fclose(f); + return false; + } + for (size_t i = 0; i < nread; i++) { + if (probe[i] == '\0') { + fclose(f); + return false; + } + } + rewind(f); + + geminux_xth_t tmp; + geminux_xth_init_anodized(&tmp); + tmp.name[0] = '\0'; + int has_is_dark = -1; + int kv_count = 0; + bool has_theme_key = false; + + char line[512]; + while (fgets(line, sizeof(line), f)) { + char *s = geminux_xth_trim(line); + if (!s[0] || s[0] == '!' || s[0] == '#') continue; + char *colon = strchr(s, ':'); + if (!colon || colon == s) continue; + *colon = '\0'; + char *k = geminux_xth_trim(s); + char *v = geminux_xth_trim(colon + 1); + if (!k[0] || !v[0]) continue; + kv_count++; + + if (strncmp(k, "theme.", 6) == 0) has_theme_key = true; + + int slot = geminux_xth_find_slot(k); + if (slot >= 0) { + int r = 0, g = 0, b = 0; + if (geminux_xth_parse_hex(v, &r, &g, &b)) { + geminux_xth_format_hex(r, g, b, tmp.colors[slot], sizeof(tmp.colors[slot])); + } + continue; + } + + if (strcmp(k, "theme.name") == 0) { + snprintf(tmp.name, sizeof(tmp.name), "%s", v); + } else if (strcmp(k, "theme.isDark") == 0) { + has_is_dark = (atoi(v) != 0) ? 1 : 0; + } else if (strcmp(k, "theme.fontFace") == 0) { + snprintf(tmp.font_face, sizeof(tmp.font_face), "%s", v); + } else if (strcmp(k, "theme.uiFontFace") == 0) { + snprintf(tmp.ui_font_face, sizeof(tmp.ui_font_face), "%s", v); + } else if (strcmp(k, "theme.iconFontFace") == 0) { + snprintf(tmp.icon_font_face, sizeof(tmp.icon_font_face), "%s", v); + } else if (strcmp(k, "theme.iconTheme") == 0) { + snprintf(tmp.icon_theme, sizeof(tmp.icon_theme), "%s", v); + } else if (strcmp(k, "theme.qtTheme") == 0) { + snprintf(tmp.qt_theme, sizeof(tmp.qt_theme), "%s", v); + } else if (strcmp(k, "theme.baseFontSize") == 0) { + int sz = atoi(v); + if (sz >= 16 && sz <= 64) tmp.base_font_size = sz; + } else if (strcmp(k, "dwm.borderpx") == 0) { + int bw = atoi(v); + if (bw >= 1 && bw <= 10) tmp.dwm_borderpx = bw; + } else if (strcmp(k, "dwm.background") == 0 || strcmp(k, "dwm.foreground") == 0 || + strcmp(k, "dwm.border") == 0 || strcmp(k, "dwm.selbackground") == 0 || + strcmp(k, "dwm.selforeground") == 0 || strcmp(k, "dwm.selborder") == 0) { + int r = 0, g = 0, b = 0; + if (geminux_xth_parse_hex(v, &r, &g, &b)) { + int alias_idx = (strcmp(k, "dwm.background") == 0) ? GEMINUX_XTH_DWM_NORM_BG + : (strcmp(k, "dwm.foreground") == 0) ? GEMINUX_XTH_DWM_NORM_FG + : (strcmp(k, "dwm.border") == 0) ? GEMINUX_XTH_DWM_NORM_BD + : (strcmp(k, "dwm.selbackground") == 0) ? GEMINUX_XTH_DWM_SEL_BG + : (strcmp(k, "dwm.selforeground") == 0) ? GEMINUX_XTH_DWM_SEL_FG + : GEMINUX_XTH_DWM_SEL_BD; + geminux_xth_format_hex(r, g, b, tmp.colors[alias_idx], 16); + } + } else if (strcmp(k, "theme.gtkTheme") == 0 || strcmp(k, "*TkTheme") == 0 || + strcmp(k, "Xft.dpi") == 0 || strcmp(k, "Xft.antialias") == 0 || + strcmp(k, "Xft.hinting") == 0 || strcmp(k, "Xft.hintstyle") == 0 || + strcmp(k, "Xft.rgba") == 0 || strcmp(k, "Xcursor.theme") == 0 || + strcmp(k, "Xcursor.size") == 0 || strcmp(k, "dwm.font") == 0 || + strcmp(k, "dmenu.font") == 0 || strcmp(k, "dmenu.highlight") == 0 || + strcmp(k, "st.font") == 0 || strcmp(k, "st.termname") == 0) { + /* Managed automatically when serialized */ + } else if (tmp.n_extra < GEMINUX_XTH_MAX_EXTRA) { + bool dup = false; + for (int ei = 0; ei < tmp.n_extra; ei++) { + if (strcmp(tmp.extra_keys[ei], k) == 0) { + snprintf(tmp.extra_vals[ei], sizeof(tmp.extra_vals[ei]), "%s", v); + dup = true; + break; + } + } + if (!dup) { + snprintf(tmp.extra_keys[tmp.n_extra], sizeof(tmp.extra_keys[0]), "%s", k); + snprintf(tmp.extra_vals[tmp.n_extra], sizeof(tmp.extra_vals[0]), "%s", v); + tmp.n_extra++; + } + } + } + fclose(f); + + if (kv_count == 0 || !has_theme_key) return false; + + if (!tmp.name[0]) { + const char *slash = strrchr(path, '/'); + const char *base = slash ? slash + 1 : path; + char raw_name[64]; + snprintf(raw_name, sizeof(raw_name), "%s", base); + size_t bl = strlen(raw_name); + if (bl > 4 && strcmp(raw_name + bl - 4, ".xth") == 0) raw_name[bl - 4] = '\0'; + geminux_xth_sanitize_name(raw_name, tmp.name, sizeof(tmp.name)); + if (!tmp.name[0]) snprintf(tmp.name, sizeof(tmp.name), "Custom"); + } + + if (has_is_dark >= 0) { + tmp.is_dark = has_is_dark; + } else { + tmp.is_dark = (geminux_xth_rel_lum(tmp.colors[GEMINUX_XTH_BG_MAIN]) < 0.20) ? 1 : 0; + } + + *out = tmp; + return true; +} + +static inline bool geminux_xth_save_file(const char *path, const geminux_xth_t *x) { + if (!path || !path[0] || !x) return false; + char safe_name[64]; + geminux_xth_sanitize_name(x->name, safe_name, sizeof(safe_name)); + if (!safe_name[0]) return false; + + int base = (x->base_font_size >= 16 && x->base_font_size <= 64) ? x->base_font_size : 32; + int dwm_px = base + 6; + int dmenu_px = base + 8; + int st_px = base + 12; + int bpx = (x->dwm_borderpx >= 1 && x->dwm_borderpx <= 10) ? x->dwm_borderpx : 4; + const char *ff = x->font_face[0] ? x->font_face : "Fira Code"; + const char *uf = x->ui_font_face[0] ? x->ui_font_face : "Roboto"; + const char *ic = x->icon_font_face[0] ? x->icon_font_face : "DejaVuSansM Nerd Font"; + const char *qt = x->qt_theme[0] ? x->qt_theme : "Fusion"; + const char *it = x->icon_theme[0] ? x->icon_theme : "Adwaita"; + + char tmp_path[640]; + int tn = snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", path); + if (tn <= 0 || (size_t)tn >= sizeof(tmp_path)) return false; + FILE *f = fopen(tmp_path, "w"); + if (!f) return false; + + fprintf(f, "! Geminux Unified Theme: %s (%s)\n", safe_name, x->is_dark ? "Dark" : "Light"); + fprintf(f, "theme.name: %s\n", safe_name); + fprintf(f, "theme.isDark: %d\n", x->is_dark ? 1 : 0); + fprintf(f, "theme.fontFace: %s\n", ff); + fprintf(f, "theme.uiFontFace: %s\n", uf); + fprintf(f, "theme.iconFontFace: %s\n", ic); + fprintf(f, "theme.baseFontSize: %d\n", base); + fprintf(f, "theme.gtkTheme: Geminux-%s\n", safe_name); + fprintf(f, "theme.qtTheme: %s\n", qt); + fprintf(f, "theme.iconTheme: %s\n", it); + fprintf(f, "*TkTheme: gtkTtk\n\n"); + + fprintf(f, "Xft.dpi: 192\n"); + fprintf(f, "Xft.antialias: 1\n"); + fprintf(f, "Xft.hinting: 1\n"); + fprintf(f, "Xft.hintstyle: hintslight\n"); + fprintf(f, "Xft.rgba: rgb\n"); + fprintf(f, "Xcursor.theme: default\n"); + fprintf(f, "Xcursor.size: 64\n\n"); + + for (int i = 0; i <= GEMINUX_XTH_DANGER_BG; i++) { + fprintf(f, "%s: %s\n", GEMINUX_XTH_SLOTS[i].key, x->colors[i]); + } + fprintf(f, "\ndwm.borderpx: %d\n", bpx); + fprintf(f, "dwm.font: %s, %s %dpx\n", ff, ic, dwm_px); + fprintf(f, "dwm.background: %s\n", x->colors[GEMINUX_XTH_DWM_NORM_BG]); + fprintf(f, "dwm.foreground: %s\n", x->colors[GEMINUX_XTH_DWM_NORM_FG]); + fprintf(f, "dwm.border: %s\n", x->colors[GEMINUX_XTH_DWM_NORM_BD]); + fprintf(f, "dwm.selbackground: %s\n", x->colors[GEMINUX_XTH_DWM_SEL_BG]); + fprintf(f, "dwm.selforeground: %s\n", x->colors[GEMINUX_XTH_DWM_SEL_FG]); + fprintf(f, "dwm.selborder: %s\n", x->colors[GEMINUX_XTH_DWM_SEL_BD]); + for (int i = GEMINUX_XTH_DWM_NORM_BG; i <= GEMINUX_XTH_DWM_SEL_BD; i++) { + fprintf(f, "%s: %s\n", GEMINUX_XTH_SLOTS[i].key, x->colors[i]); + } + + fprintf(f, "\ndmenu.font: %s, %s %dpx\n", ff, ic, dmenu_px); + for (int i = GEMINUX_XTH_DMENU_BG; i <= GEMINUX_XTH_DMENU_OUT_FG; i++) { + fprintf(f, "%s: %s\n", GEMINUX_XTH_SLOTS[i].key, x->colors[i]); + } + fprintf(f, "dmenu.highlight: %s\n", x->colors[GEMINUX_XTH_HIGHLIGHT]); + + fprintf(f, "\nst.font: %s:pixelsize=%d:style=Regular:antialias=true:autohint=true\n", ff, st_px); + fprintf(f, "st.termname: xterm-256color\n"); + for (int i = GEMINUX_XTH_ST_BG; i <= GEMINUX_XTH_ST_COLOR15; i++) { + fprintf(f, "%s: %s\n", GEMINUX_XTH_SLOTS[i].key, x->colors[i]); + } + + if (x->n_extra > 0) { + fprintf(f, "\n"); + for (int i = 0; i < x->n_extra; i++) { + fprintf(f, "%s: %s\n", x->extra_keys[i], x->extra_vals[i]); + } + } + + if (fclose(f) != 0) { + remove(tmp_path); + return false; + } + if (rename(tmp_path, path) != 0) { + remove(tmp_path); + return false; + } + return true; +} + +static inline bool geminux_xth_import_file(const char *src_path, const char *dest_dir, + const char *override_name, + char *dest_out, size_t dest_sz) { + if (!src_path || !dest_dir || !dest_dir[0]) return false; + geminux_xth_t x; + if (!geminux_xth_load_file(src_path, &x)) return false; + + char safe_name[64]; + geminux_xth_sanitize_name((override_name && override_name[0]) ? override_name : x.name, + safe_name, sizeof(safe_name)); + if (!safe_name[0]) return false; + snprintf(x.name, sizeof(x.name), "%s", safe_name); + + char dest[600]; + int dn = snprintf(dest, sizeof(dest), "%s/%s.xth", dest_dir, safe_name); + if (dn <= 0 || (size_t)dn >= sizeof(dest)) return false; + if (!geminux_xth_save_file(dest, &x)) return false; + if (dest_out && dest_sz > 0) { + size_t dlen = strlen(dest); + if (dlen >= dest_sz) dlen = dest_sz - 1; + memcpy(dest_out, dest, dlen); + dest_out[dlen] = '\0'; + } + return true; +} + +#endif /* GEMINUX_XTH_H */ diff --git a/src/geminux-daemons/geminux-powerd.c b/src/geminux-daemons/geminux-powerd.c index 19831de..a1cfc1c 100644 --- a/src/geminux-daemons/geminux-powerd.c +++ b/src/geminux-daemons/geminux-powerd.c @@ -1001,23 +1001,21 @@ static void refresh_lid_state(powerd_ctx_t *ctx) { /* gpio-keys SW_LID applies a 64 ms debounce timer on wakeup; wait up to * timeout_ms using poll() so a lid-open wake sees SW_LID == 0 before we - * decide whether to light the backlight. Returns true if an input/lid wake - * event was observed or the lid is open. */ -static bool wait_post_resume_lid_events(powerd_ctx_t *ctx, int timeout_ms) { + * decide whether to light the backlight. Only a lid transition (closed->open) + * or actual input event counts as wake input when resumed with lid open. */ +static bool wait_post_resume_lid_events(powerd_ctx_t *ctx, bool was_lid_closed, int timeout_ms) { bool saw_wake_input = false; refresh_lid_state(ctx); - if (ctx->num_ev <= 0) return !ctx->policy.lid_closed; + if (was_lid_closed && !ctx->policy.lid_closed) saw_wake_input = true; + if (ctx->num_ev <= 0 || saw_wake_input) return saw_wake_input; - uint64_t deadline = ctx->policy.lid_closed ? (monotonic_ms() + (uint64_t)timeout_ms) : 0; + uint64_t deadline = monotonic_ms() + (uint64_t)timeout_ms; struct pollfd pfds[MAX_EVDEVS]; for (;;) { - int slice = 0; - if (ctx->policy.lid_closed) { - uint64_t now = monotonic_ms(); - if (now >= deadline) break; - slice = (int)(deadline - now); - if (slice > 20) slice = 20; - } + uint64_t now = monotonic_ms(); + if (now >= deadline) break; + int slice = (int)(deadline - now); + if (slice > 20) slice = 20; for (int i = 0; i < ctx->num_ev; i++) { pfds[i].fd = ctx->ev_fds[i]; @@ -1035,7 +1033,7 @@ static bool wait_post_resume_lid_events(powerd_ctx_t *ctx, int timeout_ms) { while (read(ctx->ev_fds[i], &iev, sizeof(iev)) == (ssize_t)sizeof(iev)) { if (iev.type == EV_SW && iev.code == SW_LID) { ctx->policy.lid_closed = (iev.value != 0); - if (!ctx->policy.lid_closed) saw_wake_input = true; + if (!ctx->policy.lid_closed && was_lid_closed) saw_wake_input = true; } else if ((iev.type == EV_KEY && iev.value != 0) || iev.type == EV_REL || iev.type == EV_ABS) { ctx->last_input_ms = monotonic_ms(); @@ -1044,10 +1042,8 @@ static bool wait_post_resume_lid_events(powerd_ctx_t *ctx, int timeout_ms) { } } refresh_lid_state(ctx); - if (!ctx->policy.lid_closed) { - saw_wake_input = true; - break; - } + if (was_lid_closed && !ctx->policy.lid_closed) saw_wake_input = true; + if (saw_wake_input) break; } return saw_wake_input; } @@ -1120,6 +1116,9 @@ static void trigger_suspend(powerd_ctx_t *ctx) { apply_cpu_sysfs(ctx, false); return; } + refresh_lid_state(ctx); + bool was_lid_closed = ctx->policy.lid_closed; + bool prev_ac = ctx->policy.on_ac_power; exit_low_power_standby(ctx); prepare_consys_for_suspend(ctx); prepare_cpus_for_suspend(); @@ -1143,14 +1142,26 @@ static void trigger_suspend(powerd_ctx_t *ctx) { } ctx->low_power_standby = false; restore_cpus_after_resume(ctx); - bool saw_wake_input = suspended ? wait_post_resume_lid_events(ctx, 90) : !ctx->policy.lid_closed; + bool saw_wake_input = suspended ? wait_post_resume_lid_events(ctx, was_lid_closed, 90) + : (was_lid_closed && !ctx->policy.lid_closed); refresh_ac_and_hdmi(ctx); + if (!prev_ac && ctx->policy.on_ac_power) { + saw_wake_input = true; + } ctx->suspend_ebusy_on_ac = (!suspended && ctx->policy.on_ac_power); - if (!ctx->policy.lid_closed || !geminux_should_suspend_on_lid(&ctx->policy) || - ctx->suspend_ebusy_on_ac) { + bool want_resleep_open = !was_lid_closed && !ctx->policy.lid_closed && !saw_wake_input && + !ctx->policy.on_ac_power && !ctx->policy.hdmi_connected && + ctx->policy.inhibit_count == 0; + bool want_resleep_closed = ctx->policy.lid_closed && !saw_wake_input && + geminux_should_suspend_on_lid(&ctx->policy); + bool quiet_timer_resleep = suspended && !ctx->suspend_ebusy_on_ac && + (want_resleep_closed || want_resleep_open); + if (!quiet_timer_resleep && + (!ctx->policy.lid_closed || !geminux_should_suspend_on_lid(&ctx->policy) || + ctx->suspend_ebusy_on_ac)) { restore_consys_after_resume(ctx); } - if (!ctx->policy.lid_closed && (suspended || saw_wake_input)) { + if (!ctx->policy.lid_closed && (saw_wake_input || !quiet_timer_resleep)) { ctx->suspend_ebusy_on_ac = false; ctx->idle_stage = IDLE_STAGE_ACTIVE; ctx->last_input_ms = monotonic_ms(); @@ -1160,9 +1171,7 @@ static void trigger_suspend(powerd_ctx_t *ctx) { } else { toggle_backlight(ctx, false); ctx->idle_stage = IDLE_STAGE_LOCKED_BLANK; - if (suspended && !ctx->suspend_ebusy_on_ac && - (ctx->policy.lid_closed ? geminux_should_suspend_on_lid(&ctx->policy) - : (!ctx->policy.on_ac_power && !saw_wake_input))) { + if (quiet_timer_resleep) { arm_timer_ms(ctx->tmr_fd, 2000); } else { arm_timer_ms(ctx->tmr_fd, 0); @@ -1418,7 +1427,10 @@ int main(void) { uint64_t exp = 0; while (read(ctx.tmr_fd, &exp, sizeof(exp)) > 0) {} refresh_ac_and_hdmi(&ctx); - if (ctx.policy.lid_closed && geminux_should_suspend_on_lid(&ctx.policy)) { + if ((ctx.policy.lid_closed && geminux_should_suspend_on_lid(&ctx.policy)) || + (!ctx.policy.lid_closed && ctx.idle_stage == IDLE_STAGE_LOCKED_BLANK && + !ctx.policy.on_ac_power && ctx.policy.inhibit_count == 0 && + !ctx.policy.hdmi_connected)) { trigger_suspend(&ctx); } else { exit_low_power_standby(&ctx); diff --git a/src/libgemui/gemui.c b/src/libgemui/gemui.c index e21e7b6..f664b90 100644 --- a/src/libgemui/gemui.c +++ b/src/libgemui/gemui.c @@ -49,6 +49,7 @@ struct gemui_app { Atom utf8_string; Atom net_wm_state; Atom net_wm_state_fs; + Atom sel_prop; XIM xim; XIC xic; bool fullscreen_override; @@ -265,15 +266,6 @@ void gemui_theme_reload(gemui_app_t *app) { XrmInitialize(); gemui_theme_defaults(&app->theme); - const char *xrm_str = XResourceManagerString(app->dpy); - if (xrm_str) { - XrmDatabase mem_db = XrmGetStringDatabase(xrm_str); - if (mem_db) { - gemui_apply_xrm_db(mem_db, &app->theme); - XrmDestroyDatabase(mem_db); - } - } - const char *home = getenv("HOME"); char path[512]; if (home && home[0]) { @@ -293,6 +285,31 @@ void gemui_theme_reload(gemui_app_t *app) { XrmDestroyDatabase(fdb); } } + + /* Always read XA_RESOURCE_MANAGER directly so live xrdb -load updates win over + disk fallbacks or stale XResourceManagerString() startup caches. */ + Atom actual_type = None; + int actual_format = 0; + unsigned long nitems = 0, bytes_after = 0; + unsigned char *prop = NULL; + if (XGetWindowProperty(app->dpy, app->root, XA_RESOURCE_MANAGER, + 0L, 262144L, False, XA_STRING, &actual_type, + &actual_format, &nitems, &bytes_after, &prop) == Success && prop) { + if (actual_type == XA_STRING && actual_format == 8 && nitems > 0) { + char *buf = malloc(nitems + 1); + if (buf) { + memcpy(buf, prop, nitems); + buf[nitems] = '\0'; + XrmDatabase mem_db = XrmGetStringDatabase(buf); + free(buf); + if (mem_db) { + gemui_apply_xrm_db(mem_db, &app->theme); + XrmDestroyDatabase(mem_db); + } + } + } + XFree(prop); + } } static void gemui_ensure_backbuf(gemui_app_t *app) { @@ -408,6 +425,7 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, StructureNotifyMask | FocusChangeMask; if (fullscreen_override) { swa.override_redirect = True; + swa.event_mask |= VisibilityChangeMask; } unsigned long mask = CWBackPixmap | CWEventMask | (fullscreen_override ? CWOverrideRedirect : 0); @@ -447,8 +465,13 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, app->utf8_string = XInternAtom(dpy, "UTF8_STRING", False); app->net_wm_state = XInternAtom(dpy, "_NET_WM_STATE", False); app->net_wm_state_fs = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); + app->sel_prop = XInternAtom(dpy, "GEMUI_CLIP_DATA", False); XSetWMProtocols(dpy, app->win, &app->wm_delete, 1); + XSelectInput(dpy, app->root, + fullscreen_override ? (PropertyChangeMask | SubstructureNotifyMask) + : PropertyChangeMask); + if (fullscreen_override) { XChangeProperty(dpy, app->win, app->net_wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)&app->net_wm_state_fs, 1); @@ -509,6 +532,55 @@ const gemui_theme_t *gemui_theme(const gemui_app_t *app) { return app ? &app->th int gemui_width(const gemui_app_t *app) { return app ? app->w : 0; } int gemui_height(const gemui_app_t *app) { return app ? app->h : 0; } +static bool gemui_read_selection(gemui_app_t *app, Atom sel, Atom target, char *out, size_t out_sz) { + XDeleteProperty(app->dpy, app->win, app->sel_prop); + XConvertSelection(app->dpy, sel, target, app->sel_prop, app->win, CurrentTime); + XFlush(app->dpy); + + uint64_t deadline = gemui_now_ms() + 150ULL; + int xfd = ConnectionNumber(app->dpy); + XEvent nev; + bool got = false; + while (gemui_now_ms() < deadline) { + XEventsQueued(app->dpy, QueuedAfterReading); + if (XCheckTypedWindowEvent(app->dpy, app->win, SelectionNotify, &nev)) { + got = true; + break; + } + struct pollfd pfd = { .fd = xfd, .events = POLLIN }; + poll(&pfd, 1, 20); + } + if (!got || nev.xselection.property == None) return false; + + Atom da = None; + int di = 0; + unsigned long n = 0, after = 0; + unsigned char *prop = NULL; + bool ok = false; + if (XGetWindowProperty(app->dpy, app->win, app->sel_prop, 0L, (long)(out_sz / 4 + 16), + True, AnyPropertyType, &da, &di, &n, &after, &prop) == Success && prop) { + if (di == 8 && n > 0) { + size_t copy = n < out_sz - 1 ? n : out_sz - 1; + memcpy(out, prop, copy); + out[copy] = '\0'; + ok = true; + } + XFree(prop); + } + return ok; +} + +bool gemui_clipboard_get(gemui_app_t *app, char *out, size_t out_sz) { + if (!app || !out || out_sz == 0) return false; + out[0] = '\0'; + Atom clip = XInternAtom(app->dpy, "CLIPBOARD", False); + if (gemui_read_selection(app, clip, app->utf8_string, out, out_sz)) return true; + if (gemui_read_selection(app, clip, XA_STRING, out, out_sz)) return true; + if (gemui_read_selection(app, XA_PRIMARY, app->utf8_string, out, out_sz)) return true; + if (gemui_read_selection(app, XA_PRIMARY, XA_STRING, out, out_sz)) return true; + return false; +} + int gemui_scale_px(const gemui_app_t *app, int logical_px) { int dpi = app ? app->theme.dpi : 180; return (logical_px * dpi + 48) / 96; @@ -660,6 +732,32 @@ void gemui_flush_draw(gemui_app_t *app) { gemui_render_frame(app); } +static void gemui_keep_fullscreen_on_top(gemui_app_t *app) { + if (!app || !app->fullscreen_override || !app->mapped || !app->dpy || app->win == None) return; + Window root_ret = None, parent_ret = None; + Window *children = NULL; + unsigned int nchildren = 0; + int (*old_handler)(Display *, XErrorEvent *) = XSetErrorHandler(gemui_ignore_xerror); + if (!XQueryTree(app->dpy, app->root, &root_ret, &parent_ret, &children, &nchildren)) { + XSetErrorHandler(old_handler); + return; + } + Window top_viewable = None; + for (int i = (int)nchildren - 1; i >= 0; i--) { + Window cw = children[i]; + XWindowAttributes wa; + if (!XGetWindowAttributes(app->dpy, cw, &wa) || wa.map_state != IsViewable) continue; + top_viewable = cw; + break; + } + if (top_viewable != None && top_viewable != app->win) { + XRaiseWindow(app->dpy, app->win); + XFlush(app->dpy); + } + if (children) XFree(children); + XSetErrorHandler(old_handler); +} + static void gemui_handle_x_events(gemui_app_t *app) { while (XPending(app->dpy) > 0 && app->running) { XEvent ev; @@ -671,11 +769,37 @@ static void gemui_handle_x_events(gemui_app_t *app) { 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); + if (ev.xconfigure.window == app->win) { + 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; + } + } else if (app->fullscreen_override) { + gemui_keep_fullscreen_on_top(app); + } + break; + case MapNotify: + if (app->fullscreen_override && ev.xmap.window != app->win) { + gemui_keep_fullscreen_on_top(app); + } + break; + case VisibilityNotify: + if (app->fullscreen_override && ev.xvisibility.window == app->win && + ev.xvisibility.state != VisibilityUnobscured) { + gemui_keep_fullscreen_on_top(app); + } + 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; } @@ -892,6 +1016,7 @@ static int gemui_draw_pango(cairo_t *cr, const char *face, int px_size, pango_layout_set_font_description(layout, desc); pango_layout_set_width(layout, r.w * PANGO_SCALE); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END); + pango_layout_set_height(layout, 0); pango_layout_set_single_paragraph_mode(layout, True); if (align == GEMUI_ALIGN_CENTER) { pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER); @@ -905,9 +1030,13 @@ static int gemui_draw_pango(cairo_t *cr, const char *face, int px_size, int tw = 0, th = 0; pango_layout_get_pixel_size(layout, &tw, &th); int dy = r.y + (r.h - th) / 2; + cairo_save(cr); + cairo_rectangle(cr, r.x, r.y - 4, r.w, r.h + 8); + cairo_clip(cr); gemui_set_source(cr, c); cairo_move_to(cr, r.x, dy); pango_cairo_show_layout(cr, layout); + cairo_restore(cr); pango_font_description_free(desc); if (!g_active_layout) g_object_unref(layout); @@ -962,7 +1091,13 @@ void gemui_draw_button(gemui_app_t *app, cairo_t *cr, gemui_rect_t r, if (!app) return; const gemui_theme_t *t = &app->theme; gemui_color_t bg = active ? t->sel_bg : (primary ? t->accent : t->bg_button); - gemui_color_t fg = (active || primary) ? t->sel_fg : t->fg_bright; + double bg_lum = 0.299 * bg.r + 0.587 * bg.g + 0.114 * bg.b; + double bgm_lum = 0.299 * t->bg_main.r + 0.587 * t->bg_main.g + 0.114 * t->bg_main.b; + double fgm_lum = 0.299 * t->fg_main.r + 0.587 * t->fg_main.g + 0.114 * t->fg_main.b; + gemui_color_t dark_ink = (bgm_lum < 0.35) ? t->bg_main + : (fgm_lum < 0.35) ? t->fg_main + : (gemui_color_t){0.031, 0.035, 0.043, 1.0, 0xff08090bU}; + gemui_color_t fg = (bg_lum > 0.58) ? dark_ink : ((active || primary) ? t->sel_fg : t->fg_bright); gemui_color_t bd = focused ? t->highlight : (active ? t->sel_bg : t->border); gemui_fill_round(cr, r, 10, bg); diff --git a/src/libgemui/gemui.h b/src/libgemui/gemui.h index 5fd95dd..6e18405 100644 --- a/src/libgemui/gemui.h +++ b/src/libgemui/gemui.h @@ -26,7 +26,7 @@ extern "C" { #define GEMUI_PTR_SCROLL_UP 3 #define GEMUI_PTR_SCROLL_DOWN 4 -#define GEMUI_MAX_HITS 192 +#define GEMUI_MAX_HITS 256 #define GEMUI_MAX_FDS 16 typedef struct { @@ -115,6 +115,7 @@ 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); +bool gemui_clipboard_get(gemui_app_t *app, char *out, size_t out_sz); int gemui_scale_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); diff --git a/src/st/x.c b/src/st/x.c index 2a0e99c..820b0a5 100644 --- a/src/st/x.c +++ b/src/st/x.c @@ -272,6 +272,7 @@ static int frccap = 0; static char *usedfont = NULL; static double usedfontsize = 0; static double defaultfontsize = 0; +static volatile sig_atomic_t st_reload_requested = 0; static char *opt_class = NULL; static char **opt_cmd = NULL; @@ -690,6 +691,11 @@ propnotify(XEvent *e) Atom clipboard = XInternAtom(xw.dpy, "CLIPBOARD", 0); xpev = &e->xproperty; + if (xpev->window == XRootWindow(xw.dpy, xw.scr)) { + if (xpev->atom == XA_RESOURCE_MANAGER && xpev->state != PropertyDelete) + st_reload_requested = 1; + return; + } if (xpev->state == PropertyNewValue && (xpev->atom == XA_PRIMARY || xpev->atom == clipboard)) { @@ -1395,6 +1401,8 @@ xinit(int cols, int rows) xw.selectionmode = XInternAtom(xw.dpy, "_ST_SELMODE", False); updateselectionmodeatom(); + XSelectInput(xw.dpy, XRootWindow(xw.dpy, xw.scr), PropertyChangeMask); + /* pointer cursor setup and blank cursor for hide-while-typing */ { int ev_base = 0, err_base = 0; @@ -2332,7 +2340,6 @@ resize(XEvent *e) 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] = ""; @@ -2354,7 +2361,7 @@ run(void) 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; + struct timespec seltv, *tv, now, lastblink, trigger = {0}; double timeout; /* Waiting for window mapping */ @@ -2377,16 +2384,34 @@ run(void) ttyfd = ttynew(opt_line, shell, opt_io, opt_cmd); cresize(w, h); - signal(SIGUSR1, st_sigusr1); + { + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = st_sigusr1; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sigaction(SIGUSR1, &sa, NULL); + } for (timeout = -1, drawing = 0, lastblink = (struct timespec){0};;) { if (st_reload_requested) { + XColor xmousefg = {0}, xmousebg = {0}; st_reload_requested = 0; + drawing = 0; + timeout = -1; config_init(); xloadcols(); + XSetWindowBackground(xw.dpy, xw.win, dc.col[defaultbg].pixel); + 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); xunloadfonts(); - hbunloadfonts(); - xloadfonts(opt_font ? opt_font : font, 0); + usedfont = opt_font ? opt_font : font; + xloadfonts(usedfont, 0); cresize(win.w, win.h); redraw(); XFlush(xw.dpy); @@ -2437,6 +2462,8 @@ run(void) if (handler[ev.type]) (handler[ev.type])(&ev); } + if (st_reload_requested) + continue; /* * To reduce flicker and tearing, when new content or event @@ -2480,8 +2507,15 @@ run(void) } } +static int st_defaults_saved = 0; +static const char *default_colorname[LEN(colorname)]; +static char *default_font = NULL; +static char *default_termname = NULL; +static char *default_shell = NULL; +static char *st_res_alloc[LEN(resources)]; + int -resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst) +resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst, char **alloc_slot) { char **sdst = dst; int *idst = dst; @@ -2489,8 +2523,8 @@ resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst) char fullname[256]; char fullclass[256]; - char *type; - XrmValue ret; + char *type = NULL; + XrmValue ret = {0}; snprintf(fullname, sizeof(fullname), "%s.%s", opt_name ? opt_name : "st", name); @@ -2498,14 +2532,22 @@ resource_load(XrmDatabase db, char *name, enum resource_type rtype, void *dst) 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)) + if (!XrmGetResource(db, fullname, fullclass, &type, &ret) || + ret.addr == NULL || !type || strncmp("String", type, 64)) return 1; switch (rtype) { - case STRING: - *sdst = strdup(ret.addr); + case STRING: { + char *dup = strdup(ret.addr); + if (dup) { + *sdst = dup; + if (alloc_slot) { + free(*alloc_slot); + *alloc_slot = dup; + } + } break; + } case INTEGER: *idst = strtoul(ret.addr, NULL, 10); break; @@ -2520,6 +2562,7 @@ void config_init(void) { XrmDatabase db = NULL; + XrmDatabase mdb = NULL; ResourcePref *p; Atom actual_type = None; int actual_format = 0; @@ -2528,6 +2571,23 @@ config_init(void) char *type = NULL; XrmValue ret; + if (!st_defaults_saved) { + memcpy(default_colorname, colorname, sizeof(default_colorname)); + default_font = font; + default_termname = termname; + default_shell = shell; + st_defaults_saved = 1; + } else { + for (size_t ri = 0; ri < LEN(resources); ri++) { + free(st_res_alloc[ri]); + st_res_alloc[ri] = NULL; + } + memcpy(colorname, default_colorname, sizeof(default_colorname)); + font = default_font; + termname = default_termname; + shell = default_shell; + } + XrmInitialize(); { const char *home = getenv("HOME"); @@ -2535,23 +2595,33 @@ config_init(void) snprintf(path, sizeof(path), "%s/.Xresources", (home && home[0]) ? home : "/home/user"); db = XrmGetFileDatabase(path); } - if (!db && XGetWindowProperty(xw.dpy, DefaultRootWindow(xw.dpy), XA_RESOURCE_MANAGER, - 0L, 65536L, False, XA_STRING, &actual_type, + if (XGetWindowProperty(xw.dpy, DefaultRootWindow(xw.dpy), XA_RESOURCE_MANAGER, + 0L, 262144L, False, XA_STRING, &actual_type, &actual_format, &nitems, &bytes_after, &prop) == Success && prop) { - if (actual_type == XA_STRING && actual_format == 8 && nitems > 0) - db = XrmGetStringDatabase((const char *)prop); + if (actual_type == XA_STRING && actual_format == 8 && nitems > 0) { + char *buf = malloc(nitems + 1); + if (buf) { + memcpy(buf, prop, nitems); + buf[nitems] = '\0'; + mdb = XrmGetStringDatabase(buf); + free(buf); + } + } XFree(prop); } - if (!db) { - char *resm = XResourceManagerString(xw.dpy); - if (resm) - db = XrmGetStringDatabase(resm); + if (mdb) { + if (db) + XrmMergeDatabases(mdb, &db); + else + db = mdb; } if (!db) return; - for (p = resources; p < resources + LEN(resources); p++) - resource_load(db, p->name, p->type, p->dst); + for (size_t ri = 0; ri < LEN(resources); ri++) { + p = &resources[ri]; + resource_load(db, p->name, p->type, p->dst, &st_res_alloc[ri]); + } /* Also honor unified theme.* keys if st.* keys were omitted */ if (!(XrmGetResource(db, "st.font", "*", &type, &ret) && ret.addr && ret.addr[0])) {