From 7bb27f9373fac1f08e34b57d2164704507c81f4f Mon Sep 17 00:00:00 2001 From: soraefir Date: Thu, 10 Sep 2026 19:54:50 +0200 Subject: [PATCH] improve eww --- .../home/wayland/apps/eww/bar/css/_sys.scss | 7 +- .../wayland/apps/eww/bar/modules/clock.yuck | 26 +- .../wayland/apps/eww/bar/modules/net.yuck | 16 +- .../wayland/apps/eww/bar/modules/sys.yuck | 10 +- .../home/wayland/apps/eww/bar/scripts/_lib.sh | 80 ++++ .../apps/eww/bar/scripts/airplane-mode | 19 +- .../wayland/apps/eww/bar/scripts/brightness | 47 ++- .../wayland/apps/eww/bar/scripts/color-pick | 4 +- .../apps/eww/bar/scripts/do-not-disturb | 18 +- .../home/wayland/apps/eww/bar/scripts/lock | 9 +- .../home/wayland/apps/eww/bar/scripts/media | 3 +- .../apps/eww/bar/scripts/net/bluetooth | 38 -- .../home/wayland/apps/eww/bar/scripts/net/bt | 40 ++ .../apps/eww/bar/scripts/net/bt-devices | 33 -- .../apps/eww/bar/scripts/net/bt-toggle | 3 +- .../home/wayland/apps/eww/bar/scripts/net/net | 130 +++--- .../wayland/apps/eww/bar/scripts/net/netinfo | 79 ---- .../wayland/apps/eww/bar/scripts/nightlight | 23 +- .../wayland/apps/eww/bar/scripts/panel-toggle | 41 +- .../wayland/apps/eww/bar/scripts/power-save | 21 +- .../apps/eww/bar/scripts/powermenu-toggle | 13 +- .../home/wayland/apps/eww/bar/scripts/radio | 388 +++++++++--------- .../wayland/apps/eww/bar/scripts/read-mode | 30 +- .../wayland/apps/eww/bar/scripts/screenshot | 9 +- .../wayland/apps/eww/bar/scripts/sys/battery | 124 +++--- .../wayland/apps/eww/bar/scripts/sys/cpugrid | 49 --- .../wayland/apps/eww/bar/scripts/sys/cputemp | 11 +- .../home/wayland/apps/eww/bar/scripts/sys/gpu | 4 +- .../wayland/apps/eww/bar/scripts/sys/memory | 29 +- .../wayland/apps/eww/bar/scripts/sys/swap | 7 - .../home/wayland/apps/eww/bar/scripts/volume | 75 ++-- .../wayland/apps/eww/bar/scripts/wallpaper | 5 +- .../home/wayland/apps/eww/bar/scripts/weather | 170 ++++---- .../wayland/apps/eww/bar/scripts/workspaces | 211 ++++------ .../wayland/apps/eww/bar/windows/net.yuck | 36 +- .../wayland/apps/eww/bar/windows/popup.yuck | 4 + .../apps/eww/bar/windows/powermenu.yuck | 2 +- .../wayland/apps/eww/bar/windows/radio.yuck | 2 +- .../wayland/apps/eww/bar/windows/sys.yuck | 27 +- modules/home/wayland/apps/eww/default.nix | 153 +++---- modules/home/wayland/apps/kanshi/default.nix | 27 +- modules/home/wayland/hyprland/config.nix | 7 +- packages/default.nix | 2 +- packages/eww-bar/default.nix | 20 + packages/eww-bar/eww-bar.sh | 278 +++++++++++++ packages/eww-ensure-daemon/default.nix | 58 --- 46 files changed, 1296 insertions(+), 1092 deletions(-) create mode 100644 modules/home/wayland/apps/eww/bar/scripts/_lib.sh delete mode 100755 modules/home/wayland/apps/eww/bar/scripts/net/bluetooth create mode 100644 modules/home/wayland/apps/eww/bar/scripts/net/bt delete mode 100755 modules/home/wayland/apps/eww/bar/scripts/net/bt-devices delete mode 100755 modules/home/wayland/apps/eww/bar/scripts/net/netinfo delete mode 100644 modules/home/wayland/apps/eww/bar/scripts/sys/cpugrid delete mode 100755 modules/home/wayland/apps/eww/bar/scripts/sys/swap create mode 100644 packages/eww-bar/default.nix create mode 100644 packages/eww-bar/eww-bar.sh delete mode 100644 packages/eww-ensure-daemon/default.nix diff --git a/modules/home/wayland/apps/eww/bar/css/_sys.scss b/modules/home/wayland/apps/eww/bar/css/_sys.scss index 8807cb5..efc91eb 100644 --- a/modules/home/wayland/apps/eww/bar/css/_sys.scss +++ b/modules/home/wayland/apps/eww/bar/css/_sys.scss @@ -3,7 +3,7 @@ .cpubar { color: $base0C; } .gpubar { color: $base0E; } .membar { color: $base08; } -.batbar { color: $base0B; } +.batbar { color: $base0B; } // overridden by .bat- below .cpubar, .gpubar, .membar, .batbar { @include background-base2; margin: $gaps-window 0; } // Window chrome @@ -91,3 +91,8 @@ background-color: transparent; margin: $popup-scale * 4pt; } + +// Battery colour by state (scripts/sys/battery → .bat-) +.batbar, .bat-ring { color: $base0B; } +.bat-charging { color: $base0C; } +.bat-low { color: $base08; } diff --git a/modules/home/wayland/apps/eww/bar/modules/clock.yuck b/modules/home/wayland/apps/eww/bar/modules/clock.yuck index 180a50a..c5ff4f2 100644 --- a/modules/home/wayland/apps/eww/bar/modules/clock.yuck +++ b/modules/home/wayland/apps/eww/bar/modules/clock.yuck @@ -1,40 +1,38 @@ (defvar date_rev false) +; EWW_TIME ticks every second inside the daemon, so no shell poll is needed. (defwidget clock-mod [] (module (eventbox :onhover "${EWW_CMD} update date_rev=true" :onhoverlost "${EWW_CMD} update date_rev=false" - :onclick "(sleep 0.1 && scripts/panel-toggle clock)" - :onrightclick "(sleep 0.1 && scripts/powermenu-toggle)" + :onclick "scripts/panel-toggle clock" + :onrightclick "scripts/powermenu-toggle" (box :class "datetime" (overlay (box :orientation "v" - (label :show-truncated false - :class "hour" - :text {time.hour}) (label :show-truncated false - :class "minute" - :text {time.minute})) + :class "hour" + :text {formattime(EWW_TIME, "%H")}) + (label :show-truncated false + :class "minute" + :text {formattime(EWW_TIME, "%M")})) (revealer :reveal date_rev (box :class "date" :orientation "v" - (label :show-truncated "false" + (label :show-truncated false :class "day" - :text {time.day}) - (label :show-truncated "false" + :text {formattime(EWW_TIME, "%d")}) + (label :show-truncated false :class "month" - :text {time.month})) + :text {formattime(EWW_TIME, "%m")})) ) ) ) ) ) ) - -(defpoll time :interval "15s" "date '+{\"hour\":\"%H\",\"minute\":\"%M\",\"day\":\"%d\",\"month\":\"%m\"}'") - diff --git a/modules/home/wayland/apps/eww/bar/modules/net.yuck b/modules/home/wayland/apps/eww/bar/modules/net.yuck index 89e86d6..2a9c7e3 100644 --- a/modules/home/wayland/apps/eww/bar/modules/net.yuck +++ b/modules/home/wayland/apps/eww/bar/modules/net.yuck @@ -1,15 +1,15 @@ (deflisten net - :initial '{"wifi":{"connected":false,"enabled":false,"icon":"󰤮","ssid":""},"ethernet":{"connected":false},"usb":{"connected":false}}' + :initial '{"wifi":{"connected":false,"enabled":false,"icon":"󰤮","ssid":"","ip":"","freq":0,"band":"","gen":"","signal":0},"ethernet":{"connected":false,"interface":"","ip":"","speed":""},"usb":{"connected":false,"interface":"","ip":""}}' "scripts/net/net") -(deflisten bluetooth - :initial '{"powered":false,"connected":false,"device":""}' - "scripts/net/bluetooth") +(deflisten bt + :initial '{"powered":false,"connected":false,"device":"","devices":[]}' + "scripts/net/bt") (defwidget net-mod [] (module (eventbox - :onclick "(sleep 0.1 && scripts/panel-toggle net)" + :onclick "scripts/panel-toggle net" (box :orientation "v" (label :class "net-icon ${net.ethernet.connected ? 'net-active' : 'net-dim'}" @@ -25,6 +25,6 @@ :tooltip {net.wifi.connected ? "WiFi: ${net.wifi.ssid}" : "WiFi: Disconnected"} :text {net.wifi.icon}) (label - :class "net-icon ${bluetooth.connected ? 'blt-connected' : bluetooth.powered ? 'blt-on' : 'net-dim'}" - :tooltip {bluetooth.connected ? "Bluetooth: ${bluetooth.device}" : bluetooth.powered ? "Bluetooth: On" : "Bluetooth: Off"} - :text {bluetooth.connected ? "󰂱" : bluetooth.powered ? "󰂯" : "󰂲"}))))) + :class "net-icon ${bt.connected ? 'blt-connected' : bt.powered ? 'blt-on' : 'net-dim'}" + :tooltip {bt.connected ? "Bluetooth: ${bt.device}" : bt.powered ? "Bluetooth: On" : "Bluetooth: Off"} + :text {bt.connected ? "󰂱" : bt.powered ? "󰂯" : "󰂲"}))))) diff --git a/modules/home/wayland/apps/eww/bar/modules/sys.yuck b/modules/home/wayland/apps/eww/bar/modules/sys.yuck index 1fa23f9..de591ee 100644 --- a/modules/home/wayland/apps/eww/bar/modules/sys.yuck +++ b/modules/home/wayland/apps/eww/bar/modules/sys.yuck @@ -1,12 +1,13 @@ (deflisten gpu :initial '{"gfx_pct":0,"mem_pct":0,"media_pct":0,"sclk":0,"mclk":0,"sclk_pct":0,"mclk_pct":0,"vclk":0,"vclk_pct":0,"temp":0,"power":0,"vram_used":0,"vram_total":1}' "scripts/sys/gpu") -(deflisten memory :initial '{"human":{"used":"0G","total":"0G","cached":"0G"},"used":0.0,"total":1.0,"cached":0.0}' "scripts/sys/memory") +(deflisten memory :initial '{"total":1,"used":0,"cached":0,"human":{"total":"0G","used":"0G","cached":"0G"},"swap":{"total":0,"used":0,"human":{"total":"0G","used":"0G"}}}' "scripts/sys/memory") -(deflisten battery :initial '{"visible":false,"percentage":0.0,"color":"#FFFFFF"}' "scripts/sys/battery") +; state: charging | discharging | low | full | idle | none — styled via .bat- +(deflisten battery :initial '{"visible":false,"percentage":0,"wattage":"","status":"","state":"none"}' "scripts/sys/battery") (defwidget sys-mod [] (module (eventbox - :onclick "(sleep 0.1 && scripts/panel-toggle sys)" + :onclick "scripts/panel-toggle sys" (box :orientation "v" (circular-progress :value {EWW_CPU.avg} @@ -25,8 +26,7 @@ :tooltip "RAM ${memory.human.used} / ${memory.human.total}") (circular-progress :value {battery.percentage} - :class "batbar" + :class "batbar bat-${battery.state}" :visible {battery.visible} - :style "color: ${battery.color};" :width 28 :height 28 :thickness 6 :tooltip "Bat ${round(battery.percentage, 0)}% · ${battery.status} @ ${battery.wattage}"))))) diff --git a/modules/home/wayland/apps/eww/bar/scripts/_lib.sh b/modules/home/wayland/apps/eww/bar/scripts/_lib.sh new file mode 100644 index 0000000..8ed1d86 --- /dev/null +++ b/modules/home/wayland/apps/eww/bar/scripts/_lib.sh @@ -0,0 +1,80 @@ +# --------------------------------------------------------------------------- +# Shared helpers for the bar scripts. default.nix inlines this file at the +# top of every wrapped script, right after setting PATH. +# --------------------------------------------------------------------------- + +# Print the payload only when it differs from the previous one. +emit() { + [[ $1 == "${EMIT_LAST-}" ]] && return 0 + EMIT_LAST=$1 + printf '%s\n' "$1" +} + +# Escape a value for use inside a JSON string literal. +jstr() { + local s=$1 + s=${s//\\/\\\\} + s=${s//\"/\\\"} + s=${s//$'\n'/\\n} + s=${s//$'\t'/\\t} + printf '%s' "$s" +} + +# Run a command outside eww's cgroup so a daemon restart cannot kill it +# (hyprlock, wlsunset, mpv, satty…). With -u NAME the transient unit gets a +# fixed name that `systemctl --user stop NAME` can address later. +# detach [-u NAME] CMD ARGS... +detach() { + local unit=() cmd + if [[ $1 == -u ]]; then unit=(--unit "$2"); shift 2; fi + cmd=$(command -v "$1") || { echo "detach: $1 not found" >&2; return 1; } + shift + systemd-run --user --collect --quiet "${unit[@]}" -- "$cmd" "$@" +} + +# Event multiplexer for listener scripts. Producers run in the background +# and write one line per event into a fifo; the main loop re-evaluates the +# state on every event, coalescing bursts into a single refresh. +# +# mux_init +# mux_add FUNC [ARGS] run FUNC in the background, stdout → fifo +# mux_tick SECONDS periodic wake-up +# mux_loop HANDLER HANDLER LINE... for every burst (never returns) +# +# eww terminates a listener by sending SIGTERM to its whole process group, so +# the producers die together with the script. The EXIT trap only removes the +# fifo — it must never `kill 0`: that signals the shell itself, which +# re-enters the trap recursively until bash overflows its stack (the +# bash/volume coredumps in the journal of the previous version). +mux_init() { + MUX_DIR=$(mktemp -d "${XDG_RUNTIME_DIR:-/tmp}/eww-mux.XXXXXX") + MUX_FIFO=$MUX_DIR/events + MUX_PIDS=() + mkfifo "$MUX_FIFO" + # Open read+write once: never blocks, and readers never see EOF. + exec {MUX_FD}<>"$MUX_FIFO" + trap 'mux_cleanup' EXIT +} + +mux_cleanup() { + trap - EXIT + ((${#MUX_PIDS[@]})) && kill "${MUX_PIDS[@]}" 2>/dev/null + rm -rf "$MUX_DIR" +} + +mux_add() { + "$@" >&"$MUX_FD" 2>/dev/null & + MUX_PIDS+=("$!") +} + +_mux_ticker() { while sleep "$1"; do echo tick; done; } +mux_tick() { mux_add _mux_ticker "$1"; } + +mux_loop() { + local handler=$1 line lines + while IFS= read -r -u "$MUX_FD" line; do + lines=("$line") + while IFS= read -r -t 0.15 -u "$MUX_FD" line; do lines+=("$line"); done + "$handler" "${lines[@]}" + done +} diff --git a/modules/home/wayland/apps/eww/bar/scripts/airplane-mode b/modules/home/wayland/apps/eww/bar/scripts/airplane-mode index 6241b71..4b33f62 100644 --- a/modules/home/wayland/apps/eww/bar/scripts/airplane-mode +++ b/modules/home/wayland/apps/eww/bar/scripts/airplane-mode @@ -1,19 +1,18 @@ #!/usr/bin/env bash -is_active() { - rfkill list wifi 2>/dev/null | grep -q "Soft blocked: yes" -} +# rfkill everything (wifi + bluetooth); "active" means the wifi is soft-blocked. +active() { rfkill list wifi 2>/dev/null | grep -q "Soft blocked: yes"; } -case "$1" in - status) - is_active && echo true || echo false - ;; +case ${1:-} in + status) active && echo true || echo false ;; *) - if is_active; then + if active; then rfkill unblock all - echo false + state=false else rfkill block all - echo true + state=true fi + eww update airplane-mode="$state" 2>/dev/null + echo "$state" ;; esac diff --git a/modules/home/wayland/apps/eww/bar/scripts/brightness b/modules/home/wayland/apps/eww/bar/scripts/brightness index 70bd652..2d890ad 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/brightness +++ b/modules/home/wayland/apps/eww/bar/scripts/brightness @@ -1,29 +1,34 @@ #!/usr/bin/env bash +# Backlight brightness (first device under /sys/class/backlight). Refreshes +# on backlight udev events, which also fire for the hardware keys. +# +# brightness status loop (deflisten) +# brightness set PERCENT -BACKLIGHT="/sys/class/backlight" -DEV=$(ls "$BACKLIGHT" 2>/dev/null | head -n1) +dev="" +for d in /sys/class/backlight/*; do + [[ -e $d ]] && { dev=${d##*/}; break; } +done -gen_output() { - if [ -z "$DEV" ]; then - echo '{"percent":0,"available":false}' - return - fi - max=$(cat "$BACKLIGHT/$DEV/max_brightness") - cur=$(cat "$BACKLIGHT/$DEV/actual_brightness" 2>/dev/null || cat "$BACKLIGHT/$DEV/brightness") - percent=$(awk -v c="$cur" -v m="$max" 'BEGIN{print int(c/m*100+0.5)}') - printf '{"percent":%d,"available":true}\n' "$percent" +state() { + [[ -n $dev ]] || { printf '{"percent":0,"available":false}'; return; } + local max cur + max=$(<"/sys/class/backlight/$dev/max_brightness") + cur=$(cat "/sys/class/backlight/$dev/actual_brightness" 2>/dev/null \ + || cat "/sys/class/backlight/$dev/brightness") + printf '{"percent":%d,"available":true}' "$(((cur * 100 + max / 2) / max))" } -case "$1" in - set) - [ -z "$DEV" ] && exit 0 - brightnessctl -d "$DEV" set "${2}%" -q 2>/dev/null - ;; +refresh() { emit "$(state)"; } +_bl_events() { exec udevadm monitor --udev --subsystem-match=backlight; } + +case ${1:-} in + set) [[ -n $dev ]] && brightnessctl -q -d "$dev" set "${2%.*}%" ;; *) - gen_output - [ -z "$DEV" ] && exit 0 - udevadm monitor --udev --subsystem-match=backlight 2>/dev/null | while read -r _; do - gen_output - done + refresh + [[ -n $dev ]] || exit 0 + mux_init + mux_add _bl_events + mux_loop refresh ;; esac diff --git a/modules/home/wayland/apps/eww/bar/scripts/color-pick b/modules/home/wayland/apps/eww/bar/scripts/color-pick index d4a3fd3..2eb8170 100644 --- a/modules/home/wayland/apps/eww/bar/scripts/color-pick +++ b/modules/home/wayland/apps/eww/bar/scripts/color-pick @@ -1,3 +1,5 @@ #!/usr/bin/env bash +# Pick a colour from the screen into the clipboard, detached from eww. eww close popup 2>/dev/null -hyprpicker -a +eww update active-panel= 2>/dev/null +detach hyprpicker -a diff --git a/modules/home/wayland/apps/eww/bar/scripts/do-not-disturb b/modules/home/wayland/apps/eww/bar/scripts/do-not-disturb index 2acf892..8f5cf98 100644 --- a/modules/home/wayland/apps/eww/bar/scripts/do-not-disturb +++ b/modules/home/wayland/apps/eww/bar/scripts/do-not-disturb @@ -1,15 +1,11 @@ #!/usr/bin/env bash -case "$1" in - status) - dunstctl is-paused - ;; +# Pause / resume dunst notifications. +case ${1:-} in + status) dunstctl is-paused ;; *) - if dunstctl is-paused | grep -q true; then - dunstctl set-paused false - echo false - else - dunstctl set-paused true - echo true - fi + dunstctl set-paused toggle + state=$(dunstctl is-paused) + eww update do-not-disturb="$state" 2>/dev/null + echo "$state" ;; esac diff --git a/modules/home/wayland/apps/eww/bar/scripts/lock b/modules/home/wayland/apps/eww/bar/scripts/lock index 71561a4..fb11657 100644 --- a/modules/home/wayland/apps/eww/bar/scripts/lock +++ b/modules/home/wayland/apps/eww/bar/scripts/lock @@ -1,6 +1,9 @@ #!/usr/bin/env bash +# Lock the session. hyprlock runs as its own transient unit so that an eww +# restart can never take the lock screen down with it. +unit=eww-lock eww close popup 2>/dev/null eww close powermenu 2>/dev/null -# swaylock #swaylock-effects -hyprlock -# gtklock \ No newline at end of file +eww update active-panel= 2>/dev/null +systemctl --user is-active --quiet "$unit" && exit 0 +detach -u "$unit" hyprlock diff --git a/modules/home/wayland/apps/eww/bar/scripts/media b/modules/home/wayland/apps/eww/bar/scripts/media index e86b587..032a478 100644 --- a/modules/home/wayland/apps/eww/bar/scripts/media +++ b/modules/home/wayland/apps/eww/bar/scripts/media @@ -1,2 +1,3 @@ #!/usr/bin/env bash -playerctl "$@" +# playerctl pass-through for the media panel buttons. +exec playerctl "$@" diff --git a/modules/home/wayland/apps/eww/bar/scripts/net/bluetooth b/modules/home/wayland/apps/eww/bar/scripts/net/bluetooth deleted file mode 100755 index b562c72..0000000 --- a/modules/home/wayland/apps/eww/bar/scripts/net/bluetooth +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash - -emit() { - local powered=false connected=false device="" - - if bluetoothctl show 2>/dev/null | grep -q "Powered: yes"; then - powered=true - while IFS= read -r line; do - local mac info - mac=$(echo "$line" | awk '{ print $2 }') - info=$(bluetoothctl info "$mac" 2>/dev/null) - if echo "$info" | grep -q "Connected: yes"; then - device=$(echo "$info" | awk -F': ' '/^\tName:/ { print $2; exit }') - connected=true - break - fi - done < <(bluetoothctl devices 2>/dev/null) - fi - - printf '{"powered":%s,"connected":%s,"device":"%s"}\n' "$powered" "$connected" "$device" -} - -emit - -tmp=$(mktemp -d) -pipe="$tmp/bt-events" -mkfifo "$pipe" -trap 'rm -rf "$tmp"; kill 0 2>/dev/null' EXIT INT TERM - -# Poll every 10s as reliable fallback for missed events -(while true; do sleep 10; echo poll; done) > "$pipe" & - -# bluetoothctl monitor for reactive device connect/disconnect events -(bluetoothctl monitor 2>/dev/null | grep --line-buffered -E "Powered|Connected|Device") > "$pipe" & - -while IFS= read -r _ < "$pipe"; do - emit -done diff --git a/modules/home/wayland/apps/eww/bar/scripts/net/bt b/modules/home/wayland/apps/eww/bar/scripts/net/bt new file mode 100644 index 0000000..4220443 --- /dev/null +++ b/modules/home/wayland/apps/eww/bar/scripts/net/bt @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Bluetooth state — adapter power, connected device and the paired/trusted +# device list — from one ObjectManager call on the system bus. Refreshes on +# every org.bluez signal (property changes, devices added/removed) and every +# 60 s. + +fallback='{"powered":false,"connected":false,"device":"","devices":[]}' + +query() { + busctl --system --json=short call org.bluez / org.freedesktop.DBus.ObjectManager GetManagedObjects 2>/dev/null \ + | jq -c ' + .data[0] as $o + | ($o | to_entries | map(.value["org.bluez.Adapter1"] | select(.) | .Powered.data) | any) as $powered + | ($o | to_entries + | map(.value["org.bluez.Device1"] | select(.)) + | map(select(.Paired.data or .Trusted.data or .Connected.data)) + | map({ mac: .Address.data, + name: (.Alias.data // .Name.data // .Address.data), + connected: (.Connected.data // false), + paired: (.Paired.data // false) }) + | sort_by((.connected | not), (.paired | not), .name)) as $devices + | { powered: $powered, + connected: ($devices | any(.connected)), + device: ($devices | map(select(.connected)) | .[0].name // ""), + devices: $devices }' 2>/dev/null +} + +refresh() { + local out + out=$(query) + emit "${out:-$fallback}" +} + +_bt_events() { exec gdbus monitor --system --dest org.bluez; } + +refresh +mux_init +mux_add _bt_events +mux_tick 60 +mux_loop refresh diff --git a/modules/home/wayland/apps/eww/bar/scripts/net/bt-devices b/modules/home/wayland/apps/eww/bar/scripts/net/bt-devices deleted file mode 100755 index dfe7853..0000000 --- a/modules/home/wayland/apps/eww/bar/scripts/net/bt-devices +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash - -emit() { - local first=true arr="" - while IFS= read -r line; do - local mac name connected - mac=$(echo "$line" | awk '{ print $2 }') - name=$(echo "$line" | awk '{ $1=$2=""; sub(/^ +/, ""); print }') - info=$(bluetoothctl info "$mac" 2>/dev/null) - connected=$(echo "$info" | grep -q "Connected: yes" && echo true || echo false) - $first || arr="${arr}," - arr="${arr}{\"mac\":\"${mac}\",\"name\":\"${name}\",\"connected\":${connected}}" - first=false - done < <(bluetoothctl devices 2>/dev/null) - echo "[${arr}]" -} - -emit - -tmp=$(mktemp -d) -pipe="$tmp/bt-dev-events" -mkfifo "$pipe" -trap 'rm -rf "$tmp"; kill 0 2>/dev/null' EXIT INT TERM - -# Poll every 10s as fallback for missed events -(while true; do sleep 10; echo poll; done) > "$pipe" & - -# Reactive updates from D-Bus -(bluetoothctl monitor 2>/dev/null | grep --line-buffered -E "Connected|Device|Powered") > "$pipe" & - -while IFS= read -r _ < "$pipe"; do - emit -done diff --git a/modules/home/wayland/apps/eww/bar/scripts/net/bt-toggle b/modules/home/wayland/apps/eww/bar/scripts/net/bt-toggle index 3ad96f7..bb08919 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/net/bt-toggle +++ b/modules/home/wayland/apps/eww/bar/scripts/net/bt-toggle @@ -1,5 +1,6 @@ #!/usr/bin/env bash -mac="$1" +# Connect or disconnect the bluetooth device with MAC $1. +mac=$1 if bluetoothctl info "$mac" 2>/dev/null | grep -q "Connected: yes"; then bluetoothctl disconnect "$mac" else diff --git a/modules/home/wayland/apps/eww/bar/scripts/net/net b/modules/home/wayland/apps/eww/bar/scripts/net/net index bda2c44..e345953 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/net/net +++ b/modules/home/wayland/apps/eww/bar/scripts/net/net @@ -1,64 +1,84 @@ #!/usr/bin/env bash +# Network state for the bar icons and the net panel: wifi, ethernet and USB +# tethering. Refreshes on link/address changes and every 30 s (signal level). -get_wifi_iface() { - awk 'NR > 2 { gsub(":", "", $1); print $1; exit }' /proc/net/wireless -} - -get_usb_iface() { - ip link 2>/dev/null | awk ' - /^[0-9]+: usb[0-9]/ { gsub(":", "", $2); print $2; exit } - /^[0-9]+: enx/ { gsub(":", "", $2); print $2; exit } - ' -} +wifi_iface() { awk 'NR > 2 { sub(":", "", $1); print $1; exit }' /proc/net/wireless; } +eth_iface() { ip -o link 2>/dev/null | awk '$2 ~ /^en[op]/ { sub(":", "", $2); print $2; exit }'; } +usb_iface() { ip -o link 2>/dev/null | awk '$2 ~ /^(usb[0-9]|enx)/ { sub(":", "", $2); print $2; exit }'; } +ipv4() { ip -4 -o addr show "$1" 2>/dev/null | awk '{ print $4; exit }'; } signal_icon() { - local dbm="$1" - if [ -z "$dbm" ]; then echo "󰤮"; return; fi - if [ "$dbm" -ge -50 ]; then echo "󰤨" - elif [ "$dbm" -ge -60 ]; then echo "󰤥" - elif [ "$dbm" -ge -70 ]; then echo "󰤢" - elif [ "$dbm" -ge -80 ]; then echo "󰤟" + local dbm=${1:-} + [[ -z $dbm ]] && { echo "󰤮"; return; } + if ((dbm >= -50)); then echo "󰤨" + elif ((dbm >= -60)); then echo "󰤥" + elif ((dbm >= -70)); then echo "󰤢" + elif ((dbm >= -80)); then echo "󰤟" else echo "󰤯"; fi } -make_content() { - local wifi_iface eth_iface - - wifi_iface=$(get_wifi_iface) - eth_iface=$(ip link | awk '/^[0-9]+: en[po]/ { gsub(":",""); print $2; exit }') - - # Ethernet - local eth_connected=false - if [ -n "$eth_iface" ]; then - eth_state=$(ip link show "$eth_iface" 2>/dev/null | awk '/state/ { print $9 }') - [ "$eth_state" = "UP" ] && eth_connected=true - fi - - # USB tethering - local usb_iface usb_connected=false - usb_iface=$(get_usb_iface) - if [ -n "$usb_iface" ] && ip -4 addr show "$usb_iface" 2>/dev/null | grep -q "inet "; then - usb_connected=true - fi - - # WiFi - use IP presence as connection indicator (more reliable than wpa_cli) - local wifi_connected=false wifi_enabled=false wifi_icon="󰤮" wifi_ssid="" - if ! rfkill list wlan 2>/dev/null | grep -q "Soft blocked: yes"; then - wifi_enabled=true - fi - if [ -n "$wifi_iface" ] && ip -4 addr show "$wifi_iface" 2>/dev/null | grep -q "inet "; then - wifi_connected=true - wifi_ssid=$(wpa_cli -g "/run/wpa_supplicant/$wifi_iface" status 2>/dev/null \ - | awk -F= '/^ssid=/ { print $2 }') - signal=$(awk -v iface="$wifi_iface" '$1 == iface ":" { gsub(/\./, "", $4); print $4; exit }' /proc/net/wireless) - wifi_icon=$(signal_icon "$signal") - fi - - printf '{"wifi":{"connected":%s,"enabled":%s,"icon":"%s","ssid":"%s"},"ethernet":{"connected":%s},"usb":{"connected":%s}}\n' \ - "$wifi_connected" "$wifi_enabled" "$wifi_icon" "$wifi_ssid" "$eth_connected" "$usb_connected" +band() { + local f=${1:-0} + if ((f >= 5925)); then echo "6 GHz" + elif ((f >= 4900)); then echo "5 GHz" + elif ((f >= 2400)); then echo "2.4 GHz" + else echo ""; fi } -make_content -ip monitor | while read -r _; do - make_content -done +generation() { + case ${1:-} in + 7) echo "Wi-Fi 7" ;; 6) echo "Wi-Fi 6" ;; 5) echo "Wi-Fi 5" ;; 4) echo "Wi-Fi 4" ;; *) echo "" ;; + esac +} + +state() { + local wifi eth usb + wifi=$(wifi_iface) + eth=$(eth_iface) + usb=$(usb_iface) + + local w_enabled=false w_connected=false w_icon="󰤮" w_ssid="" w_ip="" w_freq=0 w_gen="" w_signal=0 wpa + rfkill list wlan 2>/dev/null | grep -q "Soft blocked: yes" || w_enabled=true + if [[ -n $wifi ]]; then + w_ip=$(ipv4 "$wifi") + if [[ -n $w_ip ]]; then + w_connected=true + wpa=$(wpa_cli -g "/run/wpa_supplicant/$wifi" status 2>/dev/null) + w_ssid=$(awk -F= '/^ssid=/ { print $2; exit }' <<<"$wpa") + w_freq=$(awk -F= '/^freq=/ { print $2; exit }' <<<"$wpa") + w_gen=$(generation "$(awk -F= '/^wifi_generation=/ { print $2; exit }' <<<"$wpa")") + w_signal=$(awk -v i="$wifi:" '$1 == i { sub(/\./, "", $4); print $4; exit }' /proc/net/wireless) + w_icon=$(signal_icon "$w_signal") + fi + fi + + local e_connected=false e_ip="" e_speed="" spd + if [[ -n $eth ]] && ip -o link show "$eth" 2>/dev/null | grep -q "state UP"; then + e_connected=true + e_ip=$(ipv4 "$eth") + spd=$(cat "/sys/class/net/$eth/speed" 2>/dev/null) + [[ ${spd:-0} -gt 0 ]] 2>/dev/null && e_speed="${spd} Mbps" + fi + + local u_connected=false u_ip="" + if [[ -n $usb ]]; then + u_ip=$(ipv4 "$usb") + [[ -n $u_ip ]] && u_connected=true + fi + + printf '{"wifi":{"connected":%s,"enabled":%s,"icon":"%s","ssid":"%s","ip":"%s","freq":%s,"band":"%s","gen":"%s","signal":%s},' \ + "$w_connected" "$w_enabled" "$w_icon" "$(jstr "$w_ssid")" "$w_ip" "${w_freq:-0}" "$(band "$w_freq")" "$w_gen" "${w_signal:-0}" + printf '"ethernet":{"connected":%s,"interface":"%s","ip":"%s","speed":"%s"},' \ + "$e_connected" "$eth" "$e_ip" "$e_speed" + printf '"usb":{"connected":%s,"interface":"%s","ip":"%s"}}' \ + "$u_connected" "$usb" "$u_ip" +} + +refresh() { emit "$(state)"; } +_link_events() { exec ip monitor link address; } + +refresh +mux_init +mux_add _link_events +mux_tick 30 +mux_loop refresh diff --git a/modules/home/wayland/apps/eww/bar/scripts/net/netinfo b/modules/home/wayland/apps/eww/bar/scripts/net/netinfo deleted file mode 100755 index 2a313fa..0000000 --- a/modules/home/wayland/apps/eww/bar/scripts/net/netinfo +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env bash - -get_wifi_iface() { - awk 'NR > 2 { gsub(":", "", $1); print $1; exit }' /proc/net/wireless -} - -get_usb_iface() { - ip link 2>/dev/null | awk ' - /^[0-9]+: usb[0-9]/ { gsub(":", "", $2); print $2; exit } - /^[0-9]+: enx/ { gsub(":", "", $2); print $2; exit } - ' -} - -freq_band() { - local f="$1" - if [ "$f" -ge 6000 ] 2>/dev/null; then echo "6 GHz" - elif [ "$f" -ge 5000 ] 2>/dev/null; then echo "5 GHz" - elif [ "$f" -ge 2400 ] 2>/dev/null; then echo "2.4 GHz" - else echo ""; fi -} - -wifi_gen_label() { - case "$1" in - 7) echo "Wi-Fi 7" ;; 6) echo "Wi-Fi 6" ;; - 5) echo "Wi-Fi 5" ;; 4) echo "Wi-Fi 4" ;; - *) echo "" ;; - esac -} - -make_content() { - local wifi_iface eth_iface - wifi_iface=$(get_wifi_iface) - eth_iface=$(ip link | awk '/^[0-9]+: en[po]/ { gsub(":",""); print $2; exit }') - - local wifi_ssid="" wifi_ip="" wifi_freq=0 wifi_band="" wifi_gen="" wifi_signal=0 - if [ -n "$wifi_iface" ] && ip -4 addr show "$wifi_iface" 2>/dev/null | grep -q "inet "; then - local wpa - wpa=$(wpa_cli -g "/run/wpa_supplicant/$wifi_iface" status 2>/dev/null) - wifi_ssid=$(echo "$wpa" | awk -F= '/^ssid=/ { print $2 }') - wifi_ip=$(ip -4 addr show "$wifi_iface" | awk '/inet / { print $2 }') - wifi_freq=$(echo "$wpa" | awk -F= '/^freq=/ { print $2 }') - local gen - gen=$(echo "$wpa" | awk -F= '/^wifi_generation=/ { print $2 }') - wifi_band=$(freq_band "$wifi_freq") - wifi_gen=$(wifi_gen_label "$gen") - wifi_signal=$(awk -v iface="$wifi_iface" \ - '$1 == iface ":" { gsub(/\./, "", $4); print $4; exit }' /proc/net/wireless) - fi - - local eth_ip="" eth_speed="" eth_state="down" - if [ -n "$eth_iface" ]; then - eth_state=$(ip link show "$eth_iface" 2>/dev/null | awk '/state/ { print tolower($9) }') - if [ "$eth_state" = "up" ]; then - eth_ip=$(ip -4 addr show "$eth_iface" | awk '/inet / { print $2 }') - local spd - spd=$(cat /sys/class/net/"$eth_iface"/speed 2>/dev/null) - [ "${spd:-0}" -gt 0 ] 2>/dev/null && eth_speed="${spd} Mbps" - fi - fi - - local usb_iface usb_ip="" - usb_iface=$(get_usb_iface) - if [ -n "$usb_iface" ] && ip -4 addr show "$usb_iface" 2>/dev/null | grep -q "inet "; then - usb_ip=$(ip -4 addr show "$usb_iface" | awk '/inet / { print $2 }') - fi - - # shellcheck disable=SC2059 - printf '{"wifi":{"ssid":"%s","ip":"%s","freq":%s,"band":"%s","gen":"%s","signal":%s},' \ - "$wifi_ssid" "$wifi_ip" "${wifi_freq:-0}" "$wifi_band" "$wifi_gen" "${wifi_signal:-0}" - printf '"ethernet":{"state":"%s","ip":"%s","speed":"%s","interface":"%s"},' \ - "$eth_state" "$eth_ip" "$eth_speed" "${eth_iface:-}" - printf '"usb":{"interface":"%s","ip":"%s"}}\n' \ - "${usb_iface:-}" "$usb_ip" -} - -make_content -ip monitor | while read -r _; do - make_content -done diff --git a/modules/home/wayland/apps/eww/bar/scripts/nightlight b/modules/home/wayland/apps/eww/bar/scripts/nightlight index 5f26012..8d47b0a 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/nightlight +++ b/modules/home/wayland/apps/eww/bar/scripts/nightlight @@ -1,13 +1,22 @@ #!/usr/bin/env bash -case "$1" in - status) - pgrep -x wlsunset >/dev/null 2>&1 && echo true || echo false - ;; +# Toggle wlsunset. It runs as the transient user unit eww-nightlight, so it +# survives eww restarts and can be stopped by name. +unit=eww-nightlight + +active() { systemctl --user is-active --quiet "$unit" || pgrep -x wlsunset >/dev/null; } + +case ${1:-} in + status) active && echo true || echo false ;; *) - if pgrep -x wlsunset >/dev/null 2>&1; then - pkill -x wlsunset && echo false + if active; then + systemctl --user stop "$unit" 2>/dev/null + pkill -x wlsunset + state=false else - wlsunset -T 4500 -t 3200 & echo true + detach -u "$unit" wlsunset -T 4500 -t 3200 + state=true fi + eww update night-light="$state" 2>/dev/null + echo "$state" ;; esac diff --git a/modules/home/wayland/apps/eww/bar/scripts/panel-toggle b/modules/home/wayland/apps/eww/bar/scripts/panel-toggle index b53cf68..e72a773 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/panel-toggle +++ b/modules/home/wayland/apps/eww/bar/scripts/panel-toggle @@ -1,20 +1,35 @@ #!/usr/bin/env bash -PANEL="$1" +# Toggle a panel of the popup window on the focused monitor. +# +# The popup hosts every panel behind revealers, so switching panels while it +# is open is just a variable update (animated, no scripts restarted). It is +# only closed and re-opened when it has to move to another monitor. +panel=$1 +[[ -n $panel ]] || exit 64 -# Atomic lock: flock acquires exclusively or exits immediately. -# Released automatically when the process exits (no trap needed). -exec 9>"/tmp/eww_panel_toggle.lock" +# One toggle at a time; the lock dies with this process. fd 9 is closed for +# every eww call so nothing can inherit it. +exec 9>"${XDG_RUNTIME_DIR:-/tmp}/eww-panel-toggle.lock" flock -n 9 || exit 0 -# Every eww call must run with fd 9 closed (9>&-): `eww open` daemonizes and -# would inherit the fd, holding the flock forever and wedging all later toggles. -CURRENT=$(eww get active-panel 2>/dev/null 9>&- | tr -d '"') +ew() { timeout 5 eww "$@" 9>&-; } -if [ "$CURRENT" = "$PANEL" ]; then - eww update active-panel="" 9>&- - eww close popup 2>/dev/null 9>&- +current=$(ew get active-panel 2>/dev/null | tr -d '"') +popup_screen=$(ew get popup-screen 2>/dev/null | tr -d '"') +screen=$(eww-bar focused) +if ew active-windows 2>/dev/null | grep -qx 'popup: popup'; then open=1; else open=0; fi + +if ((open)) && [[ $current == "$panel" ]]; then + ew update active-panel= + ew close popup +elif ((open)) && [[ -n $screen && $popup_screen == "$screen" ]]; then + ew update active-panel="$panel" else - eww update active-panel="$PANEL" 9>&- - eww close popup 2>/dev/null 9>&- - eww-open-on-current-screen popup 9>&- + ((open)) && ew close popup + ew update active-panel="$panel" popup-screen="$screen" + if [[ -n $screen ]]; then + ew open popup --screen "$screen" + else + ew open popup + fi fi diff --git a/modules/home/wayland/apps/eww/bar/scripts/power-save b/modules/home/wayland/apps/eww/bar/scripts/power-save index ed0d189..5392cb6 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/power-save +++ b/modules/home/wayland/apps/eww/bar/scripts/power-save @@ -1,15 +1,18 @@ #!/usr/bin/env bash -case "$1" in - status) - powerprofilesctl get | grep -q power-saver && echo true || echo false - ;; +# Toggle the power-saver profile (power-profiles-daemon). +active() { [[ $(powerprofilesctl get 2>/dev/null) == power-saver ]]; } + +case ${1:-} in + status) active && echo true || echo false ;; *) - if powerprofilesctl get | grep -q power-saver; then - powerprofilesctl set balanced 2>/dev/null || true - echo false + if active; then + powerprofilesctl set balanced 2>/dev/null + state=false else - powerprofilesctl set power-saver 2>/dev/null || true - echo true + powerprofilesctl set power-saver 2>/dev/null + state=true fi + eww update power-save="$state" 2>/dev/null + echo "$state" ;; esac diff --git a/modules/home/wayland/apps/eww/bar/scripts/powermenu-toggle b/modules/home/wayland/apps/eww/bar/scripts/powermenu-toggle index 9d31c6f..0e08e30 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/powermenu-toggle +++ b/modules/home/wayland/apps/eww/bar/scripts/powermenu-toggle @@ -1,4 +1,11 @@ #!/usr/bin/env bash -eww close popup 2>/dev/null -eww update active-panel="" -eww-open-on-current-screen powermenu --toggle +# Toggle the full-screen power menu on the focused monitor. +ew() { timeout 5 eww "$@"; } +ew close popup 2>/dev/null +ew update active-panel= +screen=$(eww-bar focused) +if [[ -n $screen ]]; then + ew open powermenu --toggle --screen "$screen" +else + ew open powermenu --toggle +fi diff --git a/modules/home/wayland/apps/eww/bar/scripts/radio b/modules/home/wayland/apps/eww/bar/scripts/radio index 14597af..1cd0e8b 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/radio +++ b/modules/home/wayland/apps/eww/bar/scripts/radio @@ -1,229 +1,225 @@ #!/usr/bin/env bash +# Internet radio (radiorecord.ru) and MPRIS "now playing" for the media panel. +# +# radio status loop (deflisten) +# radio start ID tune to station ID +# radio toggle play / stop the last station +# radio stop +# radio vol PERCENT volume of the radio stream, else of the external player +# radio mute mute toggle, same target as vol +# +# mpv runs as the transient user unit eww-radio: independent of the eww +# daemon, and `systemctl --user stop eww-radio` always works. -URL_BASE="https://www.radiorecord.ru/api" -MPV_PID_FILE="/tmp/mpv_radio_pid" -RADIO_ID_FILE="/tmp/radio_id" +api="https://www.radiorecord.ru/api" +unit=eww-radio +state_dir=${XDG_STATE_HOME:-$HOME/.local/state}/eww +cache_dir=${XDG_CACHE_HOME:-$HOME/.cache}/eww +id_file=$state_dir/radio-station +mkdir -p "$state_dir" "$cache_dir" -STATION_IDS='[507,522,523,536,537,42532,42602]' +station_ids='[507,522,523,536,537,42532,42602]' +# Extra stations: {id (unique integer >= 1000000), title, stream_hls, icon_fill_white ("" for none)} +custom_stations='[]' -# Custom (non-radiorecord) stations -# id must be a unique integer >= 1000000 to avoid collision with radiorecord IDs. -# icon_fill_white: URL to station icon image, or "" for none. -CUSTOM_STATIONS='[ -]' +default_song='{"artist":"","song":"","image600":""}' +default_media='{"player":"","status":"Stopped","artist":"","title":"","art":""}' +stations_cache="$cache_dir/radio-stations-$(cksum <<<"$station_ids$custom_stations" | cut -d' ' -f1).json" -STATIONS="[]" -DEFAULT_INFO='{"artist":"","song":"","image600":""}' -DEFAULT_MEDIA='{"player":"","status":"Stopped","artist":"","title":"","art":""}' +# --- stations -------------------------------------------------------------- -PID=$([ -e "$MPV_PID_FILE" ] && cat "$MPV_PID_FILE" || echo 0) -RADIO_ID=$([ -e "$RADIO_ID_FILE" ] && cat "$RADIO_ID_FILE" || echo 0) -PAUSED=$(( PID == 0 ? 1 : 0 )) -INFO="$DEFAULT_INFO" -MEDIA="$DEFAULT_MEDIA" -STATUS="{}" - -get_stations() { - local rr - rr=$(curl -s --compressed "$URL_BASE/stations/" 2>/dev/null \ - | jq --argjson ids "$STATION_IDS" \ - '.result.stations | map(select(.id | IN($ids[]))) | map({id, title, stream_hls, icon_fill_white, "radiorecord": true})' 2>/dev/null) - jq -n \ - --argjson rr "${rr:-[]}" \ - --argjson custom "$CUSTOM_STATIONS" \ - '$rr + ($custom | map(. + {"radiorecord": false}))' -} - -get_song() { - curl -s --compressed "$URL_BASE/station/history/?id=$RADIO_ID" \ - | jq '.result.history[0] | {artist, song, image600}' -} - -get_stream_url() { - echo "$STATIONS" | jq -r --argjson id "$RADIO_ID" 'map(select(.id == $id))[0].stream_hls // empty' -} - -get_player_info() { - local player status artist title art - # exclude mpv (radio) so it never appears as "external player" - player=$(playerctl -l 2>/dev/null | grep -Ev '^mpv' | head -1) - if [ -z "$player" ]; then - echo '{"player":"","status":"Stopped","artist":"","title":"","art":""}' +# Station list, cached for a day (it only changes with station_ids). +stations() { + if [[ -s $stations_cache && -n $(find "$stations_cache" -mmin -1440 2>/dev/null) ]]; then + cat "$stations_cache" return fi - status=$(playerctl -p "$player" status 2>/dev/null || echo "Stopped") - artist=$(playerctl -p "$player" metadata artist 2>/dev/null || echo "") - title=$(playerctl -p "$player" metadata title 2>/dev/null || echo "") - art=$(playerctl -p "$player" metadata mpris:artUrl 2>/dev/null || echo "") - jq -cnr --arg player "$player" --arg status "$status" \ - --arg artist "$artist" --arg title "$title" --arg art "$art" \ - '{player:$player, status:$status, artist:$artist, title:$title, art:$art}' -} - -update_state() { - PID=$([ -e "$MPV_PID_FILE" ] && cat "$MPV_PID_FILE" || echo 0) - RADIO_ID=$([ -e "$RADIO_ID_FILE" ] && cat "$RADIO_ID_FILE" || echo 0) - if [ "$PID" -gt 0 ] && ! kill -0 "$PID" 2>/dev/null; then - PID=0 - rm -f "$MPV_PID_FILE" + local rr out + rr=$(curl -sf --compressed --max-time 8 "$api/stations/" 2>/dev/null \ + | jq -c --argjson ids "$station_ids" \ + '.result.stations | map(select(.id | IN($ids[]))) | map({id, title, stream_hls, icon_fill_white, radiorecord: true})' 2>/dev/null) + if [[ -z $rr || $rr == null ]]; then + [[ -s $stations_cache ]] && { cat "$stations_cache"; return; } + rr='[]' fi - PAUSED=$(( PID == 0 ? 1 : 0 )) + out=$(jq -cn --argjson rr "$rr" --argjson custom "$custom_stations" '$rr + ($custom | map(. + {radiorecord: false}))') + [[ $rr != '[]' ]] && printf '%s\n' "$out" >"$stations_cache" + printf '%s\n' "$out" } -emit_status() { - jq -cnr \ - --argjson stations "${STATIONS:-[]}" \ - --argjson radio_id "${RADIO_ID:-0}" \ - --argjson is_paused "${PAUSED:-1}" \ - --argjson info "${INFO:-$DEFAULT_INFO}" \ - --argjson media "${MEDIA:-$DEFAULT_MEDIA}" \ - '{"is_paused": $is_paused, "song": $info, "radio": $radio_id, "stations": $stations, "media": $media}' +station() { # ID FIELD + jq -r --argjson id "${1:-0}" --arg f "$2" 'first(.[] | select(.id == $id) | .[$f]) // empty' <<<"$STATIONS" } -get_stream_node() { - local name="$1" - wpctl status 2>/dev/null | awk -v pat="$name" ' - /Streams:/ { in_s = 1 } - /Sinks:|Sources:|Clients:/ { in_s = 0 } - in_s && /[0-9]+\./ && tolower($0) ~ tolower(pat) { - match($0, /[0-9]+/); print substr($0, RSTART, RLENGTH); exit - } - ' +current_id() { + local id + id=$(cat "$id_file" 2>/dev/null) + [[ $id =~ ^[0-9]+$ ]] && echo "$id" || echo 0 } -get_mpv_node() { - get_stream_node "mpv" +playing() { systemctl --user is-active --quiet "$unit"; } + +# --- playback -------------------------------------------------------------- + +start() { + local id=${1:-0} url + ((id > 0)) || return 1 + STATIONS=$(stations) + url=$(station "$id" stream_hls) + [[ -n $url && $url != null ]] || return 1 + systemctl --user stop "$unit" 2>/dev/null + detach -u "$unit" mpv --no-video --really-quiet --audio-client-name="$unit" "$url" || return 1 + printf '%s\n' "$id" >"$id_file" +} + +stop() { systemctl --user stop "$unit" 2>/dev/null; } + +# --- volume ---------------------------------------------------------------- + +# PipeWire node id of the first stream whose line matches $1 (case-insensitive). +stream_node() { + wpctl status 2>/dev/null | awk -v pat="$1" ' + /Streams:/ { s = 1; next } + /Sinks:|Sources:|Filters:|Clients:/ { s = 0 } + s && tolower($0) ~ tolower(pat) && match($0, /[0-9]+\./) { print substr($0, RSTART, RLENGTH - 1); exit }' +} + +external_player() { playerctl -l 2>/dev/null | grep -v '^mpv' | head -n1; } + +# "pw NODE" while the radio plays, else "mpris PLAYER" for an external player. +volume_target() { + local n p + if playing; then + n=$(stream_node "$unit") + [[ -n $n ]] && { echo "pw $n"; return; } + fi + p=$(external_player) + [[ -n $p ]] && echo "mpris $p" } get_volume() { - if [ "$PID" -gt 0 ] && kill -0 "$PID" 2>/dev/null; then - local node_id; node_id=$(get_mpv_node) - [ -n "$node_id" ] && wpctl get-volume "$node_id" 2>/dev/null \ - | awk '{printf "%d", $2 * 100}' + local kind target + read -r kind target < <(volume_target) + case $kind in + pw) wpctl get-volume "$target" 2>/dev/null | awk '{ printf "%d", $2 * 100 + 0.5 }' ;; + mpris) playerctl -p "$target" volume 2>/dev/null | awk '{ printf "%d", $1 * 100 + 0.5 }' ;; + esac +} + +set_volume() { + local vol=${1%.*} kind target + read -r kind target < <(volume_target) + case $kind in + pw) wpctl set-volume -l 1.0 "$target" "${vol}%" ;; + mpris) playerctl -p "$target" volume "$(awk -v v="$vol" 'BEGIN { printf "%.2f", v / 100 }')" 2>/dev/null ;; + esac + eww update radio-vol="$vol" 2>/dev/null +} + +toggle_mute() { + local kind target n="" + read -r kind target < <(volume_target) + case $kind in + pw) n=$target ;; + mpris) n=$(stream_node "${target%%.*}") ;; + esac + [[ -n $n ]] || return + wpctl set-mute "$n" toggle + if wpctl get-volume "$n" 2>/dev/null | grep -q MUTED; then muted=true; else muted=false; fi + eww update radio-muted="$muted" 2>/dev/null +} + +# --- status loop ----------------------------------------------------------- + +media_json() { # PLAYER STATUS ARTIST TITLE ART + jq -cn --arg player "$1" --arg status "${2:-Stopped}" --arg artist "$3" --arg title "$4" --arg art "$5" \ + '{player: $player, status: $status, artist: $artist, title: $title, art: $art}' +} + +song_playing() { # ID → SONG from the station history (radiorecord) or the title + local id=$1 fetched + if [[ $(station "$id" radiorecord) == true ]]; then + fetched=$(curl -sf --compressed --max-time 8 "$api/station/history/?id=$id" 2>/dev/null \ + | jq -c '.result.history[0] | {artist: (.artist // ""), song: (.song // ""), image600: (.image600 // "")}' 2>/dev/null) + [[ -n $fetched && $fetched != null ]] && SONG=$fetched else - local player; player=$(playerctl -l 2>/dev/null | grep -Ev '^mpv' | head -1) - [ -n "$player" ] && playerctl -p "$player" volume 2>/dev/null \ - | awk '{printf "%d", $1 * 100}' + SONG=$(jq -cn --arg t "$(station "$id" title)" '{artist: "", song: $t, image600: ""}') fi } -do_vol() { - local vol="${1%.*}" - if [ "$PID" -gt 0 ] && kill -0 "$PID" 2>/dev/null; then - local node_id; node_id=$(get_mpv_node) - [ -n "$node_id" ] && wpctl set-volume "$node_id" "${vol}%" - else - playerctl volume "$(awk -v v="$vol" 'BEGIN{printf "%.2f", v/100}')" 2>/dev/null - fi - eww update radio-vol="$vol" +song_idle() { # ID → placeholder with the station's name and logo + SONG=$(jq -cn --arg t "$(station "$1" title)" --arg i "$(station "$1" icon_fill_white)" \ + '{artist: "", song: $t, image600: $i}') } -do_mute() { - local node_id - if [ "$PID" -gt 0 ] && kill -0 "$PID" 2>/dev/null; then - node_id=$(get_mpv_node) - else - local player; player=$(playerctl -l 2>/dev/null | grep -Ev '^mpv' | head -1) - [ -n "$player" ] && node_id=$(get_stream_node "${player%%.*}") - fi - [ -z "$node_id" ] && return - wpctl set-mute "$node_id" toggle - if wpctl get-volume "$node_id" 2>/dev/null | grep -q MUTED; then - eww update radio-muted=true - else - eww update radio-muted=false +# playerctl --follow line: media\tPLAYER\tSTATUS\tARTIST\tTITLE\tART +media_event() { + local player status artist title art + IFS=$'\t' read -r player status artist title art <<<"$1" + if [[ -z $player ]]; then + MEDIA=$default_media MEDIA_PLAYER="" + elif [[ $player != mpv* ]]; then # the radio and jellyfin are mpv, not "external" + MEDIA=$(media_json "$player" "$status" "$artist" "$title" "$art") + MEDIA_PLAYER=$player fi } -do_start() { - [ "$RADIO_ID" -le 0 ] && return - STATIONS=$(get_stations) - RADIO_URL=$(get_stream_url) - [ -z "$RADIO_URL" ] || [ "$RADIO_URL" = "null" ] && return - [ "$PID" -gt 0 ] && kill "$PID" 2>/dev/null - nohup mpv --no-video --quiet "$RADIO_URL" >/dev/null 2>&1 & - echo $! > "$MPV_PID_FILE" - echo "$RADIO_ID" > "$RADIO_ID_FILE" +_media_events() { + exec playerctl -a --follow metadata \ + --format $'media\t{{playerName}}\t{{status}}\t{{artist}}\t{{title}}\t{{mpris:artUrl}}' +} + +refresh() { + local line id now + for line in "$@"; do + [[ $line == media$'\t'* ]] && media_event "${line#media$'\t'}" + done + # a player that quit without a final metadata line + if [[ -n $MEDIA_PLAYER ]] && ! playerctl -l 2>/dev/null | grep -qx "$MEDIA_PLAYER"; then + MEDIA=$default_media MEDIA_PLAYER="" + fi + + id=$(current_id) + now=$SECONDS + if playing; then + if [[ $PLAYING != true ]] || ((now - LAST_SONG >= 15)); then + PLAYING=true + song_playing "$id" + LAST_SONG=$now + fi + elif [[ $PLAYING != false ]]; then + PLAYING=false + song_idle "$id" + fi + + emit "$(jq -cn --argjson stations "$STATIONS" --argjson radio "$id" \ + --argjson paused "$([[ $PLAYING == true ]] && echo 0 || echo 1)" \ + --argjson song "$SONG" --argjson media "$MEDIA" \ + '{is_paused: $paused, song: $song, radio: $radio, stations: $stations, media: $media}')" + + local v + v=$(get_volume) + if [[ -n $v && $v != "$LAST_VOL" ]]; then + LAST_VOL=$v + eww update radio-vol="$v" 2>/dev/null + fi } status_loop() { - STATIONS=$(get_stations) - echo "$(emit_status)" - - last_pid_check=0 - last_song_fetch=0 - last_media_fetch=0 - - while true; do - now=$(date -u +%s%3N) - - if (( now - last_pid_check > 1000 )); then - update_state - NEW_STATUS=$(emit_status) - if [ "$NEW_STATUS" != "$STATUS" ]; then STATUS=$NEW_STATUS; echo "$STATUS"; fi - last_pid_check=$now - fi - - if (( now - last_song_fetch > 15000 )); then - if [ "$PAUSED" = 0 ]; then - IS_RR=$(echo "$STATIONS" | jq --argjson id "$RADIO_ID" 'map(select(.id == $id))[0].radiorecord // true') - if [ "$IS_RR" = "true" ]; then - FETCHED=$(get_song) - INFO=$(echo "$INFO" "$FETCHED" | jq -s ' - reduce .[] as $x ({}; . + ($x | with_entries(select(.value != null))))') - else - STATION_TITLE=$(echo "$STATIONS" | jq -r --argjson id "$RADIO_ID" 'map(select(.id == $id))[0].title // ""') - INFO=$(jq -cnr --arg title "$STATION_TITLE" '{artist:"",song:$title,image600:""}') - fi - else - STATION_IMG=$(echo "$STATIONS" \ - | jq -r --argjson id "$RADIO_ID" 'map(select(.id == $id))[0].icon_fill_white // ""') - STATION_TITLE=$(echo "$STATIONS" \ - | jq -r --argjson id "$RADIO_ID" 'map(select(.id == $id))[0].title // ""') - INFO=$(jq -cnr --arg img "$STATION_IMG" --arg title "$STATION_TITLE" \ - '{artist:"",song:$title,image600:$img}') - fi - NEW_STATUS=$(emit_status) - if [ "$NEW_STATUS" != "$STATUS" ]; then STATUS=$NEW_STATUS; echo "$STATUS"; fi - last_song_fetch=$now - fi - - if (( now - last_media_fetch > 3000 )); then - MEDIA=$(get_player_info) - NEW_STATUS=$(emit_status) - if [ "$NEW_STATUS" != "$STATUS" ]; then STATUS=$NEW_STATUS; echo "$STATUS"; fi - VOL=$(get_volume) - [ -n "$VOL" ] && eww update radio-vol="$VOL" 2>/dev/null - last_media_fetch=$now - fi - - sleep 0.5 - done + STATIONS=$(stations) + SONG=$default_song MEDIA=$default_media MEDIA_PLAYER="" PLAYING="" LAST_SONG=0 LAST_VOL="" + refresh + mux_init + mux_add _media_events + mux_tick 2 + mux_loop refresh } -case "$1" in - start) - RADIO_ID="$2" - echo "$RADIO_ID" > "$RADIO_ID_FILE" - do_start - ;; - vol) - do_vol "$2" - ;; - mute) - update_state - do_mute - ;; - toggle) - update_state - if [ "$PAUSED" = 1 ]; then - [ "$RADIO_ID" -gt 0 ] && do_start - else - [ "$PID" -gt 0 ] && kill "$PID" 2>/dev/null - rm -f "$MPV_PID_FILE" - fi - ;; - *) - status_loop - ;; +case ${1:-} in + start) start "$2" ;; + stop) stop ;; + toggle) if playing; then stop; else start "$(current_id)"; fi ;; + vol) set_volume "$2" ;; + mute) toggle_mute ;; + *) status_loop ;; esac diff --git a/modules/home/wayland/apps/eww/bar/scripts/read-mode b/modules/home/wayland/apps/eww/bar/scripts/read-mode index 85a0c7e..e30c521 100644 --- a/modules/home/wayland/apps/eww/bar/scripts/read-mode +++ b/modules/home/wayland/apps/eww/bar/scripts/read-mode @@ -1,23 +1,23 @@ #!/usr/bin/env bash -SHADER="$HOME/.config/eww/shaders/read-mode.glsl" +# Toggle the warm/low-contrast screen shader. fp16 rendering is switched off +# with it: the shader is written for 8-bit output. +shader="$HOME/.config/eww/shaders/read-mode.glsl" -is_active() { - hyprctl getoption decoration:screen_shader | grep -qF "$SHADER" -} +active() { hyprctl getoption decoration:screen_shader 2>/dev/null | grep -qF "$shader"; } -case "$1" in - status) - is_active && echo true || echo false - ;; +case ${1:-} in + status) active && echo true || echo false ;; *) - if is_active; then - hyprctl eval 'hl.config({ decoration = { screen_shader = "" } })' - hyprctl eval 'hl.config({ render = { use_fp16 = 2 } })' - echo false + if active; then + hyprctl eval 'hl.config({ decoration = { screen_shader = "" } })' >/dev/null + hyprctl eval 'hl.config({ render = { use_fp16 = 2 } })' >/dev/null + state=false else - hyprctl eval 'hl.config({ render = { use_fp16 = 0 } })' - hyprctl eval "hl.config({ decoration = { screen_shader = \"$SHADER\" } })" - echo true + hyprctl eval 'hl.config({ render = { use_fp16 = 0 } })' >/dev/null + hyprctl eval "hl.config({ decoration = { screen_shader = \"$shader\" } })" >/dev/null + state=true fi + eww update read-mode="$state" 2>/dev/null + echo "$state" ;; esac diff --git a/modules/home/wayland/apps/eww/bar/scripts/screenshot b/modules/home/wayland/apps/eww/bar/scripts/screenshot index dfa1cfa..cffefee 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/screenshot +++ b/modules/home/wayland/apps/eww/bar/scripts/screenshot @@ -1,4 +1,9 @@ #!/usr/bin/env bash +# Region screenshot → satty (annotate, copy to clipboard), detached from eww. eww close popup 2>/dev/null -sleep 0.15 -hyprshot -m region --raw | satty --filename - --early-exit --action-on-enter save-to-clipboard --copy-command wl-copy +eww update active-panel= 2>/dev/null +hyprshot=$(command -v hyprshot) +satty=$(command -v satty) +wl_copy=$(command -v wl-copy) +detach "$BASH" -c 'sleep 0.15; "$1" -m region --raw | "$2" --filename - --early-exit --action-on-enter save-to-clipboard --copy-command "$3"' \ + screenshot "$hyprshot" "$satty" "$wl_copy" diff --git a/modules/home/wayland/apps/eww/bar/scripts/sys/battery b/modules/home/wayland/apps/eww/bar/scripts/sys/battery index 5964975..59cf256 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/sys/battery +++ b/modules/home/wayland/apps/eww/bar/scripts/sys/battery @@ -1,61 +1,67 @@ -#!/usr/bin/env zsh +#!/usr/bin/env bash +# Battery state from sysfs; refreshes on power_supply udev events and every +# 30 s. Emits a `state` (charging / discharging / low / full / idle) that the +# CSS maps to a colour, instead of hard-coding one here. -icons=("󰂎" "󰁺" "󰁻" "󰁼" "󰁽" "󰁾" "󰁿" "󰂀" "󰂁" "󰂂" "󰁹") -num_icons=$(awk -v n="${#icons[@]}" 'BEGIN{print 100 / n}') -BATTERY="/sys/class/power_supply/BAT0" - -geticon() { - level=$(awk -v n="$CAPACITY" -v c="$num_icons" 'BEGIN{print int(n/c-1)}') - echo "${icons[$level]}" -} - -status() { - if [ "$STATE" = "Charging" ]; then - echo -n "Charging" - - if [ "$RATE" -gt 0 ]; then - echo ", $(gettime) left" - else - echo "" - fi - elif [ "$STATE" = "Discharging" ]; then - echo "$(gettime)h left" - else - echo "Fully Charged" - fi -} - -color() { - [ "$CAPACITY" -le 20 ] && echo '#f38ba8' || echo '#a6e3a1' -} - -wattage() { - awk -v rate="$RATE" -v uw="1000000" 'BEGIN{print sprintf("%.1f W", rate/uw)}' -} - -gettime() { - FULL=$(cat $BATTERY/energy_full) - NOW=$(cat $BATTERY/energy_now) - - if [ "$RATE" -gt 0 ]; then - if [ "$STATE" = "Discharging" ]; then - EX=$(( ($NOW*1.0) / $RATE)) - else - EX=$(( (($FULL - $NOW)*1.0) / $RATE)) - fi - date -u -d@"$(awk -v ex="$EX" 'BEGIN{print ex * 3600}')" +%H:%M - fi -} - -if [ -d "$BATTERY" ]; then - while true; do - RATE=$(cat $BATTERY/power_now) - CAPACITY=$(cat $BATTERY/capacity) - STATE=$(cat $BATTERY/status) - - echo '{ "visible": true, "icon": "'$(geticon)'", "percentage": '$CAPACITY', "wattage": "'$(wattage)'", "status": "'$(status)'", "color": "'$(color)'" }' - sleep 15 - done -else - echo '{ "visible": false, "icon": "", "percentage": 0, "wattage": "", "status": "", "color": "#a6e3a1" }' +bat="" +for d in /sys/class/power_supply/*; do + [[ -r $d/type && $(<"$d/type") == Battery ]] && { bat=$d; break; } +done +if [[ -z $bat ]]; then + echo '{"visible":false,"percentage":0,"wattage":"","status":"","state":"none"}' + exit 0 fi + +attr() { # first readable, non-empty attribute of the list, else 0 + local a v + for a in "$@"; do + v=$(cat "$bat/$a" 2>/dev/null) && [[ -n $v ]] && { echo "$v"; return; } + done + echo 0 +} + +hours_to_clock() { awk -v h="$1" 'BEGIN { printf "%d:%02d", int(h), int((h - int(h)) * 60 + 0.5) }'; } + +state() { + local cap status rate now full power time="" wattage state + cap=$(attr capacity) + status=$(attr status) + rate=$(attr power_now current_now) # µW or µA + now=$(attr energy_now charge_now) # µWh or µAh — same unit as rate, so now/rate = hours + full=$(attr energy_full charge_full) + if [[ -r $bat/power_now ]]; then power=$rate; else power=$((rate * $(attr voltage_now) / 1000000)); fi + wattage=$(awk -v p="$power" 'BEGIN { printf "%.1f W", p / 1000000 }') + if ((rate > 0)); then + case $status in + Discharging) time=$(hours_to_clock "$(awk -v n="$now" -v r="$rate" 'BEGIN { print n / r }')") ;; + Charging) time=$(hours_to_clock "$(awk -v n="$now" -v f="$full" -v r="$rate" 'BEGIN { print (f - n) / r }')") ;; + esac + fi + case $status in + Charging) + state=charging + status="Charging${time:+, $time left}" + ;; + Discharging) + state=discharging + ((cap <= 20)) && state=low + status=${time:+$time left} + ;; + Full) + state=full + status="Fully charged" + ;; + *) state=idle ;; + esac + printf '{"visible":true,"percentage":%s,"wattage":"%s","status":"%s","state":"%s"}' \ + "$cap" "$wattage" "$(jstr "$status")" "$state" +} + +refresh() { emit "$(state)"; } +_ps_events() { exec udevadm monitor --udev --subsystem-match=power_supply; } + +refresh +mux_init +mux_add _ps_events +mux_tick 30 +mux_loop refresh diff --git a/modules/home/wayland/apps/eww/bar/scripts/sys/cpugrid b/modules/home/wayland/apps/eww/bar/scripts/sys/cpugrid deleted file mode 100644 index 6b06792..0000000 --- a/modules/home/wayland/apps/eww/bar/scripts/sys/cpugrid +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env bash -COLS=4 -declare -A prev_idle prev_total - -emit_grid() { - local rows=() row_items=() - while IFS= read -r line; do - [[ $line =~ ^cpu([0-9]+) ]] || continue - local core="${BASH_REMATCH[1]}" - read -ra f <<< "$line" - local idle=$(( f[4] + f[5] )) - local total=0 - for x in "${f[@]:1}"; do (( total += x )); done - - local usage="0.0" - if [[ -n "${prev_total[$core]+x}" ]]; then - local dt=$(( total - prev_total[$core] )) - local di=$(( idle - prev_idle[$core] )) - (( dt > 0 )) && usage=$(awk "BEGIN{printf \"%.1f\", 100*(1-$di/$dt)}") - fi - prev_idle[$core]=$idle - prev_total[$core]=$total - - local freq=0 - local fpath="/sys/devices/system/cpu/cpu${core}/cpufreq/scaling_cur_freq" - [[ -r $fpath ]] && freq=$(( $(< "$fpath") / 1000 )) - - row_items+=("{\"core\":$core,\"usage\":$usage,\"freq\":$freq}") - - if (( ${#row_items[@]} == COLS )); then - local row; printf -v row '%s,' "${row_items[@]}"; row="${row%,}" - rows+=("[$row]") - row_items=() - fi - done < /proc/stat - - if (( ${#row_items[@]} > 0 )); then - local row; printf -v row '%s,' "${row_items[@]}"; row="${row%,}" - rows+=("[$row]") - fi - - local out; printf -v out '%s,' "${rows[@]}"; out="${out%,}" - echo "[$out]" -} - -while true; do - emit_grid - sleep 2 -done diff --git a/modules/home/wayland/apps/eww/bar/scripts/sys/cputemp b/modules/home/wayland/apps/eww/bar/scripts/sys/cputemp index 94f9a54..899375c 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/sys/cputemp +++ b/modules/home/wayland/apps/eww/bar/scripts/sys/cputemp @@ -1,3 +1,10 @@ #!/usr/bin/env bash -dir=$(grep -rl k10temp /sys/class/hwmon/*/name 2>/dev/null | head -1 | xargs dirname) -awk '{printf "%.0f\n", $1/1000}' "$dir/temp1_input" +# CPU package temperature in °C from the first known hwmon driver. +for name in k10temp zenpower coretemp cpu_thermal acpitz; do + for d in /sys/class/hwmon/hwmon*; do + [[ -r $d/name && $(<"$d/name") == "$name" && -r $d/temp1_input ]] || continue + awk '{ printf "%d\n", $1 / 1000 }' "$d/temp1_input" + exit 0 + done +done +echo 0 diff --git a/modules/home/wayland/apps/eww/bar/scripts/sys/gpu b/modules/home/wayland/apps/eww/bar/scripts/sys/gpu index ccea39a..1e54cb1 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/sys/gpu +++ b/modules/home/wayland/apps/eww/bar/scripts/sys/gpu @@ -1,5 +1,7 @@ #!/usr/bin/env bash -amdgpu_top -J -s 5000 | jq -c --unbuffered '.devices[0] | { +# AMD GPU activity, clocks, temperature, power and VRAM via amdgpu_top's JSON +# stream, flattened to what the widgets need. +exec amdgpu_top -J -s 5000 | jq -c --unbuffered '.devices[0] | { gfx_pct: (.gpu_activity.GFX.value // 0), mem_pct: (.gpu_activity.Memory.value // 0), media_pct: (.gpu_activity.MediaEngine.value // 0), diff --git a/modules/home/wayland/apps/eww/bar/scripts/sys/memory b/modules/home/wayland/apps/eww/bar/scripts/sys/memory index 512d88a..5827c34 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/sys/memory +++ b/modules/home/wayland/apps/eww/bar/scripts/sys/memory @@ -1,13 +1,18 @@ -#!/usr/bin/env zsh - -total="$(free --si | rg Mem | awk '{print $2}')" - -human() { - awk -v mem="$1" 'BEGIN{print sprintf("%.1f%s", mem/1000/(mem > 1000000 ? 1000 : 1), mem > 1000000 ? "G" : "M")}' -} - -free --si -s 3 | rg --line-buffered Mem | while read -r line; do - used=$(echo "$line" | awk '{print $3}') - cached=$(echo "$line" | awk '{print $6}') - echo '{"human": {"total": "'$(human "$total")'", "used": "'$(human "$used")'", "cached": "'$(human "$cached")'"}, "total": "'$total'", "used": "'$used'", "cached": "'$cached'"}' +#!/usr/bin/env bash +# RAM and swap from /proc/meminfo every 3 s. "used" follows `free` +# (total - available); "cached" is buffers + page cache + reclaimable slab. +# Human values use SI units like the previous `free --si`. +while :; do + awk ' + /^MemTotal:/ { t = $2 } /^MemAvailable:/ { a = $2 } + /^Buffers:/ { b = $2 } /^Cached:/ { c = $2 } + /^SReclaimable:/ { s = $2 } /^SwapTotal:/ { st = $2 } + /^SwapFree:/ { sf = $2 } + function h(kb) { return kb >= 1000000 ? sprintf("%.1fG", kb / 1000000) : sprintf("%.0fM", kb / 1000) } + END { + used = t - a; cached = b + c + s; su = st - sf + printf "{\"total\":%d,\"used\":%d,\"cached\":%d,\"human\":{\"total\":\"%s\",\"used\":\"%s\",\"cached\":\"%s\"},", t, used, cached, h(t), h(used), h(cached) + printf "\"swap\":{\"total\":%d,\"used\":%d,\"human\":{\"total\":\"%s\",\"used\":\"%s\"}}}\n", st, su, h(st), h(su) + }' /proc/meminfo + sleep 3 done diff --git a/modules/home/wayland/apps/eww/bar/scripts/sys/swap b/modules/home/wayland/apps/eww/bar/scripts/sys/swap deleted file mode 100755 index 19301e8..0000000 --- a/modules/home/wayland/apps/eww/bar/scripts/sys/swap +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env bash -free --si | awk '/Swap/ { - used=$3; total=$2 - u = sprintf("%.1fG", used/1000000) - t = sprintf("%.1fG", total/1000000) - printf "{\"used\":%d,\"total\":%d,\"human\":{\"used\":\"%s\",\"total\":\"%s\"}}\n", used, total, u, t -}' diff --git a/modules/home/wayland/apps/eww/bar/scripts/volume b/modules/home/wayland/apps/eww/bar/scripts/volume index ad3f054..2f53c59 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/volume +++ b/modules/home/wayland/apps/eww/bar/scripts/volume @@ -1,45 +1,46 @@ #!/usr/bin/env bash +# Default sink / source volume for the popup. Refreshes on PipeWire events +# (pactl subscribe on the pipewire-pulse socket) and every 30 s. +# +# volume status loop (deflisten) +# volume setvol SINK|SOURCE PERCENT +# volume mute SINK|SOURCE -volicons=("󰕿" "󰖀" "󰕾") +icons=("󰕿" "󰖀" "󰕾") -vol() { wpctl get-volume @DEFAULT_AUDIO_"$1"@ | awk '{print int($2*100)}'; } -ismuted() { wpctl get-volume @DEFAULT_AUDIO_"$1"@ | rg -qi muted; echo -n $?; } -setvol() { wpctl set-volume @DEFAULT_AUDIO_"$1"@ "$(awk -v n="$2" 'BEGIN{print n/100}')"; } -setmute() { wpctl set-mute @DEFAULT_AUDIO_"$1"@ toggle; } - -gen_output() { - percent=$(vol "SINK") - lvl=$(awk -v n="$percent" 'BEGIN{print int(n/34)}') - sink_muted=$(ismuted "SINK") - source_muted=$(ismuted "SOURCE") - sink=$(wpctl inspect @DEFAULT_AUDIO_SINK@ 2>/dev/null | grep -m1 'node\.nick' | sed 's/.*= "\(.*\)"/\1/') - - [ "$sink_muted" = 0 ] && icon="󰝟" || icon="${volicons[$lvl]}" - [ "$source_muted" = 0 ] && mic_icon="󰍭" || mic_icon="󰍬" - - printf '{"icon":"%s","percent":%s,"sink_muted":%s,"mic_icon":"%s","microphone":%s,"source_muted":%s,"sink":"%s"}\n' \ - "$icon" "$percent" "$([ "$sink_muted" = 0 ] && echo true || echo false)" \ - "$mic_icon" "$(vol SOURCE)" "$([ "$source_muted" = 0 ] && echo true || echo false)" "$sink" +level() { # prints " " + wpctl get-volume "@DEFAULT_AUDIO_$1@" 2>/dev/null \ + | awk '{ printf "%d %s\n", $2 * 100 + 0.5, ($0 ~ /MUTED/) ? "true" : "false" }' } -case "$1" in - mute) setmute "$2" ;; - setvol) setvol "$2" "$3" ;; +sink_name() { + wpctl inspect @DEFAULT_AUDIO_SINK@ 2>/dev/null \ + | awk -F'"' '/node\.nick/ { n = $2 } /node\.description/ { d = $2 } END { print (n != "" ? n : d) }' +} + +state() { + local vol muted mic mic_muted icon mic_icon lvl + read -r vol muted < <(level SINK) + read -r mic mic_muted < <(level SOURCE) + vol=${vol:-0} muted=${muted:-false} mic=${mic:-0} mic_muted=${mic_muted:-false} + lvl=$((vol >= 67 ? 2 : vol >= 34 ? 1 : 0)) + if [[ $muted == true ]]; then icon="󰝟"; else icon=${icons[$lvl]}; fi + if [[ $mic_muted == true ]]; then mic_icon="󰍭"; else mic_icon="󰍬"; fi + printf '{"icon":"%s","percent":%d,"sink_muted":%s,"mic_icon":"%s","microphone":%d,"source_muted":%s,"sink":"%s"}' \ + "$icon" "$vol" "$muted" "$mic_icon" "$mic" "$mic_muted" "$(jstr "$(sink_name)")" +} + +refresh() { emit "$(state)"; } +_pw_events() { pactl subscribe 2>/dev/null | grep --line-buffered -E "on (sink|source|server) "; } + +case ${1:-} in + mute) wpctl set-mute "@DEFAULT_AUDIO_$2@" toggle ;; + setvol) wpctl set-volume -l 1.0 "@DEFAULT_AUDIO_$2@" "${3%.*}%" ;; *) - gen_output - - tmp=$(mktemp -d) - pipe="$tmp/vol-events" - mkfifo "$pipe" - trap 'rm -rf "$tmp"; kill 0 2>/dev/null' EXIT INT TERM - - # 2s polling fallback - (while true; do sleep 2; echo poll; done) > "$pipe" & - # PipeWire property-change events (fires on mute/volume change) - (pw-cli -m 2>/dev/null | grep --line-buffered "changed") > "$pipe" & - - while IFS= read -r _ < "$pipe"; do - gen_output - done + refresh + mux_init + mux_add _pw_events + mux_tick 30 + mux_loop refresh ;; esac diff --git a/modules/home/wayland/apps/eww/bar/scripts/wallpaper b/modules/home/wayland/apps/eww/bar/scripts/wallpaper index 219a78d..5b8236b 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/wallpaper +++ b/modules/home/wayland/apps/eww/bar/scripts/wallpaper @@ -1,2 +1,5 @@ #!/usr/bin/env bash -nohup bash "$HOME/.config/script/wallpaper.sh" >/dev/null 2>&1 & +# Wallpaper chooser (wofi + awww), detached from eww. +eww close popup 2>/dev/null +eww update active-panel= 2>/dev/null +detach "$BASH" "$HOME/.config/script/wallpaper.sh" diff --git a/modules/home/wayland/apps/eww/bar/scripts/weather b/modules/home/wayland/apps/eww/bar/scripts/weather index 9139dca..6144339 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/weather +++ b/modules/home/wayland/apps/eww/bar/scripts/weather @@ -1,100 +1,106 @@ #!/usr/bin/env bash +# Weather from met.no for the IP-geolocated position. The last result is +# cached on disk, so re-opening the panel is instant and offline-safe; the +# network is hit at most every 10 minutes. -FALLBACK='{"temp":0,"feelslike":0,"humidity":0,"wind":0,"desc":"Unavailable","icon":"󰖐","city":""}' -CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/eww" -LOC_CACHE="$CACHE_DIR/weather-location" -UA="eww-bar/1.0 cedric.hoelzl@gmail.com" +fallback='{"temp":0,"feelslike":0,"humidity":0,"wind":0,"desc":"Unavailable","icon":"󰖐","city":""}' +cache_dir=${XDG_CACHE_HOME:-$HOME/.cache}/eww +loc_cache=$cache_dir/weather-location.json +wx_cache=$cache_dir/weather.json +interval=600 +ua="eww-bar/1.0 cedric.hoelzl@gmail.com" +mkdir -p "$cache_dir" -mkdir -p "$CACHE_DIR" +fresh() { [[ -s $1 ]] && [[ -n $(find "$1" -mmin "-$2" 2>/dev/null) ]]; } # FILE MINUTES -get_location() { - # Cache location for 1 hour; IP rarely changes - if [ -f "$LOC_CACHE" ] && [ -n "$(find "$LOC_CACHE" -mmin -60 2>/dev/null)" ]; then - cat "$LOC_CACHE" - return 0 +location() { + fresh "$loc_cache" 60 && { cat "$loc_cache"; return; } + local data + if data=$(curl -sf --max-time 5 "http://ip-api.com/json?fields=lat,lon,city"); then + printf '%s' "$data" | tee "$loc_cache" + elif [[ -s $loc_cache ]]; then + cat "$loc_cache" + else + return 1 fi - data=$(curl -sf --max-time 5 "http://ip-api.com/json?fields=lat,lon,city") || return 1 - echo "$data" | tee "$LOC_CACHE" } icon_for() { - case "$1" in - *thunder*) echo "󰖔" ;; - *snow*|*sleet*) echo "󰖘" ;; - heavyrain*|*heavyrainshowers*) echo "󰖖" ;; - *rain*|*shower*) echo "󰖗" ;; - fog*) echo "󰖑" ;; - cloudy*) echo "󰖐" ;; - partlycloudy*) echo "󰖕" ;; - fair*|clearsky*) echo "󰖙" ;; - *) echo "󰖐" ;; + case $1 in + *thunder*) echo "󰖔" ;; + *snow* | *sleet*) echo "󰖘" ;; + heavyrain*) echo "󰖖" ;; + *rain* | *shower*) echo "󰖗" ;; + fog*) echo "󰖑" ;; + cloudy*) echo "󰖐" ;; + partlycloudy*) echo "󰖕" ;; + fair* | clearsky*) echo "󰖙" ;; + *) echo "󰖐" ;; esac } desc_for() { - case "$(echo "$1" | sed 's/_day//;s/_night//;s/_polartwilight//')" in - clearsky) echo "Clear sky" ;; - fair) echo "Fair" ;; - partlycloudy) echo "Partly cloudy" ;; - cloudy) echo "Cloudy" ;; - fog) echo "Foggy" ;; - lightrain) echo "Light rain" ;; - rain) echo "Rain" ;; - heavyrain) echo "Heavy rain" ;; - lightrainshowers) echo "Light showers" ;; - rainshowers) echo "Rain showers" ;; - heavyrainshowers) echo "Heavy showers" ;; - lightrainandthunder) echo "Light rain & thunder" ;; - rainandthunder) echo "Rain & thunder" ;; - heavyrainandthunder) echo "Heavy rain & thunder" ;; - *showersandthunder) echo "Showers & thunder" ;; - lightsleet|lightsleetshowers) echo "Light sleet" ;; - sleet|sleetshowers) echo "Sleet" ;; - heavysleet|heavysleetshowers) echo "Heavy sleet" ;; - *sleetandthunder) echo "Sleet & thunder" ;; - lightsnow|lightsnowshowers) echo "Light snow" ;; - snow|snowshowers) echo "Snow" ;; - heavysnow|heavysnowshowers) echo "Heavy snow" ;; - *snowandthunder) echo "Snow & thunder" ;; - *) echo "$1" ;; + local c=$1 + c=${c%_day}; c=${c%_night}; c=${c%_polartwilight} + case $c in + clearsky) echo "Clear sky" ;; + fair) echo "Fair" ;; + partlycloudy) echo "Partly cloudy" ;; + cloudy) echo "Cloudy" ;; + fog) echo "Foggy" ;; + lightrain) echo "Light rain" ;; + rain) echo "Rain" ;; + heavyrain) echo "Heavy rain" ;; + lightrainshowers) echo "Light showers" ;; + rainshowers) echo "Rain showers" ;; + heavyrainshowers) echo "Heavy showers" ;; + lightrainandthunder) echo "Light rain & thunder" ;; + rainandthunder) echo "Rain & thunder" ;; + heavyrainandthunder) echo "Heavy rain & thunder" ;; + *showersandthunder) echo "Showers & thunder" ;; + lightsleet | lightsleetshowers) echo "Light sleet" ;; + sleet | sleetshowers) echo "Sleet" ;; + heavysleet | heavysleetshowers) echo "Heavy sleet" ;; + *sleetandthunder) echo "Sleet & thunder" ;; + lightsnow | lightsnowshowers) echo "Light snow" ;; + snow | snowshowers) echo "Snow" ;; + heavysnow | heavysnowshowers) echo "Heavy snow" ;; + *snowandthunder) echo "Snow & thunder" ;; + *) echo "$c" ;; esac } fetch() { - loc=$(get_location) || { echo "$FALLBACK"; return; } - lat=$(echo "$loc" | jq -r '.lat') - lon=$(echo "$loc" | jq -r '.lon') - city=$(echo "$loc" | jq -r '.city') - - data=$(curl -sf --max-time 8 \ - -H "User-Agent: $UA" \ - -H "Accept: application/json" \ - "https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=$lat&lon=$lon") \ - || { echo "$FALLBACK"; return; } - - d='.properties.timeseries[0].data' - temp=$( echo "$data" | jq -r "${d}.instant.details.air_temperature | round") - humidity=$(echo "$data" | jq -r "${d}.instant.details.relative_humidity | round") - wind_ms=$( echo "$data" | jq -r "${d}.instant.details.wind_speed") - wind=$( echo "$wind_ms" | awk '{printf "%d", $1 * 3.6}') - code=$( echo "$data" | jq -r \ - "(${d}.next_1_hours.summary.symbol_code) // (${d}.next_6_hours.summary.symbol_code) // \"cloudy\"") - - # Simplified apparent temperature: wind chill below 10°C, else = temp - feelslike=$(echo "$temp $wind" | awk '{ - t=$1; v=$2 - if (v > 4.8 && t < 10) - printf "%d", 13.12 + 0.6215*t - 11.37*(v^0.16) + 0.3965*t*(v^0.16) - else - printf "%d", t - }') - - icon=$(icon_for "$code") - desc=$(desc_for "$code") - - printf '{"temp":%s,"feelslike":%s,"humidity":%s,"wind":%s,"desc":"%s","icon":"%s","city":"%s"}\n' \ - "$temp" "$feelslike" "$humidity" "$wind" "$desc" "$icon" "$city" + local loc lat lon city data temp humidity wind code feelslike + loc=$(location) || return 1 + read -r lat lon city < <(jq -r '"\(.lat) \(.lon) \(.city)"' <<<"$loc") + data=$(curl -sf --max-time 8 -H "User-Agent: $ua" -H "Accept: application/json" \ + "https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=$lat&lon=$lon") || return 1 + read -r temp humidity wind code < <(jq -r ' + .properties.timeseries[0].data + | "\(.instant.details.air_temperature | round) \(.instant.details.relative_humidity | round) \(.instant.details.wind_speed * 3.6 | floor) \(.next_1_hours.summary.symbol_code // .next_6_hours.summary.symbol_code // "cloudy")"' <<<"$data") + [[ -n $temp ]] || return 1 + # Apparent temperature: wind chill below 10 °C, otherwise the air temperature. + feelslike=$(awk -v t="$temp" -v v="$wind" 'BEGIN { + if (v > 4.8 && t < 10) printf "%d", 13.12 + 0.6215 * t - 11.37 * (v ^ 0.16) + 0.3965 * t * (v ^ 0.16) + else printf "%d", t }') + printf '{"temp":%s,"feelslike":%s,"humidity":%s,"wind":%s,"desc":"%s","icon":"%s","city":"%s"}' \ + "$temp" "$feelslike" "$humidity" "$wind" "$(desc_for "$code")" "$(icon_for "$code")" "$(jstr "$city")" } -fetch -while true; do sleep 600; fetch; done +refresh() { + local out + if fresh "$wx_cache" $((interval / 60)); then + emit "$(cat "$wx_cache")" + elif out=$(fetch); then + printf '%s\n' "$out" >"$wx_cache" + emit "$out" + elif [[ -s $wx_cache ]]; then + emit "$(cat "$wx_cache")" + else + emit "$fallback" + fi +} + +refresh +while sleep "$interval"; do refresh; done diff --git a/modules/home/wayland/apps/eww/bar/scripts/workspaces b/modules/home/wayland/apps/eww/bar/scripts/workspaces index c3948d8..7f4f5a4 100755 --- a/modules/home/wayland/apps/eww/bar/scripts/workspaces +++ b/modules/home/wayland/apps/eww/bar/scripts/workspaces @@ -1,120 +1,97 @@ #!/usr/bin/env bash +# Workspace indicator: numbered workspaces 1-9, preceded by named (special) +# workspaces except the scratchpad. Keeps a local model of Hyprland's state +# from socket2 events and only calls hyprctl on structural changes. +# +# Entry: {id, name, target, state: focused|active|running|empty, +# color: blue|red|grey, sep} -declare -A ws_windows=() -declare -A ws_name=() -declare -A ws_urgent=() -declare -A mon_active=() -focused_ws="" -focused_monitor="" -_state="" -_color="" +declare -A ws_windows=() ws_name=() ws_urgent=() mon_active=() +focused_ws="" focused_monitor="" + +hypr_json() { hyprctl -j "$1" 2>/dev/null; } load_workspaces() { - local raw - raw=$(hyprctl -j workspaces 2>/dev/null) || return + local raw id windows name + raw=$(hypr_json workspaces) || return ws_windows=() ws_name=() while read -r id windows name; do ws_windows[$id]=$windows ws_name[$id]=$name - done < <(printf '%s' "$raw" | jaq -jr '.[] | (.id | tostring), " ", (.windows | tostring), " ", .name, "\n"' 2>/dev/null) + done < <(jaq -r '.[] | "\(.id) \(.windows) \(.name)"' <<<"$raw") } load_monitors() { - local raw - raw=$(hyprctl -j monitors 2>/dev/null) || return + local raw name active focused + raw=$(hypr_json monitors) || return mon_active=() - focused_ws="" - focused_monitor="" - while read -r name active_id is_focused; do - mon_active[$name]=$active_id - if [ "$is_focused" = "true" ]; then - focused_ws=$active_id + while read -r name active focused; do + mon_active[$name]=$active + if [[ $focused == true ]]; then + focused_ws=$active focused_monitor=$name fi - done < <(printf '%s' "$raw" | jaq -jr '.[] | .name, " ", (.activeWorkspace.id | tostring), " ", (.focused | tostring), "\n"' 2>/dev/null) + done < <(jaq -r '.[] | "\(.name) \(.activeWorkspace.id) \(.focused)"' <<<"$raw") } load_urgent() { - local raw - raw=$(hyprctl -j clients 2>/dev/null) || return + local raw id + raw=$(hypr_json clients) || return ws_urgent=() - while read -r wsid; do - ws_urgent[$wsid]=1 - done < <(printf '%s' "$raw" | jaq -r '.[] | select(.urgent == true) | (.workspace.id | tostring)' 2>/dev/null) + while read -r id; do ws_urgent[$id]=1; done \ + < <(jaq -r '.[] | select(.urgent) | .workspace.id' <<<"$raw") } -ws_state_color() { - local id=$1 - _state="empty" - _color="grey" +# Window address → workspace id. Events carry the address without the 0x +# prefix that hyprctl uses, which is why urgency never showed up before. +window_workspace() { + hypr_json clients | jaq -r --arg a "0x$1" 'first(.[] | select(.address == $a) | .workspace.id) // empty' +} - if [ "$id" = "$focused_ws" ]; then - _state="focused" +ws_state() { # sets _state / _color for workspace $1 + local id=$1 mon + _state=empty + _color=grey + if [[ $id == "$focused_ws" ]]; then + _state=focused else - local mon for mon in "${!mon_active[@]}"; do - if [ "${mon_active[$mon]}" = "$id" ]; then - _state="active" - break - fi + [[ ${mon_active[$mon]} == "$id" ]] && { _state=active; break; } done - if [ "$_state" = "empty" ] && [ "${ws_windows[$id]:-0}" -gt 0 ]; then - _state="running" - fi + [[ $_state == empty && ${ws_windows[$id]:-0} -gt 0 ]] && _state=running fi - - if [ "$_state" != "empty" ]; then - if [ "${ws_urgent[$id]:-0}" -eq 1 ]; then - _color="red" - else - _color="blue" - fi + if [[ $_state != empty ]]; then + if [[ ${ws_urgent[$id]:-0} == 1 ]]; then _color=red; else _color=blue; fi fi } -ws_entry() { - local id=$1 name=$2 target=$3 sep=${4:-false} - ws_state_color "$id" +entry() { # id name target [sep] + ws_state "$1" printf '{"id":%s,"name":"%s","target":"%s","state":"%s","color":"%s","sep":%s}' \ - "$id" "$name" "$target" "$_state" "$_color" "$sep" + "$1" "$(jstr "$2")" "$(jstr "$3")" "$_state" "$_color" "${4:-false}" } generate() { - printf '[' - local first=true - - local neg_ids=() id + local out='[' sep='' id i named=() for id in "${!ws_name[@]}"; do - if [[ "$id" == -* ]] && [ "${ws_name[$id]}" != "special:magic" ]; then - neg_ids+=("$id") - fi + [[ $id == -* && ${ws_name[$id]} != "special:magic" ]] && named+=("$id") done - - local has_neg=false - if [ ${#neg_ids[@]} -gt 0 ]; then - has_neg=true - IFS=$'\n' sorted_neg=($(printf '%s\n' "${neg_ids[@]}" | sort -n)); unset IFS - for id in "${sorted_neg[@]}"; do - $first || printf ',' - first=false - ws_entry "$id" "${ws_name[$id]}" "name:${ws_name[$id]}" - done + if ((${#named[@]})); then + while read -r id; do + out+="$sep$(entry "$id" "${ws_name[$id]}" "name:${ws_name[$id]}")" + sep=, + done < <(printf '%s\n' "${named[@]}" | sort -n) fi - - local first_pos=true for i in {1..9}; do - $first || printf ',' - first=false - if $first_pos && $has_neg; then - ws_entry "$i" "$i" "$i" true + if ((i == 1 && ${#named[@]})); then + out+="$sep$(entry "$i" "$i" "$i" true)" else - ws_entry "$i" "$i" "$i" + out+="$sep$(entry "$i" "$i" "$i")" fi - first_pos=false + sep=, done - - printf ']\n' + emit "$out]" } load_workspaces @@ -122,53 +99,37 @@ load_monitors load_urgent generate -while read -r line; do - event="${line%>>*}" - data="${line#*>>}" - case "$event" in - "workspace") - # data is the workspace name, not id — resolve to id for named workspaces - focused_ws="$data" - for _k in "${!ws_name[@]}"; do - [ "${ws_name[$_k]}" = "$data" ] && { focused_ws="$_k"; break; } - done - unset "ws_urgent[$focused_ws]" - [ -n "$focused_monitor" ] && mon_active[$focused_monitor]="$focused_ws" - ;; - "workspacev2") - focused_ws="${data%%,*}" - unset "ws_urgent[$focused_ws]" - [ -n "$focused_monitor" ] && mon_active[$focused_monitor]="$focused_ws" - ;; - "focusedmon") - focused_monitor="${data%%,*}" - _wsname="${data#*,}" - focused_ws="$_wsname" - for _k in "${!ws_name[@]}"; do - [ "${ws_name[$_k]}" = "$_wsname" ] && { focused_ws="$_k"; break; } - done - unset "ws_urgent[$focused_ws]" - mon_active[$focused_monitor]="$focused_ws" - ;; - "urgent") - wsid=$(hyprctl -j clients 2>/dev/null | jaq -r --arg addr "$data" '.[] | select(.address == $addr) | (.workspace.id | tostring)' 2>/dev/null) - [ -n "$wsid" ] && ws_urgent[$wsid]=1 - ;; - "createworkspace"*|"destroyworkspace"*|"moveworkspace"*) - load_workspaces - load_monitors - ;; - "openwindow"|"movewindow"*) - load_workspaces - ;; - "closewindow") - load_workspaces - load_urgent - ;; - "monitor"*) - load_monitors - ;; +hypr_socket="$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock" +events='^(workspacev2|focusedmonv2|urgent|openwindow|closewindow|movewindowv2|createworkspacev2|destroyworkspacev2|moveworkspacev2|renameworkspace|monitoraddedv2|monitorremovedv2)>>' + +while IFS= read -r line; do + event=${line%%>>*} + data=${line#*>>} + case $event in + workspacev2) # WORKSPACEID,WORKSPACENAME + focused_ws=${data%%,*} + unset "ws_urgent[$focused_ws]" + [[ -n $focused_monitor ]] && mon_active[$focused_monitor]=$focused_ws + ;; + focusedmonv2) # MONNAME,WORKSPACEID + focused_monitor=${data%%,*} + focused_ws=${data#*,} + unset "ws_urgent[$focused_ws]" + mon_active[$focused_monitor]=$focused_ws + ;; + urgent) # WINDOWADDRESS + id=$(window_workspace "$data") + [[ -n $id && $id != "$focused_ws" ]] && ws_urgent[$id]=1 + ;; + openwindow | movewindowv2) load_workspaces ;; + closewindow) + load_workspaces + load_urgent + ;; + *) + load_workspaces + load_monitors + ;; esac generate -done < <(socat -u UNIX-CONNECT:"$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock" - | \ - rg --line-buffered "^(workspace|focusedmon|createworkspace|destroyworkspace|openwindow|closewindow|movewindow|moveworkspace|monitor|urgent)") +done < <(socat -u UNIX-CONNECT:"$hypr_socket" - | rg --line-buffered "$events") diff --git a/modules/home/wayland/apps/eww/bar/windows/net.yuck b/modules/home/wayland/apps/eww/bar/windows/net.yuck index 9ece3a0..e3e81bd 100644 --- a/modules/home/wayland/apps/eww/bar/windows/net.yuck +++ b/modules/home/wayland/apps/eww/bar/windows/net.yuck @@ -1,12 +1,4 @@ -(deflisten netinfo - :initial '{"wifi":{"ssid":"","ip":"","freq":0,"band":"","gen":"","signal":0},"ethernet":{"state":"down","ip":"","speed":"","interface":""},"usb":{"interface":"","ip":""}}' - "scripts/net/netinfo") - -(deflisten bt-devices - :initial "[]" - "scripts/net/bt-devices") - ; --- Shared widgets --- (defwidget netinfo-row [label value] @@ -34,10 +26,10 @@ :icon-on "󰤨" :icon-off "󰖪") (box :orientation "v" :space-evenly false :visible {net.wifi.connected} - (netinfo-row :label "SSID" :value {netinfo.wifi.ssid}) - (netinfo-row :label "IP" :value {netinfo.wifi.ip}) - (netinfo-row :label "Signal" :value "${net.wifi.icon} ${netinfo.wifi.signal} dBm") - (netinfo-row :label "Freq" :value "${netinfo.wifi.freq} MHz · ${netinfo.wifi.band} · ${netinfo.wifi.gen}")) + (netinfo-row :label "SSID" :value {net.wifi.ssid}) + (netinfo-row :label "IP" :value {net.wifi.ip}) + (netinfo-row :label "Signal" :value "${net.wifi.icon} ${net.wifi.signal} dBm") + (netinfo-row :label "Freq" :value "${net.wifi.freq} MHz · ${net.wifi.band} · ${net.wifi.gen}")) (label :class "netinfo-dim" :halign "start" :visible {!net.wifi.connected} :text {net.wifi.enabled ? "Not connected" : "Disabled"}))) @@ -47,8 +39,8 @@ (defwidget usb-net-section [] (box :orientation "v" :space-evenly false :class "sys-section" (section-header :title "USB" :accent "usb-accent") - (netinfo-row :label "Interface" :value {netinfo.usb.interface}) - (netinfo-row :label "IP" :value {netinfo.usb.ip}))) + (netinfo-row :label "Interface" :value {net.usb.interface}) + (netinfo-row :label "IP" :value {net.usb.ip}))) ; --- Ethernet --- @@ -57,9 +49,9 @@ (section-header :title "Ethernet" :accent "eth-accent") (box :orientation "v" :space-evenly false :visible {net.ethernet.connected} - (netinfo-row :label "Interface" :value {netinfo.ethernet.interface}) - (netinfo-row :label "IP" :value {netinfo.ethernet.ip}) - (netinfo-row :label "Speed" :value {netinfo.ethernet.speed})) + (netinfo-row :label "Interface" :value {net.ethernet.interface}) + (netinfo-row :label "IP" :value {net.ethernet.ip}) + (netinfo-row :label "Speed" :value {net.ethernet.speed})) (label :class "netinfo-dim" :halign "start" :visible {!net.ethernet.connected} :text "No carrier"))) @@ -79,16 +71,16 @@ (box :orientation "v" :space-evenly false :class "sys-section" (section-header-toggle :title "Bluetooth" :accent "blt-accent" - :enabled {bluetooth.powered} - :onclick {bluetooth.powered ? "bluetoothctl power off" : "bluetoothctl power on"} + :enabled {bt.powered} + :onclick {bt.powered ? "bluetoothctl power off" : "bluetoothctl power on"} :icon-on "󰂯" :icon-off "󰂲") (scroll :vscroll true :hscroll false :height 90 - :visible {bluetooth.powered} + :visible {bt.powered} (box :orientation "v" :space-evenly false - (for device in {bt-devices} + (for device in {bt.devices} (bt-device-row :device {device})))) (label :class "netinfo-dim" :halign "start" - :visible {!bluetooth.powered} + :visible {!bt.powered} :text "Disabled"))) ; --- Root --- diff --git a/modules/home/wayland/apps/eww/bar/windows/popup.yuck b/modules/home/wayland/apps/eww/bar/windows/popup.yuck index 54e3685..ff3e022 100644 --- a/modules/home/wayland/apps/eww/bar/windows/popup.yuck +++ b/modules/home/wayland/apps/eww/bar/windows/popup.yuck @@ -1,4 +1,8 @@ +; Monitor the popup is currently open on (set by scripts/panel-toggle), so a +; panel switch on the same monitor is an in-place revealer transition. +(defvar popup-screen "") + (defwidget popup-win [] (box :space-evenly false :orientation "v" (revealer :reveal {active-panel == "sys"} :transition "slidedown" :duration 120 diff --git a/modules/home/wayland/apps/eww/bar/windows/powermenu.yuck b/modules/home/wayland/apps/eww/bar/windows/powermenu.yuck index a22706a..5e284a0 100644 --- a/modules/home/wayland/apps/eww/bar/windows/powermenu.yuck +++ b/modules/home/wayland/apps/eww/bar/windows/powermenu.yuck @@ -18,7 +18,7 @@ (pm-btn :icon "󰍁" :label "Lock" :onclick "scripts/lock") (pm-btn :icon "󰤄" :label "Suspend" - :onclick "scripts/lock & systemctl suspend") + :onclick "scripts/lock; systemctl suspend") (pm-btn :icon "󰗼" :label "Sign out" :onclick "hyprctl eval \"hl.dispatch(hl.dsp.exit())\"") (pm-btn :icon "󰅖" :label "Cancel" diff --git a/modules/home/wayland/apps/eww/bar/windows/radio.yuck b/modules/home/wayland/apps/eww/bar/windows/radio.yuck index 8b692d3..78283e5 100644 --- a/modules/home/wayland/apps/eww/bar/windows/radio.yuck +++ b/modules/home/wayland/apps/eww/bar/windows/radio.yuck @@ -77,6 +77,6 @@ (defwidget radio-mod [] (module (eventbox - :onclick "(sleep 0.1 && scripts/panel-toggle radio)" + :onclick "scripts/panel-toggle radio" (box :orientation "v" (label :show-truncated false :class "icon-text" :text "󰝚"))))) diff --git a/modules/home/wayland/apps/eww/bar/windows/sys.yuck b/modules/home/wayland/apps/eww/bar/windows/sys.yuck index 5684c43..67350bd 100644 --- a/modules/home/wayland/apps/eww/bar/windows/sys.yuck +++ b/modules/home/wayland/apps/eww/bar/windows/sys.yuck @@ -1,17 +1,15 @@ -(defpoll swap :interval "30s" "scripts/sys/swap") - -(defpoll cpu-freq-min :interval "60s" +(defpoll cpu-freq-min :interval "60s" :initial "0" "awk '{print $1/1000}' /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq") -(defpoll cpu-freq-max :interval "60s" +(defpoll cpu-freq-max :interval "60s" :initial "1" "awk '{print $1/1000}' /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq") -(defpoll cpu-temp :interval "4s" +(defpoll cpu-temp :interval "4s" :initial "0" "scripts/sys/cputemp") -(defpoll cpu-freq-avg :interval "2s" +(defpoll cpu-freq-avg :interval "2s" :initial "0" "awk '{sum+=$1; count++} END {printf \"%.1f\", sum/count/1000000}' /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq") -(deflisten cpu-grid :initial '[[{"core":0,"usage":0,"freq":0}]]' - "bash scripts/sys/cpugrid") +; The CPU grid is fed by the EWW_CPU magic variable (2 s); jq() reshapes the +; core list into rows of four. ; --- Shared --- @@ -46,7 +44,7 @@ (box :orientation "v" :space-evenly false :class "sys-section" (section-header :title "CPU" :accent "cpu-accent") (box :orientation "v" :space-evenly false :halign "center" - (for row in {cpu-grid} + (for row in {jq(EWW_CPU.cores, '[.[] | .core |= ltrimstr("cpu")] | [range(0; length; 4) as $i | .[$i:$i + 4]]')} (box :orientation "h" :space-evenly false (for core in {row} (cpu-core-cell :core {core}))))) @@ -162,13 +160,13 @@ (overlay (circular-progress :width 72 :height 72 - :value {100*swap.used/swap.total} + :value {memory.swap.total > 0 ? 100 * memory.swap.used / memory.swap.total : 0} :start-at 0 :clockwise true :thickness 7 :class "swap-ring" - :tooltip "Swap\n${swap.human.used} / ${swap.human.total}") + :tooltip "Swap\n${memory.swap.human.used} / ${memory.swap.human.total}") (box :orientation "v" :valign "center" :halign "center" :space-evenly false - (label :class "ram-used-label" :text "${swap.human.used}") - (label :class "ram-total-label" :text "${swap.human.total}")))) + (label :class "ram-used-label" :text "${memory.swap.human.used}") + (label :class "ram-total-label" :text "${memory.swap.human.total}")))) ) ) ) @@ -185,8 +183,7 @@ :start-at 0 :clockwise true :thickness 6 - :class "bat-ring" - :style "color: ${battery.color};" + :class "bat-ring bat-${battery.state}" :tooltip "Battery ${round(battery.percentage, 0)}%\n${battery.status} @ ${battery.wattage}") (label :class "bat-ring-label" :text "${round(battery.percentage, 0)}%")) diff --git a/modules/home/wayland/apps/eww/default.nix b/modules/home/wayland/apps/eww/default.nix index adcebe3..e305859 100755 --- a/modules/home/wayland/apps/eww/default.nix +++ b/modules/home/wayland/apps/eww/default.nix @@ -1,94 +1,104 @@ { lib, config, pkgs, ... }: let - ensureDaemon = pkgs.custom.eww-ensure-daemon; + ewwBar = "${pkgs.custom.eww-bar}/bin/eww-bar"; - ewwCleanStart = pkgs.writeShellScript "eww-clean-start" '' - uid="$(${pkgs.coreutils}/bin/id -u)" - runtime_dir="''${XDG_RUNTIME_DIR:-/run/user/$uid}" - - ${pkgs.procps}/bin/pkill -TERM -x -u "$uid" eww >/dev/null 2>&1 || true - ${pkgs.coreutils}/bin/sleep 0.2 - ${pkgs.procps}/bin/pkill -KILL -x -u "$uid" eww >/dev/null 2>&1 || true - ${pkgs.coreutils}/bin/rm -f "$runtime_dir"/eww-server_* - ''; - - openOnCurrentScreen = pkgs.writeShellScriptBin "eww-open-on-current-screen" '' - window="$1" - shift - - ${ensureDaemon}/bin/eww-ensure-daemon || exit 1 - - screen="$(hyprctl monitors -j | ${lib.getExe pkgs.jq} -r '.[] | select(.focused == true) | .name' | head -n1)" - - if [ -n "$screen" ]; then - exec ${lib.getExe pkgs.eww} open "$window" --screen "$screen" "$@" - fi - - exec ${lib.getExe pkgs.eww} open "$window" "$@" - ''; - - # Escape hatch: tears down every eww process (including orphaned daemons that - # own unreachable surfaces), clears the stale socket, and brings back a single - # daemon with the bar. `pkill -x` matches the process name exactly so it can - # never match a wrapper script or a shell that merely mentions eww. - ewwReset = pkgs.writeShellScriptBin "eww-reset" '' - ${pkgs.systemd}/bin/systemctl --user stop eww.service >/dev/null 2>&1 || true - ${pkgs.procps}/bin/pkill -x -u "$(id -u)" eww >/dev/null 2>&1 || true - sleep 1 - ${pkgs.procps}/bin/pkill -9 -x -u "$(id -u)" eww >/dev/null 2>&1 || true - rm -f "''${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"/eww-server_* - - ${ensureDaemon}/bin/eww-ensure-daemon || exit 1 - exec ${lib.getExe pkgs.eww} open bar --screen 0 - ''; - - # Wraps a static script file with a bash launcher that prepends Nix store - # bin dirs to PATH — keeps the source files unchanged. + # Every script ships as a bash wrapper that pins PATH to its dependencies + # and inlines the shared helpers, so the sources under bar/scripts stay + # plain shell files. + baseInputs = with pkgs; [ coreutils findutils gawk gnugrep gnused systemd util-linux ]; mkScript = name: src: inputs: pkgs.writeShellScriptBin name '' - export PATH="${lib.makeBinPath inputs}:$PATH" + export PATH="${lib.makeBinPath (baseInputs ++ inputs)}:$PATH" + ${builtins.readFile ./bar/scripts/_lib.sh} ${builtins.readFile src} ''; - scripts = { - "scripts/brightness" = mkScript "brightness" ./bar/scripts/brightness [ pkgs.brightnessctl ]; - "scripts/nightlight" = mkScript "nightlight" ./bar/scripts/nightlight [ pkgs.wlsunset ]; - "scripts/read-mode" = mkScript "read-mode" ./bar/scripts/read-mode [ pkgs.hyprland ]; - "scripts/airplane-mode" = mkScript "airplane-mode" ./bar/scripts/airplane-mode [ pkgs.util-linux ]; - "scripts/do-not-disturb" = mkScript "do-not-disturb" ./bar/scripts/do-not-disturb [ pkgs.dunst ]; - "scripts/panel-toggle" = mkScript "panel-toggle" ./bar/scripts/panel-toggle [ pkgs.eww pkgs.util-linux openOnCurrentScreen ]; - "scripts/powermenu-toggle" = mkScript "powermenu-toggle" ./bar/scripts/powermenu-toggle [ pkgs.eww openOnCurrentScreen ]; - "scripts/power-save" = mkScript "power-save" ./bar/scripts/power-save [ pkgs.eww ]; - "scripts/radio" = mkScript "radio" ./bar/scripts/radio [ pkgs.eww pkgs.jq pkgs.curl pkgs.mpv pkgs.playerctl ]; - "scripts/color-pick" = mkScript "color-pick" ./bar/scripts/color-pick [ pkgs.eww pkgs.hyprpicker ]; - "scripts/media" = mkScript "media" ./bar/scripts/media [ pkgs.playerctl ]; - "scripts/lock" = mkScript "lock" ./bar/scripts/lock [ pkgs.eww pkgs.hyprlock ]; - "scripts/screenshot" = mkScript "screenshot" ./bar/scripts/screenshot [ pkgs.eww pkgs.hyprshot pkgs.satty pkgs.wl-clipboard ]; - "scripts/sys/gpu" = mkScript "gpu" ./bar/scripts/sys/gpu [ pkgs.custom.amdgpu_top pkgs.jq ]; - "scripts/sys/memory" = mkScript "memory" ./bar/scripts/sys/memory [ pkgs.ripgrep ]; - "scripts/volume" = mkScript "volume" ./bar/scripts/volume [ pkgs.ripgrep ]; - "scripts/weather" = mkScript "weather" ./bar/scripts/weather [ pkgs.jq pkgs.curl ]; - "scripts/workspaces" = mkScript "workspaces" ./bar/scripts/workspaces [ pkgs.jaq pkgs.socat pkgs.ripgrep ]; + scripts = with pkgs; { + # bar + "scripts/workspaces" = mkScript "workspaces" ./bar/scripts/workspaces [ hyprland jaq socat ripgrep ]; + "scripts/panel-toggle" = mkScript "panel-toggle" ./bar/scripts/panel-toggle [ eww custom.eww-bar ]; + "scripts/powermenu-toggle" = mkScript "powermenu-toggle" ./bar/scripts/powermenu-toggle [ eww custom.eww-bar ]; + "scripts/net/net" = mkScript "net" ./bar/scripts/net/net [ iproute2 wpa_supplicant ]; + "scripts/net/bt" = mkScript "bt" ./bar/scripts/net/bt [ jq glib ]; + "scripts/net/bt-toggle" = mkScript "bt-toggle" ./bar/scripts/net/bt-toggle [ bluez ]; + "scripts/sys/gpu" = mkScript "gpu" ./bar/scripts/sys/gpu [ custom.amdgpu_top jq ]; + "scripts/sys/memory" = mkScript "memory" ./bar/scripts/sys/memory [ ]; + "scripts/sys/battery" = mkScript "battery" ./bar/scripts/sys/battery [ ]; + "scripts/sys/cputemp" = mkScript "cputemp" ./bar/scripts/sys/cputemp [ ]; + # popup panels + "scripts/volume" = mkScript "volume" ./bar/scripts/volume [ wireplumber pulseaudio ]; + "scripts/brightness" = mkScript "brightness" ./bar/scripts/brightness [ brightnessctl ]; + "scripts/weather" = mkScript "weather" ./bar/scripts/weather [ jq curl ]; + "scripts/radio" = mkScript "radio" ./bar/scripts/radio [ eww jq curl mpv playerctl wireplumber ]; + "scripts/media" = mkScript "media" ./bar/scripts/media [ playerctl ]; + # quick actions (long-running ones are detached via systemd-run) + "scripts/nightlight" = mkScript "nightlight" ./bar/scripts/nightlight [ eww wlsunset procps ]; + "scripts/read-mode" = mkScript "read-mode" ./bar/scripts/read-mode [ eww hyprland ]; + "scripts/airplane-mode" = mkScript "airplane-mode" ./bar/scripts/airplane-mode [ eww ]; + "scripts/do-not-disturb" = mkScript "do-not-disturb" ./bar/scripts/do-not-disturb [ eww dunst ]; + "scripts/power-save" = mkScript "power-save" ./bar/scripts/power-save [ eww power-profiles-daemon ]; + "scripts/lock" = mkScript "lock" ./bar/scripts/lock [ eww hyprlock ]; + "scripts/screenshot" = mkScript "screenshot" ./bar/scripts/screenshot [ eww hyprshot satty wl-clipboard ]; + "scripts/color-pick" = mkScript "color-pick" ./bar/scripts/color-pick [ eww hyprpicker ]; + "scripts/wallpaper" = mkScript "wallpaper" ./bar/scripts/wallpaper [ eww ]; }; in { config = lib.mkIf (config.usercfg.wm == "Wayland") { - home.packages = [ pkgs.eww openOnCurrentScreen ensureDaemon ewwReset ]; + home.packages = [ pkgs.eww pkgs.custom.eww-bar ]; - # One explicitly-managed daemon, so no client ever races to spawn a rival. - # ExecStartPre clears a socket left behind by an unclean exit, which would - # otherwise make the fresh daemon look reachable to clients before it binds. + # The daemon and the bar are one unit: it starts and stops with the + # graphical session, opens the bar once the daemon answers, and is + # restarted on crash. `eww-bar` (packages/eww-bar) does the heavy + # lifting; kanshi calls `eww-bar place` to move the bar between outputs. systemd.user.services.eww = { Unit = { - Description = "eww daemon"; + Description = "eww daemon and bar"; + Documentation = "https://elkowar.github.io/eww/"; PartOf = [ "graphical-session.target" ]; After = [ "graphical-session.target" ]; + ConditionEnvironment = "WAYLAND_DISPLAY"; + # Cap crash loops (e.g. a broken config) without giving up for good: + # the watchdog resets the counter and tries again later. + StartLimitIntervalSec = 60; + StartLimitBurst = 5; }; Service = { Type = "simple"; - ExecStartPre = "${ewwCleanStart}"; + ExecStartPre = "${ewwBar} clean"; ExecStart = "${lib.getExe pkgs.eww} daemon --no-daemonize"; + ExecStartPost = "${ewwBar} open"; + ExecReload = "${ewwBar} reload"; Restart = "always"; - RestartSec = 1; + RestartSec = 2; + TimeoutStartSec = 30; + TimeoutStopSec = 5; + }; + Install.WantedBy = [ "graphical-session.target" ]; + }; + + # Liveness check: `eww ping` only proves the socket is up, so the check + # also lists the windows through the GTK main loop. Two consecutive + # failures (≈40 s) restart the daemon; a missing bar is simply reopened. + systemd.user.services.eww-watchdog = { + Unit = { + Description = "eww health check"; + After = [ "eww.service" ]; + }; + Service = { + Type = "oneshot"; + ExecStart = "${ewwBar} check"; + }; + }; + systemd.user.timers.eww-watchdog = { + Unit = { + Description = "Periodic eww health check"; + PartOf = [ "graphical-session.target" ]; + After = [ "graphical-session.target" ]; + }; + Timer = { + OnActiveSec = "30s"; + OnUnitActiveSec = "20s"; + AccuracySec = "5s"; }; Install.WantedBy = [ "graphical-session.target" ]; }; @@ -97,13 +107,14 @@ in { { "eww" = { source = lib.cleanSourceWith { + # scripts/ is shipped through the wrappers below, never verbatim filter = name: _type: let baseName = baseNameOf (toString name); relPath = lib.removePrefix (toString ./bar + "/") (toString name); in !(lib.hasSuffix ".nix" baseName) && (baseName != "_colors.scss") - && !(builtins.elem relPath (builtins.attrNames scripts)); + && !(lib.hasPrefix "scripts/" relPath); src = lib.cleanSource ./bar/.; }; recursive = true; diff --git a/modules/home/wayland/apps/kanshi/default.nix b/modules/home/wayland/apps/kanshi/default.nix index 19a853a..1caa052 100644 --- a/modules/home/wayland/apps/kanshi/default.nix +++ b/modules/home/wayland/apps/kanshi/default.nix @@ -1,17 +1,10 @@ { config, lib, pkgs, ... }: let - # Close the bar if it's already open (wrong screen), then open on the target screen. - # Must go through eww-ensure-daemon: this runs on every monitor hotplug, and a - # bare `eww open` against a busy/dead socket spawns a second daemon, leaving the - # first one's bar and popups on screen with no way to close them. - moveOrOpenBar = screen: "${pkgs.writeShellScript "kanshi-eww-bar-${toString screen}" '' - ${pkgs.custom.eww-ensure-daemon}/bin/eww-ensure-daemon || exit 1 - - if ${pkgs.eww}/bin/eww active-windows 2>/dev/null | grep -qx "bar"; then - ${pkgs.eww}/bin/eww close bar - fi - ${pkgs.eww}/bin/eww open bar --screen ${toString screen} - ''}"; + # Re-place the bar on the profile's main output. eww-bar waits for the + # daemon (kanshi and eww.service start together at login), and resolves the + # monitor by description on every hotplug, so the bar follows the profile + # instead of a GDK monitor index that changes as outputs come and go. + placeBar = screen: "${pkgs.custom.eww-bar}/bin/eww-bar place '${screen}'"; baseOutput = { position = "0,0"; @@ -71,7 +64,7 @@ in { } ]; exec = [ - (moveOrOpenBar 0) + (placeBar "desc:${aocB}") "${pkgs.writeShellScript "kanshi-hyprland-init" '' #!/usr/bin/env bash ${pkgs.hyprland}/bin/hyprctl eval ' @@ -127,8 +120,8 @@ in { ''}" "${pkgs.awww}/bin/awww restore" - (moveOrOpenBar 0) - ]; + (placeBar "desc:${aocB}") + ]; };} {profile = { name = "valinor00"; @@ -156,8 +149,8 @@ in { ''}" "${pkgs.awww}/bin/awww restore" - (moveOrOpenBar 0) - ]; + (placeBar "desc:Lenovo Group Limited") + ]; };} ]; }; diff --git a/modules/home/wayland/hyprland/config.nix b/modules/home/wayland/hyprland/config.nix index e95b395..8b34c0f 100644 --- a/modules/home/wayland/hyprland/config.nix +++ b/modules/home/wayland/hyprland/config.nix @@ -24,11 +24,8 @@ startupScript = pkgs.writeShellScriptBin "hyprland-start" '' - # Wait for the managed daemon rather than letting `eww open` spawn its own: - # at login the socket may not be bound yet, and a self-spawned client daemon - # would orphan the service's one, leaving unclosable windows behind. - (${pkgs.custom.eww-ensure-daemon}/bin/eww-ensure-daemon \ - && ${pkgs.eww}/bin/eww open bar --screen 0) & + # The eww bar is not started here: eww.service opens it with the + # graphical session and kanshi places it per profile (see apps/eww). ${pkgs.awww}/bin/awww-daemon & ${pkgs.awww}/bin/awww restore & diff --git a/packages/default.nix b/packages/default.nix index 2c05fbb..0067a85 100644 --- a/packages/default.nix +++ b/packages/default.nix @@ -6,7 +6,7 @@ vosk = pkgs.callPackage ./vosk { }; - eww-ensure-daemon = pkgs.callPackage ./eww-ensure-daemon { }; + eww-bar = pkgs.callPackage ./eww-bar { }; jellyfin-mpv-shim-watchdog = pkgs.callPackage ./jellyfin-mpv-shim-watchdog { }; } diff --git a/packages/eww-bar/default.nix b/packages/eww-bar/default.nix new file mode 100644 index 0000000..36d0184 --- /dev/null +++ b/packages/eww-bar/default.nix @@ -0,0 +1,20 @@ +{ writeShellApplication +, coreutils +, eww +, gnugrep +, gnused +, hyprland +, jq +, procps +, systemd +, util-linux +}: + +# Lifecycle manager for the eww daemon and the bar window. Used by +# eww.service (ExecStartPre/Post, ExecReload), eww-watchdog.timer, the kanshi +# profiles and the user (`eww-bar status`, `eww-bar reset`). +writeShellApplication { + name = "eww-bar"; + runtimeInputs = [ coreutils eww gnugrep gnused hyprland jq procps systemd util-linux ]; + text = builtins.readFile ./eww-bar.sh; +} diff --git a/packages/eww-bar/eww-bar.sh b/packages/eww-bar/eww-bar.sh new file mode 100644 index 0000000..440878b --- /dev/null +++ b/packages/eww-bar/eww-bar.sh @@ -0,0 +1,278 @@ +# eww-bar — lifecycle manager for the eww daemon and the bar window. +# +# The daemon is owned by the user unit eww.service. Every window open goes +# through `ensure` first: a plain `eww open` against a dead or stale socket +# silently forks a *second* daemon that takes over the socket path and orphans +# the first daemon's surfaces ("a bar/popup I can't close"). +# +# SCREEN is a GDK monitor index (0), a connector name (DP-1) or +# desc:. Descriptions +# survive re-plugging and profile changes; indices do not. + +usage() { + cat <<'USAGE' +usage: eww-bar COMMAND [ARGS] + + ensure make sure a healthy, service-owned daemon is running + open [SCREEN] open the bar (no-op if already open there), remember SCREEN + place [SCREEN] force re-open of the bar on SCREEN (used by kanshi) + close close the bar and the popups + reload reload the eww config and re-place the bar + restart restart eww.service (the bar comes back with it) + reset kill every eww process, wipe the sockets, start fresh + check health check run by eww-watchdog.timer + clean ExecStartPre: kill stray daemons, wipe stale sockets + focused print the name of the focused Hyprland monitor + status show unit state, open windows and the bar's screen +USAGE +} + +uid=$(id -u) +runtime_dir=${XDG_RUNTIME_DIR:-/run/user/$uid} +state_dir=$runtime_dir/eww-bar +lock_file=$state_dir/lock +screen_file=$state_dir/screen # requested screen spec, re-resolved on restart +current_file=$state_dir/current # resolved screen the bar is currently on +fail_file=$state_dir/strikes +unit=eww.service +default_screen=0 +max_strikes=2 + +mkdir -p "$state_dir" + +log() { printf 'eww-bar: %s\n' "$*" >&2; } + +# ---------------------------------------------------------------- daemon --- + +# nixpkgs wraps eww (wrapGAppsHook), so the running process is `.eww-wrapped`; +# `pkill -x eww` never matched it. Exact match, this user only. +kill_stray_daemons() { + pkill -TERM -x -u "$uid" '(\.eww-wrapped|eww)' 2>/dev/null || true + sleep 0.3 + pkill -KILL -x -u "$uid" '(\.eww-wrapped|eww)' 2>/dev/null || true + rm -f "$runtime_dir"/eww-server_* +} + +unit_state() { systemctl --user show -p ActiveState --value "$unit" 2>/dev/null || echo unknown; } +unit_running() { + case $(unit_state) in + active | activating | reloading) return 0 ;; + *) return 1 ;; + esac +} + +# `eww ping` is answered by the IPC thread and only proves the socket is alive. +ping_daemon() { timeout 3 eww ping >/dev/null 2>&1 9>&-; } + +# `active-windows` is answered from the GTK main loop, so it also detects a +# frozen UI: the reply is then empty instead of listing the windows. +# fd 9 is closed for every client call so a daemonizing client (which can +# only happen when the socket is dead) can never inherit our lock. +list_windows() { timeout 5 eww active-windows 2>/dev/null 9>&- || true; } +bar_open() { list_windows | grep -qx 'bar: bar'; } + +healthy() { unit_running && ping_daemon; } + +wait_for_daemon() { + local i + for ((i = 0; i < 100; i++)); do + ping_daemon && return 0 + sleep 0.1 + done + return 1 +} + +start_unit() { + systemctl --user reset-failed "$unit" >/dev/null 2>&1 || true + systemctl --user start "$unit" +} + +restart_unit() { + log "restarting $unit" + systemctl --user reset-failed "$unit" >/dev/null 2>&1 || true + systemctl --user restart "$unit" +} + +ensure() { + healthy && return 0 + ( + flock -x 9 + healthy && exit 0 + # The unit is (re)starting — possibly running us from ExecStartPost — + # so give the daemon time to bind before declaring it dead. + if unit_running && wait_for_daemon; then exit 0; fi + log "daemon unreachable, restarting $unit" + systemctl --user stop "$unit" >/dev/null 2>&1 || true + kill_stray_daemons + start_unit + wait_for_daemon + ) 9>"$lock_file" +} + +# --------------------------------------------------------------- screens --- + +focused_monitor() { + hyprctl -j monitors 2>/dev/null | jq -r 'first(.[] | select(.focused) | .name) // empty' +} + +# desc: → connector name via hyprctl; anything else is passed to eww. +resolve_screen() { + local spec=$1 name + case $spec in + desc:*) + name=$(hyprctl -j monitors 2>/dev/null \ + | jq -r --arg p "${spec#desc:}" '[.[] | select(.description | startswith($p))][0].name // empty') + if [[ -n $name ]]; then + printf '%s\n' "$name" + else + log "no monitor matches '$spec', using screen $default_screen" + printf '%s\n' "$default_screen" + fi + ;; + '') printf '%s\n' "$default_screen" ;; + *) printf '%s\n' "$spec" ;; + esac +} + +saved_screen() { cat "$screen_file" 2>/dev/null || true; } +current_screen() { cat "$current_file" 2>/dev/null || true; } + +# ------------------------------------------------------------------- bar --- + +close_popups() { + local w + for w in popup powermenu; do + timeout 3 eww close "$w" >/dev/null 2>&1 9>&- || true + done + timeout 3 eww update active-panel= >/dev/null 2>&1 9>&- || true +} + +# open_bar [--force] [SPEC] +open_bar() { + local force=0 spec screen + if [[ ${1:-} == --force ]]; then force=1; shift; fi + spec=${1:-$(saved_screen)} + spec=${spec:-$default_screen} + ensure || { log "no daemon, cannot open the bar"; return 1; } + screen=$(resolve_screen "$spec") + ( + flock -x 9 + if ((force == 0)) && [[ $(current_screen) == "$screen" ]] && bar_open; then + exit 0 + fi + # Popups may sit on an output that just vanished; `eww open` itself + # replaces an already-open bar. + close_popups + if ! timeout 10 eww open bar --screen "$screen" >/dev/null 9>&-; then + if [[ $screen == "$default_screen" ]]; then + log "eww open failed, restarting $unit" + restart_unit + exit 1 + fi + log "cannot open the bar on '$screen', using screen $default_screen" + screen=$default_screen + timeout 10 eww open bar --screen "$screen" >/dev/null 9>&- || { restart_unit; exit 1; } + fi + printf '%s\n' "$spec" >"$screen_file" + printf '%s\n' "$screen" >"$current_file" + log "bar opened on screen $screen" + ) 9>"$lock_file" +} + +close_bar() { + close_popups + timeout 3 eww close bar >/dev/null 2>&1 9>&- || true + rm -f "$current_file" +} + +reload() { + ensure || return 1 + if ! timeout 15 eww reload >/dev/null 9>&-; then + log "reload failed, restarting $unit" + restart_unit + return + fi + open_bar --force +} + +reset() { + log "full reset" + systemctl --user stop "$unit" >/dev/null 2>&1 || true + kill_stray_daemons + rm -f "$current_file" "$fail_file" + start_unit # ExecStartPost re-opens the bar +} + +# ExecStartPre +clean() { + kill_stray_daemons + rm -f "$current_file" "$fail_file" +} + +# -------------------------------------------------------------- watchdog --- + +# One bad check is tolerated (a busy daemon can miss eww's 100 ms IPC reply +# deadline); the second consecutive one restarts the unit. +strike() { + local n + n=$(($(cat "$fail_file" 2>/dev/null || echo 0) + 1)) + if ((n >= max_strikes)); then + log "$1 ($n/$max_strikes) — restarting $unit" + rm -f "$fail_file" + restart_unit + else + log "$1 ($n/$max_strikes)" + printf '%s\n' "$n" >"$fail_file" + fi +} + +check() { + systemctl --user is-active --quiet graphical-session.target || return 0 + if ! unit_running; then + log "$unit is not running, starting it" + start_unit || true + return 0 + fi + [[ $(unit_state) == active ]] || return 0 # still starting; ExecStartPost handles it + if ! ping_daemon; then + strike "daemon does not answer" + return 0 + fi + if bar_open; then + rm -f "$fail_file" + return 0 + fi + # Either nothing is open or the main loop is frozen (empty reply). Try to + # open the bar: a frozen daemon still won't list it afterwards. + open_bar || true + if bar_open; then + rm -f "$fail_file" + log "bar was missing, reopened" + else + strike "UI unresponsive" + fi +} + +status() { + systemctl --user --no-pager status "$unit" 2>&1 | head -n 12 || true + printf '\nwindows:\n' + list_windows | sed 's/^/ /' + printf 'screen: %s (requested: %s)\n' "$(current_screen)" "$(saved_screen)" + printf 'strikes: %s\n' "$(cat "$fail_file" 2>/dev/null || echo 0)" +} + +case ${1:-} in + ensure) ensure ;; + open) shift; open_bar "$@" ;; + place) shift; open_bar --force "$@" ;; + close) close_bar ;; + reload) reload ;; + restart) restart_unit ;; + reset) reset ;; + check) check ;; + clean) clean ;; + focused) focused_monitor ;; + status) status ;; + -h | --help | help) usage ;; + *) usage >&2; exit 64 ;; +esac diff --git a/packages/eww-ensure-daemon/default.nix b/packages/eww-ensure-daemon/default.nix deleted file mode 100644 index c4a983c..0000000 --- a/packages/eww-ensure-daemon/default.nix +++ /dev/null @@ -1,58 +0,0 @@ -{ lib -, writeShellScriptBin -, coreutils -, eww -, procps -, systemd -, util-linux -}: - -# `eww open` silently becomes a NEW daemon when it can't reach the socket, -# rebinding the same socket path and orphaning the previous daemon. The old -# daemon keeps rendering its layer-shell surfaces but no longer answers any -# `eww close` — that is the "zombie panel I can't close" / "bar opened twice". -# Every open path must go through here first, so the socket is always live and -# owned by the managed user service before a client touches it. -writeShellScriptBin "eww-ensure-daemon" '' - eww=${lib.getExe eww} - uid="$(${coreutils}/bin/id -u)" - runtime_dir="''${XDG_RUNTIME_DIR:-/run/user/$uid}" - lock_file="$runtime_dir/eww-ensure-daemon.lock" - - service_active() { - ${systemd}/bin/systemctl --user is-active --quiet eww.service - } - - daemon_healthy() { - "$eww" ping >/dev/null 2>&1 && service_active - } - - wait_for_ping() { - i=0 - while [ "$i" -lt 100 ]; do - daemon_healthy && return 0 - ${coreutils}/bin/sleep 0.1 - i=$((i + 1)) - done - return 1 - } - - daemon_healthy && exit 0 - - ${coreutils}/bin/mkdir -p "$runtime_dir" - ( - ${util-linux}/bin/flock -x 9 - - daemon_healthy && exit 0 - - ${systemd}/bin/systemctl --user stop eww.service >/dev/null 2>&1 || true - ${procps}/bin/pkill -TERM -x -u "$uid" eww >/dev/null 2>&1 || true - ${coreutils}/bin/sleep 0.2 - ${procps}/bin/pkill -KILL -x -u "$uid" eww >/dev/null 2>&1 || true - ${coreutils}/bin/rm -f "$runtime_dir"/eww-server_* - - ${systemd}/bin/systemctl --user reset-failed eww.service >/dev/null 2>&1 || true - ${systemd}/bin/systemctl --user start eww.service >/dev/null 2>&1 || true - wait_for_ping - ) 9>"$lock_file" -''