diff --git "a/data/source_usage.json" "b/data/source_usage.json" --- "a/data/source_usage.json" +++ "b/data/source_usage.json" @@ -2553,7 +2553,7 @@ "scripts/keybindings.sh": "#!/usr/bin/env bash\n# Keybinding browser for Better Bar's launcher.\n#\n# `omarchy-menu-keybindings` is the stock entry point and it works right up to\n# the last line: it builds the full binding table (cached under\n# ~/.cache/omarchy/keybindings-.records), then hands the list to\n# `omarchy-menu-select` to pick from. That selector summons `omarchy.menu`,\n# which is in disabledPlugins on this desktop, so the list is built and then\n# thrown away with nothing on screen. `SUPER + K` looks like it does nothing.\n#\n# So this exposes the same table two ways the launcher can use:\n#\n# --print one \"MODIFIERS + KEY \u2192 action\" label per line, for the\n# menu provider to turn into rows\n# --dispatch LABEL re-find that label in the cache and run it\n#\n# The records and their priority ordering are the stock ones, read straight out\n# of the stock cache rather than reimplemented: this only adds the dispatch half\n# that `omarchy-menu-select` used to provide.\n#\n# `omarchy-menu-keybindings` remains installed and unchanged; only the selection\n# step is replaced.\n\nset -uo pipefail\n\nCACHE_DIR=\"${XDG_CACHE_HOME:-$HOME/.cache}/omarchy\"\nSTOCK=/usr/bin/omarchy-menu-keybindings\n\n# Newest cache file, which is the one the stock script last wrote. Falls back to\n# building the table when there is no cache yet.\ncache_file() {\n local newest\n newest=$(ls -t \"$CACHE_DIR\"/keybindings-*.records 2>/dev/null | head -1)\n if [[ -n \"$newest\" && -s \"$newest\" ]]; then\n printf '%s' \"$newest\"\n return 0\n fi\n return 1\n}\n\n# The full records: \"displaydispatcherarg\", tab-separated.\nrecords() {\n local file\n if file=$(cache_file); then\n cat \"$file\"\n else\n # No cache: let the stock script build one. Its stdout here is display-only,\n # which still serves --print; --dispatch then reports that it cannot run a\n # single binding rather than guessing.\n \"$STOCK\" --print\n fi\n}\n\ncase \"${1:---print}\" in\n --print)\n records | cut -f1\n ;;\n\n --dispatch)\n selection=\"${2:-}\"\n if [[ -z \"$selection\" ]]; then\n echo \"keybindings.sh: --dispatch needs a label\" >&2\n exit 1\n fi\n\n file=$(cache_file) || {\n echo \"keybindings.sh: no keybinding cache; run --print first\" >&2\n exit 1\n }\n\n # Exact match on the display text, which is what the row carried. First hit\n # wins, matching the stock script's own selection lookup.\n record=$(awk -F '\\t' -v s=\"$selection\" '$1 == s { print; exit }' \"$file\")\n if [[ -z \"$record\" ]]; then\n echo \"keybindings.sh: no binding named '$selection'\" >&2\n exit 1\n fi\n\n dispatcher=$(cut -f2 <<<\"$record\")\n arg=$(cut -f3- <<<\"$record\")\n\n trim() {\n local value=\"$1\"\n value=\"${value#\"${value%%[![:space:]]*}\"}\"\n value=\"${value%\"${value##*[![:space:]]}\"}\"\n printf '%s' \"$value\"\n }\n\n # Same three cases the stock script dispatches, minus the selector.\n case \"$dispatcher\" in\n exec)\n command=$(trim \"$arg\")\n [[ -z \"$command\" ]] && exit 1\n hyprctl dispatch \"hl.dsp.exec_cmd($(jq -Rn --arg v \"$command\" '$v|@json'))\" >/dev/null 2>&1 \\\n || hyprctl dispatch exec \"$command\"\n ;;\n sendshortcut)\n IFS=',' read -r mods key window _ <<<\"$arg\"\n mods=$(trim \"${mods:-}\")\n key=$(trim \"${key:-}\")\n window=$(trim \"${window:-}\")\n [[ -z \"$window\" ]] && window=\"activewindow\"\n if [[ -n \"$key\" ]]; then\n m=$(jq -Rn --arg v \"$mods\" '$v|@json')\n k=$(jq -Rn --arg v \"$key\" '$v|@json')\n hyprctl dispatch \"hl.dsp.send_key_state({ mods = $m, key = $k, state = \\\"down\\\", window = \\\"$window\\\" })\" >/dev/null 2>&1 && {\n sleep 0.05\n hyprctl dispatch \"hl.dsp.send_key_state({ mods = $m, key = $k, state = \\\"up\\\", window = \\\"$window\\\" })\"\n exit 0\n }\n fi\n hyprctl dispatch sendshortcut \"$arg\"\n ;;\n lua)\n [[ -n \"$arg\" ]] && hyprctl dispatch \"$arg\"\n ;;\n \"\")\n echo \"keybindings.sh: '$selection' has no dispatcher\" >&2\n exit 1\n ;;\n *)\n if [[ -n \"$arg\" ]]; then\n hyprctl dispatch \"$dispatcher\" \"$arg\"\n else\n hyprctl dispatch \"$dispatcher\"\n fi\n ;;\n esac\n ;;\n\n *)\n echo \"usage: keybindings.sh [--print | --dispatch LABEL]\" >&2\n exit 1\n ;;\nesac", "scripts/lock.sh": "#!/bin/sh\n# Better session lock: hand the session to hyprlock.\n#\n# One entry point: the pill's power menu, the SUPER,L keybind and\n# hypridle all call this. The lock's look is entirely hyprlock's \u2014\n# this repo ships no hyprlock.conf and generates none \u2014 so configure\n# it the way you configure hyprlock everywhere else.\n#\n# Only one process can hold the Wayland session lock, so a second\n# hyprlock can never improve on a first: it either fails to take the\n# lock, or stacks an identical surface behind the live one where no\n# dismiss can reach it. Either way it never exits, and each instance\n# parks ~167 MiB of renderer for the rest of the session. The pid\n# guard below makes a repeat request a no-op instead; a missing\n# hyprlock is a hard error, never a silently unlocked session.\nCACHE_DIR=\"${XDG_CACHE_HOME:-$HOME/.cache}/better\"\nLOG=\"$CACHE_DIR/lock.log\"\nPIDFILE=\"$CACHE_DIR/hyprlock.pid\"\n\nmkdir -p \"$CACHE_DIR\" 2>/dev/null\n\nnote() {\n echo \"$(date '+%F %T'): $*\" >>\"$LOG\"\n}\n\nif ! command -v hyprlock >/dev/null 2>&1; then\n note \"ERROR hyprlock is not installed \u2014 nothing to lock with\"\n echo \"lock.sh: hyprlock is not installed \u2014 cannot lock\" >&2\n exit 1\nfi\n\n# A live recorded pid means the session is already locked and the\n# request is a no-op; anything else is stale bookkeeping. The pid is\n# confirmed to really be hyprlock so a recycled pid cannot read as\n# \"locked\".\nif [ -f \"$PIDFILE\" ]; then\n pid=$(cat \"$PIDFILE\" 2>/dev/null)\n case \"$pid\" in\n '' | *[!0-9]*) ;;\n *)\n if kill -0 \"$pid\" 2>/dev/null &&\n [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = \"hyprlock\" ]; then\n note \"hyprlock already running (pid $pid) -> session is already locked, not spawning another\"\n exit 0\n fi\n ;;\n esac\nfi\n\n# Reap instances this script did not start. A stray that happens to\n# hold the lock is replaced within the same request instead of being\n# left to linger.\nif command -v pkill >/dev/null 2>&1; then\n strays=$(pgrep -x hyprlock 2>/dev/null | wc -l)\n if [ \"$strays\" -gt 0 ]; then\n pkill -x hyprlock 2>/dev/null\n sleep 0.3\n note \"reaped $strays stray hyprlock instance(s) from an earlier lock request\"\n fi\nfi\n\nrm -f \"$PIDFILE\"\n# `exec` preserves the pid, so writing $$ first names the exact\n# process this script started.\necho $$ >\"$PIDFILE\"\nexec hyprlock\n", "scripts/wallcolors.py": "#!/usr/bin/env python3\n\"\"\"\nGenerate the rice colour set from a wallpaper and fan it out to the consumers.\nOne histogram pass yields both the area-dominant chromatic hue (binned by hue\nfamily so a small vivid accent never hijacks the theme) and the mean lightness.\nThe mean lightness drives the pill's whole tone: a bright wallpaper makes a light\npill with dark text, a dark or OLED-black one makes a near-black pill with cream\ntext, so the surfaces and the text flip together for contrast across the full\nrange. The dominant hue tints every tier in HSL. An achromatic wallpaper drops to\na neutral grey ramp.\n\nThe terminal gets a normal light scheme no matter the pill's tone: a near-white,\nhue-tinted background with dark text tiers (the classic default look), then the\n16 ANSI slots are shaped by matugen's light variant so the readout stays legible\non the light background. The pill JSON carries surfaces, accent and the\ncontrast-matched text.\n\n--hue is the rice-only mode: it renders fastfetch, Hyprland and the terminal\nfrom the chosen hue but no longer writes the shared colors.json. The pill's\nmanual palette and the dock's manual palette are computed locally from their own\nhue flags (Singletons/PaletteHue.qml) instead, so a manual slider recolours only\nthe side that owns it \u2014 colors.json stays the wallpaper palette that dynamic\nmodes on both sides read.\n\"\"\"\nimport colorsys\nimport json\nimport os\nimport re\nimport subprocess\nimport sys\nfrom pathlib import Path\n\n# All cache lands in the single better folder under the cache dir, resolved the\n# same way the QML side and the thumb scripts do (Dyn reads this file).\nCACHE = Path(os.environ.get(\"XDG_CACHE_HOME\") or (Path.home() / \".cache\")) / \"better\"\n\nSURF_NAMES = [\"surface\", \"surface_container_low\", \"surface_container\",\n \"surface_container_high\", \"surface_container_highest\", \"outline_variant\"]\nDARK_STEPS = [0.0, 0.022, 0.038, 0.065, 0.100, 0.225]\nLIGHT_STEPS = [0.0, -0.045, -0.075, -0.115, -0.160, -0.340]\nTEXT_KEYS = [\"cream\", \"bright\", \"subtle\", \"dim\", \"faint\", \"icon_dim\", \"tick_rest\"]\nDARK_TEXT = [(0.90, 0.05), (0.97, 0.03), (0.73, 0.07), (0.54, 0.06),\n (0.44, 0.05), (0.81, 0.07), (0.75, 0.08)]\nLIGHT_TEXT = [(0.20, 0.18), (0.10, 0.20), (0.36, 0.14), (0.48, 0.10),\n (0.56, 0.08), (0.28, 0.12), (0.34, 0.12)]\n\n\ndef analyze(wallpaper):\n # Bounded: a wedged magick would hang the caller (the QML Process and\n # wallpaper.sh both wait on this), and an unbounded child is exactly what\n # leaves a shell sitting in the process list. Degrades to a neutral palette.\n try:\n out = subprocess.run(\n [\"magick\", wallpaper, \"-alpha\", \"off\", \"-resize\", \"200x200\", \"-colors\", \"48\",\n \"-format\", \"%c\", \"histogram:info:-\"],\n capture_output=True, text=True, timeout=20).stdout\n except (OSError, subprocess.SubprocessError):\n return None, 0.0, 0.5\n buckets, total, lum, chroma = {}, 0, 0.0, 0\n for line in out.splitlines():\n m = re.search(r\"\\s*(\\d+):\\s*\\([^)]*\\)\\s*#([0-9A-Fa-f]{6})\", line)\n if not m:\n continue\n count, hex_str = int(m.group(1)), m.group(2)\n r, g, b = (int(hex_str[i:i + 2], 16) / 255 for i in (0, 2, 4))\n h, l, s = colorsys.rgb_to_hls(r, g, b)\n total += count\n lum += count * l\n if s < 0.15 or l < 0.05 or l > 0.92:\n continue\n chroma += count\n bucket = buckets.setdefault((int(h * 360) // 30) % 12, {\"wsat\": 0.0, \"best\": None})\n bucket[\"wsat\"] += count * s\n score = count * s * (1 if 0.12 < l < 0.55 else 0.4)\n if not bucket[\"best\"] or score > bucket[\"best\"][0]:\n bucket[\"best\"] = (score, h, s)\n mean_l = lum / total if total else 0.0\n if not buckets or chroma < 0.08 * total:\n return None, 0.0, mean_l\n win = max(buckets.values(), key=lambda v: v[\"wsat\"])\n return win[\"best\"][1], win[\"best\"][2], mean_l\n\n\ndef matugen(source_hex):\n # Bounded like magick above; the caller already treats a SubprocessError\n # (TimeoutExpired included) as \"no matugen\" and falls back to its own ramp.\n out = subprocess.run(\n [\"matugen\", \"color\", \"hex\", source_hex, \"-m\", \"dark\", \"-j\", \"hex\"],\n capture_output=True, text=True, check=True, timeout=15,\n )\n return json.loads(out.stdout)\n\n\ndef tint(hue, sat, light):\n r, g, b = colorsys.hls_to_rgb(hue % 1.0, max(0.0, min(1.0, light)), max(0.0, min(1.0, sat)))\n return \"#%02x%02x%02x\" % (round(r * 255), round(g * 255), round(b * 255))\n\n\ndef lerp(x, x0, x1, y0, y1):\n t = max(0.0, min(1.0, (x - x0) / (x1 - x0)))\n return y0 + t * (y1 - y0)\n\n\ndef rgb(h):\n return tuple(int(h[i:i + 2], 16) / 255 for i in (1, 3, 5))\n\n\ndef to_hex(v):\n return \"#%02x%02x%02x\" % tuple(round(c * 255) for c in v)\n\n\ndef lum(h):\n lin = [c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 for c in rgb(h)]\n return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2]\n\n\ndef contrast(a, b):\n l1, l2 = lum(a), lum(b)\n lo, hi = min(l1, l2), max(l1, l2)\n return (hi + 0.05) / (lo + 0.05)\n\n\ndef ensure_contrast(color, bg, ratio):\n \"\"\"Shift a colour until it clears ratio:1 against bg, keeping its hue:\n toward white on a dark background, toward black on a light one.\"\"\"\n if contrast(color, bg) >= ratio:\n return color\n h, l, s = colorsys.rgb_to_hls(*rgb(color))\n dark_bg = lum(bg) < 0.5\n lo, hi = (l, 1.0) if dark_bg else (0.0, l)\n for _ in range(30):\n mid = (lo + hi) / 2\n if contrast(to_hex(colorsys.hls_to_rgb(h, mid, s)), bg) >= ratio:\n if dark_bg:\n hi = mid\n else:\n lo = mid\n else:\n if dark_bg:\n lo = mid\n else:\n hi = mid\n return to_hex(colorsys.hls_to_rgb(h, hi if dark_bg else lo, s))\n\n\ndef render_fastfetch(pill):\n \"\"\"\n Recolour the fastfetch readout from the same pill palette. fastfetch has no\n daemon, so writing the rendered config is enough, the next run picks it up.\n The accent drives the keys and the torii, the surface ramp the lantern body,\n and a dim text tone the section rules, so it tracks the wallpaper like the\n pill and terminal do.\n \"\"\"\n ff = Path.home() / \".config\" / \"fastfetch\"\n tmpl = ff / \"config.jsonc.in\"\n if not tmpl.is_file():\n return\n seq = lambda h: \"%d;%d;%d\" % tuple(int(h[i:i + 2], 16) for i in (1, 3, 5))\n repl = {\n \"__LANTERN__\": str(ff / \"lantern.txt\"),\n \"__KEYS__\": seq(pill[\"primary\"]),\n \"__SEP__\": seq(pill[\"dim\"]),\n \"__LOGO1__\": seq(pill[\"primary\"]),\n \"__LOGO2__\": seq(pill[\"on_primary_container\"]),\n \"__LOGO3__\": seq(pill[\"surface_container\"]),\n \"__LOGO4__\": seq(pill[\"surface_container_high\"]),\n \"__LOGO5__\": seq(pill[\"subtle\"]),\n \"__LOGO6__\": seq(pill[\"outline\"]),\n \"__LOGO7__\": seq(pill[\"bright\"]),\n }\n out = tmpl.read_text()\n for key, val in repl.items():\n out = out.replace(key, val)\n (ff / \"config.jsonc\").write_text(out)\n\n\ndef main():\n if len(sys.argv) < 2:\n return 1\n hue_only = sys.argv[1] == \"--hue\"\n if hue_only:\n hue = (float(sys.argv[2]) % 360) / 360.0\n mode = sys.argv[3] if len(sys.argv) > 3 else \"dark\"\n sat = float(sys.argv[4]) if len(sys.argv) > 4 else 0.5\n sat = max(0.0, min(1.0, sat))\n mean_l = 0.85 if mode == \"light\" else 0.12\n chromatic = sat > 0.02\n else:\n wallpaper = sys.argv[1]\n if not Path(wallpaper).is_file():\n return 0\n hue, sat, mean_l = analyze(wallpaper)\n chromatic = hue is not None\n if not chromatic:\n hue, sat = 0.09, 0.0\n CACHE.mkdir(parents=True, exist_ok=True)\n\n light = mean_l >= 0.40\n surf_sat = min(sat, 0.26) if light else min(max(sat, 0.30 if chromatic else 0.0), 0.45)\n acc_sat = (min(sat + 0.18, 0.85) if light else min(max(sat, 0.30) + 0.12, 0.82)) if chromatic else 0.05\n if light:\n base = lerp(mean_l, 0.40, 0.66, 0.80, 0.93)\n steps, text, acc_l, deep_l, glow_l = LIGHT_STEPS, LIGHT_TEXT, 0.42, 0.30, 0.55\n else:\n base = lerp(mean_l, 0.0, 0.40, 0.045, 0.20)\n steps, text, acc_l, deep_l, glow_l = DARK_STEPS, DARK_TEXT, 0.70, 0.34, 0.86\n\n pill = {name: tint(hue, surf_sat, base + step) for name, step in zip(SURF_NAMES, steps)}\n pill[\"primary\"] = tint(hue, acc_sat, acc_l)\n pill[\"primary_container\"] = tint(hue, min(acc_sat + 0.08, 0.9), deep_l)\n pill[\"on_primary_container\"] = tint(hue, min(acc_sat, 0.45), glow_l)\n pill[\"outline\"] = tint(hue, surf_sat, base + (-0.35 if light else 0.35))\n for key, (lit, st) in zip(TEXT_KEYS, text):\n pill[key] = tint(hue, st, lit)\n if not hue_only:\n # colors.json is the shared WALLPAPER palette (read by Dyn for the pill's\n # and the dock's dynamic modes). --hue keeps it untouched so a manual\n # slider never restyles the other side's dynamic palette.\n (CACHE / \"colors.json\").write_text(json.dumps(pill, indent=2) + \"\\n\")\n render_fastfetch(pill)\n\n try:\n # Terminal ramp: a normal light scheme (dark text tiers on the\n # terminal's OWN background \u2014 the background is never overridden, so a\n # transparent/blurred terminal keeps its configured look). base07\n # clears ~7:1 and base04 ~4.5:1 against a light background.\n ramp = [(0.93, 0.03), (0.88, 0.03), (0.80, 0.03), (0.70, 0.04),\n (0.55, 0.05), (0.40, 0.05), (0.25, 0.04), (0.13, 0.03)]\n b = {\"base%02x\" % i: tint(hue, s, l) for i, (l, s) in enumerate(ramp)}\n b00 = b[\"base00\"]\n # matugen shapes the 16 ANSI slots from its light variant; a hue-anchored\n # ramp covers its absence.\n try:\n theme = matugen(tint(hue, sat, 0.45) if chromatic else \"#787878\")\n ansi = [theme[\"base16\"][\"base%02x\" % i][\"light\"][\"color\"]\n for i in range(8, 16)]\n except (OSError, ValueError, KeyError, subprocess.SubprocessError):\n ansi = [tint(h, s, l) for (h, s, l) in (\n (0.00, 0.55, 0.45), (0.062, 0.55, 0.40), (0.14, 0.50, 0.42),\n (0.33, 0.47, 0.40), (0.50, 0.45, 0.40), (0.60, 0.50, 0.42),\n (0.76, 0.50, 0.42), (0.083, 0.60, 0.38))]\n for i, c in enumerate(ansi):\n b[\"base%02x\" % (8 + i)] = ensure_contrast(c, b00, 3.0)\n\n (CACHE / \"hypr-colors.lua\").write_text(\n 'return {\\n active = \"%s\",\\n inactive = \"%s\",\\n}\\n'\n % (pill[\"primary\"], b[\"base01\"]))\n\n lines = [\n f'foreground = {b[\"base07\"]}',\n f'cursor-color = {pill[\"primary\"]}',\n f'selection-background = {b[\"base02\"]}',\n f'selection-foreground = {b[\"base07\"]}',\n ]\n for i in range(16):\n lines.append(f'palette = {i}={b[\"base%02x\" % i]}')\n (CACHE / \"ghostty-colors\").write_text(\"\\n\".join(lines) + \"\\n\")\n\n kitty_lines = [\n f'foreground {b[\"base07\"]}',\n f'cursor {pill[\"primary\"]}',\n f'selection_background {b[\"base02\"]}',\n f'selection_foreground {b[\"base07\"]}',\n ]\n for i in range(16):\n kitty_lines.append(f'color{i} {b[\"base%02x\" % i]}')\n (CACHE / \"kitty-colors\").write_text(\"\\n\".join(kitty_lines) + \"\\n\")\n except (OSError, subprocess.SubprocessError):\n pass\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n", - "scripts/wallpaper-search.sh": "#!/usr/bin/env bash\n\nUA=\"Mozilla/5.0 (X11; Linux x86_64) Gecko/20100101 Firefox/126.0\"\n\nsearch_moewalls() {\n local query=\"${1:-}\"\n UA=\"$UA\" python3 - \"$query\" <<'PYEOF'\nimport concurrent.futures\nimport json\nimport os\nimport re\nimport sys\nimport urllib.parse\nimport urllib.request\n\nua = os.environ.get(\"UA\", \"Mozilla/5.0\")\n\ndef fetch(url, timeout=10):\n req = urllib.request.Request(url, headers={\"User-Agent\": ua, \"Referer\": \"https://moewalls.com/\"})\n with urllib.request.urlopen(req, timeout=timeout) as r:\n return r.read().decode(\"utf-8\", \"ignore\")\n\ndef post_entry(url):\n html = fetch(url)\n prev = re.search(r']*data-url=\"([^\"]+)\"', html)\n thumb = re.search(r'poster=\"([^\"]+)\"', html)\n if not prev or not token:\n return None\n res = re.search(r'resolutions-(\\d+)x(\\d+)', html)\n return {\n \"image\": \"https://go.moewalls.com/download.php?video=\" + token.group(1),\n \"thumb\": urllib.parse.urljoin(\"https://moewalls.com/\", thumb.group(1)) if thumb else \"\",\n \"preview\": urllib.parse.urljoin(\"https://moewalls.com/\", prev.group(1)),\n \"w\": int(res.group(1)) if res else 0,\n \"h\": int(res.group(2)) if res else 0,\n }\n\ntry:\n q = urllib.parse.quote(sys.argv[1])\n page = fetch(\"https://moewalls.com/?s=\" + q, timeout=12)\n posts = []\n for m in re.finditer(r'href=\"(https://moewalls\\.com/[a-z0-9-]+/[a-z0-9-]+-live-wallpaper/)\"', page):\n if m.group(1) not in posts:\n posts.append(m.group(1))\n out = []\n with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:\n for entry in ex.map(post_entry, posts[:24]):\n if entry:\n out.append(entry)\n print(json.dumps(out))\nexcept Exception:\n print(\"[]\")\nPYEOF\n}\n\nwh_state() {\n local base=\"${XDG_STATE_HOME:-$HOME/.local/state}/better\"\n mkdir -p \"$base\"\n printf '%s\\n' \"$base\"\n}\n\n# Shared rate gate for every wallhaven-bound request (API searches, thumbnail\n# fetches, picks), so the strip can never trip wallhaven's limits again: the\n# documented API cap is 45 calls/min (429 past it), and a Cloudflare WAF has\n# also banned whole IPs on request bursts \u2014 one such burst here took even a\n# cookie'd browser down with a 403. The gate is a rolling-window budget: it\n# lets a burst through (so a fresh page of thumbs loads in seconds instead of\n# trickling), but caps everything wallhaven-bound at WH_BUDGET (default 30)\n# requests per 60s, shared across all processes via a timestamp journal, and\n# latches a hard cooling-off period on any throttle/block signal.\nwh_state() {\n local base=\"${XDG_STATE_HOME:-$HOME/.local/state}/better\"\n mkdir -p \"$base\"\n printf '%s\\n' \"$base\"\n}\n\n# Suspend all wallhaven traffic for `secs` (default 60). Seeded by any 429/403\n# the fetchers see, so a throttle resets the whole pipeline's clock instead of\n# letting parts of the UI keep slipping requests through.\nwh_backoff() {\n local secs=\"${1:-60}\" base\n base=$(wh_state)\n printf '%s\\n' \"$(( $(date +%s) + secs ))\" > \"$base/wh-cooldown.until\"\n}\n\nwh_gate() {\n local base budget now oldest need_ms count\n base=$(wh_state)\n budget=\"${WH_BUDGET:-30}\"\n { [ \"$budget\" -gt 0 ] 2>/dev/null; } || budget=30\n exec 9>\"$base/wh-window.lock\"\n flock 9\n\n # Cooling-off latch: a recent 429/403 parks every wallhaven request until\n # the timestamp passes. The lock is held throughout so the whole pipeline\n # wakes together instead of trickling back in.\n local cooldown until now_s\n cooldown=\"$base/wh-cooldown.until\"\n if [ -f \"$cooldown\" ]; then\n until=$(cat \"$cooldown\" 2>/dev/null || echo 0)\n now_s=$(date +%s)\n if [ \"$now_s\" -lt \"$until\" ]; then\n sleep \"$(( until - now_s ))\"\n fi\n rm -f \"$cooldown\"\n fi\n\n window=\"$base/wh-window.ts\"\n while :; do\n now=$(date +%s%N)\n if [ -f \"$window\" ]; then\n awk -v now=\"$now\" ' $0 + 60000000000 > now ' \"$window\" > \"$window.tmp\" \\\n && mv \"$window.tmp\" \"$window\"\n count=$(wc -l < \"$window\")\n else\n count=0\n fi\n if [ \"$count\" -lt \"$budget\" ]; then\n printf '%s\\n' \"$now\" >> \"$window\"\n break\n fi\n # Budget exhausted: wait until the oldest in-window request ages out.\n oldest=$(head -1 \"$window\")\n need_ms=$(( 60000 - (now - oldest) / 1000000 ))\n if [ \"$need_ms\" -le 250 ]; then\n # Nearly expired anyway \u2014 nudge past without a clever sleep.\n sleep 0.3\n else\n sleep \"$(awk -v w=\"$need_ms\" 'BEGIN { printf \"%.3f\", w/1000 }')\"\n fi\n done\n flock -u 9\n}\n\n# Wallhaven browse/search. An empty query returns the default hot feed \u2014\n# clicking the strip's wallhaven chip lands there; a query tags it. The third\n# arg picks the sort bucket (hot, latest, top, random, favorites). Each maps to\n# the API's own sort, so the UI labels mean exactly what the site's tabs show:\n# hot -> the Hot feed (rolls over constantly), latest -> date_added, top ->\n# toplist over the last month (its topRange window rolls, so it is not frozen),\n# random -> random, favorites -> all-time Top Liked (kept for API parity, not\n# exposed in the UI because it never changes). A typed query keeps the chosen\n# sort \u2014 there is no silent favorites fallback, which used to make tag searches\n# show the same static most-favorited wallpapers forever. The API serves\n# ready-made thumbs, so results are URLs handed over to `thumbget` for a paced\n# local copy: nothing is downloaded until the strip actually shows it.\nwhsearch() {\n local query=\"${1:-}\" page=\"${2:-1}\" want=\"${3:-}\"\n case \"$page\" in\n ''|*[!0-9]*) page=1 ;;\n esac\n\n local enc sort extra raw code base key mapped\n enc=$(jq -rn --arg q \"$query\" '$q|@uri') || { printf '[]\\n'; return 0; }\n sort=\"hot\"\n extra=\"\"\n case \"$want\" in\n latest) sort=\"date_added\" ;;\n top) sort=\"toplist\"; extra=\"topRange=1M&\" ;;\n random) sort=\"random\" ;;\n favorites) sort=\"favorites\" ;;\n hot) sort=\"hot\" ;;\n esac\n # Hot is the default browse bucket and the API's real Hot sort: it rolls\n # over constantly, unlike toplist/views/favorites which sit on the same\n # mega-popular page one for weeks. Top maps to toplist (with a rolling 1M\n # window) so it changes over time instead of freezing on all-time views.\n # A typed query keeps the picked sort; there is no implied favorites.\n\n base=$(wh_state)\n key=$(printf '%s' \"$query|$page|$sort\" | sha1sum | cut -c1-24)\n cache=\"$base/wh-cache/$key.json\"\n # Dedupe: a repeat of the same query+page+sort within the window replays the\n # stored chunk without any network. The UI re-fires the current page on\n # picks, sort changes and surface re-entry, which used to be a fresh request\n # every time; now those are free.\n if [ -f \"$cache\" ] && [ $(( $(date +%s) - $(stat -c %Y \"$cache\") )) -lt 20 ]; then\n cat \"$cache\"\n return 0\n fi\n\n wh_gate\n raw=$(curl -s --max-time 15 -w $'\\n%{http_code}' -A \"$UA\" \\\n \"https://wallhaven.cc/api/v1/search?${query:+q=${enc}&}sorting=${sort}&${extra}order=desc&page=${page}\")\n code=\"${raw##*$'\\n'}\"\n raw=\"${raw%$'\\n'*}\"\n [ -n \"$code\" ] || code=000\n if [ \"$code\" = \"000\" ]; then\n # No HTTP response at all \u2014 offline, DNS failure, or a time-out. That\n # is a network hiccup, not wallhaven blocking us: don't latch a phantom\n # cooldown or a blocked chip, just hand back an empty page and let the\n # UI sit idle until connectivity returns.\n printf '[]\\n'\n return 0\n fi\n if [ \"$code\" != \"200\" ]; then\n # 429 = the documented rate cap (45/min); 403/5xx = WAF block or edge\n # hiccup. Either way latch a hard cooldown so no part of the UI can\n # keep requesting, and hand the UI a pause marker \u2014 its slow retry\n # timer owns the re-checks, and this is never cached.\n case \"$code\" in\n 429) wh_backoff 120 ;;\n *) wh_backoff 60 ;;\n esac\n printf '%s\\n' '{\"wallhaven\":\"blocked\"}'\n return 0\n fi\n [ -n \"$raw\" ] || { printf '%s\\n' '{\"wallhaven\":\"blocked\"}'; return 0; }\n\n # Map the wallhaven JSON to the strip's entry shape and keep the mapped\n # chunk as the dedupe cache line.\n mapped=$(printf '%s' \"$raw\" | jq -c '\n .data // []\n | map({\n image: .path,\n thumb: (.thumbs.large // .thumbs.original // \"\"),\n w: (.dimension_x // 0),\n h: (.dimension_y // 0)\n })\n | map(select(.image != null and .image != \"\"))\n ' 2>/dev/null || true)\n if [ -n \"$mapped\" ]; then\n mkdir -p \"$base/wh-cache\"\n printf '%s\\n' \"$mapped\" > \"$cache\"\n printf '%s\\n' \"$mapped\"\n else\n printf '%s\\n' '{\"wallhaven\":\"blocked\"}'\n fi\n}\n\n# ---------------------------------------------------------------------------\n# Alpha Coders\n# ---------------------------------------------------------------------------\n#\n# A third source, and the only one with no API at all: api.alphacoders.com is\n# gone (404), so a category page is scraped HTML. The site splits phone\n# wallpapers into separate `-phone-wallpapers` sections, so the\n# desktop sections are already free of them and no orientation filter is\n# needed here.\n#\n# Both pieces of a wallpaper live in different attributes of the same tile --\n# the id in the link to wall.alphacoders.com/big.php?i=, the thumbnail in\n# the picture's source -- so both are pulled per tile rather than one being\n# matched up to the other afterwards. Each id appears three times in the markup\n# (a source per breakpoint plus the img), so tiles are emitted once per unique\n# id; a naive extract returns the same wallpaper two or three times and the\n# strip fills with duplicates.\n#\n# The full-size file cannot be derived from the thumbnail URL. Alpha Coders\n# serves .jpg and .png from the same shape of path and nothing in the listing\n# says which, so a pick goes back to the wallpaper's own page for it. That\n# costs one request per pick, which is the right trade: picks are deliberate\n# and rare, and a strip full of tiles that cannot be downloaded is worthless.\n\n# One wallpaper's entry: the thumbnail the tile renders, and the page the pick\n# resolves through.\nAC_PAGE_URL='https://alphacoders.com'\nAC_VIEW_URL='https://wall.alphacoders.com/big.php?i='\n\n# True when $1 is one of the categories this source is browsed by. The site\n# has far more sections than the strip offers; these are the ones that line up\n# with what the other two sources already expose, so switching sources keeps\n# the meaning of the category row.\nac_category_ok() {\n case \"${1:-}\" in\n abstract|anime|amoled|architecture|art|cars|minimal|nature|tech) ;;\n *) return 1 ;;\n esac\n}\n\n# Parse a category page into the strip's entry shape. Reads the page on stdin.\n#\n# awk rather than grep -o here because the two fields are ordered differently\n# per tile -- the link precedes the picture in every tile seen so far, but a\n# regex that assumed it would silently drop the tail of a page the moment the\n# markup shifted. Matching the id anywhere in the tile and the thumb anywhere\n# in the same tile does not care about their order.\nac_parse_page() {\n awk '\n # New tile: a link to the wallpaper page carries its id.\n /big\\.php\\?i=[0-9]+/ {\n # The digits are matched directly rather than sliced out of a\n # wider match, so no offset arithmetic can drift and leave the\n # \"=\" or a stray character glued to the id.\n if (match($0, /big\\.php\\?i=[0-9]+/)) {\n line = $0\n sub(/.*big\\.php\\?i=/, \"\", line)\n sub(/[^0-9].*$/, \"\", line)\n id = line\n thumb = \"\"\n have = 1\n }\n }\n # The thumbnail for the tile being read. Kept as the last one seen so a\n # page that repeats the image per breakpoint still yields one thumb.\n have && /thumbbig-[0-9]+\\.webp/ {\n if (match($0, /https:\\/\\/images[0-9]*\\.alphacoders\\.com\\/[0-9]+\\/thumbbig-[0-9]+\\.webp/))\n thumb = substr($0, RSTART, RLENGTH)\n }\n # End of tile: the closes the link the id came from, which is the\n # only reliable boundary between one wallpaper and the next.\n have && /<\\/a>/ {\n if (thumb != \"\" && !(id in seen)) {\n seen[id] = 1\n printf \"{\\\"thumb\\\":\\\"%s\\\",\\\"image\\\":\\\"%s%s\\\"}\\n\", thumb, \"'\"$AC_VIEW_URL\"'\", id\n }\n id = \"\"\n thumb = \"\"\n have = 0\n }\n '\n}\n\n# Browse one category page. Output is JSON lines, which the caller turns into\n# an array; a page that cannot be fetched answers an empty array so the strip\n# shows its empty state rather than spinning.\nacsearch() {\n local cat=\"${1:-}\" page=\"${2:-1}\" base cache raw code mapped\n ac_category_ok \"$cat\" || cat=\"minimal\"\n case \"$page\" in\n ''|*[!0-9]*) page=1 ;;\n esac\n [ \"$page\" -lt 1 ] && page=1\n\n base=$(wh_state)\n cache=\"$base/ac-cache/$(printf '%s' \"$cat-$page\" | sha1sum | cut -c1-24).json\"\n\n # Cached for the same window as the wallhaven chunks: the strip re-fires a\n # page on every entry and category change, and the collection moves slowly\n # enough that a fresh fetch is almost never what is wanted.\n if [ -f \"$cache\" ] && [ $(( $(date +%s) - $(stat -c %Y \"$cache\") )) -lt 1200 ]; then\n cat \"$cache\"\n return 0\n fi\n\n # -L because four of the category names the strip uses are not the site's own:\n # it redirects art -> artistic, cars -> cars-(pixar), minimal ->\n # minimalist and tech -> technology. Without following, those four answer\n # 301 with an empty body, which parsed as \"this category has no\n # wallpapers\" and left four of the nine chips permanently blank.\n raw=$(curl -sL --max-time 20 -w $'\\n%{http_code}' -A \"$UA\" \\\n \"$AC_PAGE_URL/$cat-wallpapers?page=$page\")\n # The site serves an empty 200 for an out-of-range page rather than a 404,\n # so a page number past the end is a legitimate empty answer and not a\n # failure to report.\n code=\"${raw##*$'\\n'}\"\n raw=\"${raw%$'\\n'*}\"\n [ -n \"$code\" ] || code=000\n # 000 is offline or a timeout rather than the site refusing: no cooldown\n # latch here, because there is no rate budget to protect. An empty answer\n # lets the strip sit idle until connectivity returns.\n [ \"$code\" = \"200\" ] || { printf '[]\\n'; return 0; }\n\n # fromjson on each line: -R reads the awk output as raw strings, so without it\n# the array would hold the JSON as text and every consumer would get a string\n# where it expects an entry.\n mapped=$(printf '%s\\n' \"$raw\" | ac_parse_page \\\n | jq -R -s -c 'split(\"\\n\") | map(select(length > 0)) | map(fromjson)')\n\n if [ -z \"$mapped\" ] || [ \"$mapped\" = \"[]\" ]; then\n printf '[]\\n'\n return 0\n fi\n\n mkdir -p \"$(dirname \"$cache\")\"\n printf '%s\\n' \"$mapped\" > \"$cache\"\n printf '%s\\n' \"$mapped\"\n}\n\n# Recover the full-size image URL for a picked wallpaper.\n#\n# The detail page's og:image is the original file, named thumb-1920-.\n# because it is also what the page shows inline. The name is rewritten to\n# ., keeping the extension the site chose -- which is the whole point,\n# since guessing it wrong 404s on the png wallpapers.\nacresolve() {\n local url=\"${1:-}\" id raw full\n id=\"${url##*=}\"\n case \"$id\" in\n ''|*[!0-9]*) printf '\\n'; return 0 ;;\n esac\n\n raw=$(curl -s --max-time 20 -A \"$UA\" \"$url\")\n [ -n \"$raw\" ] || { printf '\\n'; return 0; }\n\n full=$(printf '%s\\n' \"$raw\" | grep -oE \\\n 'https://images[0-9]*\\.alphacoders\\.com/[0-9]+/thumb-1920-[0-9]+\\.(jpg|png)' \\\n | head -1 | sed -E 's#/thumb-1920-([0-9]+)\\.(jpg|png)$#/\\1.\\2#')\n\n printf '%s\\n' \"$full\"\n}\n\n# WallWidgy browse. The API's search endpoint only ever hands back a\n# handful of random picks, but its index endpoint lists the whole\n# collection with metadata (category, orientation, resolution,\n# timestamp). The index is cached for an hour; each call filters it\n# to desktop wallpapers of the chosen collection (or all of them),\n# newest first, and slices out the requested page. Results are JSON\n# in the strip's entry shape, like whsearch, plus the matching total\n# so the UI can page without asking the server.\nwwsearch() {\n local cat=\"${1:-}\" count=\"${2:-17}\" page=\"${3:-0}\"\n case \"$count\" in\n ''|*[!0-9]*) count=17 ;;\n esac\n [ \"$count\" -gt 2000 ] && count=2000\n [ \"$count\" -lt 1 ] && count=1\n case \"$page\" in\n ''|*[!0-9]*) page=0 ;;\n esac\n case \"$cat\" in\n all|\"\") cat=\"all\" ;;\n abstract|anime|amoled|architecture|art|cars|minimal|nature|tech) ;;\n *) cat=\"minimal\" ;;\n esac\n\n local base idx raw code\n base=$(wh_state)\n mkdir -p \"$base/ww-cache\"\n idx=\"$base/ww-index.json\"\n # The collection changes slowly, so the index is kept for an hour.\n # A stale or corrupt cache is re-fetched; with no response at all\n # a stale cache still serves, and only a cold cache yields an\n # empty page until connectivity returns.\n if ! { [ -f \"$idx\" ] && [ $(( $(date +%s) - $(stat -c %Y \"$idx\") )) -lt 3600 ] && jq -e 'type == \"array\"' \"$idx\" >/dev/null 2>&1; }; then\n raw=$(curl -s --max-time 20 -w $'\\n%{http_code}' -A \"$UA\" \\\n \"https://wallwidgy.vercel.app/api/wallpapers/index\")\n code=\"${raw##*$'\\n'}\"\n raw=\"${raw%$'\\n'*}\"\n [ -n \"$code\" ] || code=000\n if [ \"$code\" = \"000\" ]; then\n [ -f \"$idx\" ] || { printf '%s\\n' '{\"wallpapers\":[],\"total\":0}'; return 0; }\n elif [ \"$code\" != \"200\" ] || [ -z \"$raw\" ]; then\n printf '%s\\n' '{\"wallwidgy\":\"blocked\"}'\n return 0\n else\n printf '%s' \"$raw\" > \"$idx\"\n fi\n fi\n\n # Filter to desktop wallpapers of the collection, newest\n # first, then slice the page out. The thumb is the\n # collection's pre-scaled webp cache variant (a few tens\n # of KB) rather than the multi-megabyte master the image\n # field names \u2014 the strip renders tiles, not wallpapers,\n # and the master is fetched only when a pick is applied.\n jq -c --arg cat \"$cat\" --arg u \"https://raw.githubusercontent.com/not-ayan/storage/main/\" \\\n --argjson skip \"$(( page * count ))\" --argjson take \"$count\" '\n ([.[] | select(.orientation == \"Desktop\" and .file_main_name != null and .file_main_name != \"\")]\n | if $cat == \"all\" then .\n else map(select((.category // \"\") | ascii_downcase == (\"#\" + ($cat | ascii_downcase)))) end\n | sort_by(.timestamp) | reverse) as $all\n | {\n wallpapers: ($all[$skip : ($skip + $take)]\n | map({ image: ($u + \"main/\" + .file_main_name),\n thumb: (if (.file_cache_name // \"\") != \"\"\n then ($u + \"cache/\" + .file_cache_name)\n else ($u + \"main/\" + .file_main_name) end),\n w: (.width // 0), h: (.height // 0) })),\n total: ($all | length)\n }\n ' \"$idx\" 2>/dev/null || printf '%s\\n' '{\"wallwidgy\":\"blocked\"}'\n}\n\n# Fetch one wallhaven thumb into a disk cache at the same shared pace.\n# Cached hits are served instantly with no network and no gate (Qt decodes by\n# content, so the extensionless cache name is fine), so scrolling back over a\n# page costs zero wallhaven requests. The cache is kept under\n# WH_THUMB_MAX_MB (default 20): every fresh store prunes the least-recently\n# used thumbs (newest just saved is kept) until the directory fits again.\nthumbget() {\n local url=\"${1:-}\"\n [ -n \"$url\" ] || exit 1\n local base digest cache tmp\n base=\"${XDG_CACHE_HOME:-$HOME/.cache}/better/wh-thumbs\"\n digest=$(printf '%s\\n' \"$url\" | sha1sum | cut -c1-24)\n # The cache holds the resized JPEG, so the suffix is part\n # of the name. Qt decodes by content, and the LRU prune\n # below counts the directory either way.\n cache=\"$base/$digest.jpg\"\n # Cache check before mkdir \u2014 every hit skips the directory\n # creation entirely, which is the point of the disk cache.\n [ -s \"$cache\" ] && { printf '%s\\n' \"$cache\"; exit 0; }\n mkdir -p \"$base\"\n # The rate gate exists for wallhaven's API budget. The\n # WallWidgy thumbnails come from GitHub's raw CDN, which\n # has no such budget, so they fetch without it -- the\n # fetch pool on the QML side already bounds how many run\n # at once.\n case \"$url\" in\n *wallhaven.cc*) wh_gate ;;\n esac\n tmp=\"$base/.$digest.tmp\"\n trap 'rm -f \"$tmp\"' EXIT\n curl -fsSL --max-time 25 -A \"$UA\" -o \"$tmp\" \"$url\" \\\n || exit 1\n [ -s \"$tmp\" ] || exit 1\n # Shrink anything a tile never needs to a 720px JPEG\n # before caching it. Wallhaven serves ready-made thumbs\n # and WallWidgy's cache variant is a pre-scaled webp,\n # so most fetches are already inside the box and are\n # cached untouched -- no decode, no encode, no CPU. The\n # ones that are not go through vips when it is\n # installed: it resizes in a single pass at a fraction\n # of ImageMagick's CPU and memory, and writes JPEG, a\n # tenth the size of the PNG it replaces. ImageMagick\n # stays as the fallback.\n local dim w h\n if command -v vipsheader >/dev/null 2>&1; then\n # [0-9]+ (not *) so a bare \"x\" in the path -- the\n # home directory is /home/pixllbeat -- cannot match\n # ahead of the real dimensions.\n dim=$(vipsheader \"$tmp\" 2>/dev/null | head -1 \\\n | grep -oE '[0-9]+x[0-9]+' | head -1 | tr 'x' ' ')\n fi\n if [ -z \"$dim\" ]; then\n export MAGICK_CONFIGURE_PATH=\"$(dirname \"$0\")/magick-policy\"\n dim=$(magick identify -format '%w %h' \"$tmp\" 2>/dev/null | head -1) || dim=\"\"\n case \"$dim\" in\n *[!0-9\\ ]*) dim=\"\" ;;\n esac\n fi\n w=${dim%% *}\n h=${dim##* }\n if [ -n \"$dim\" ] && { [ \"$w\" -gt 720 ] || [ \"$h\" -gt 720 ]; }; then\n if command -v vipsthumbnail >/dev/null 2>&1; then\n vipsthumbnail \"$tmp\" -s 720x720 -o \"$cache[Q=85]\" \\\n >/dev/null 2>&1 && [ -s \"$cache\" ] || rm -f \"$cache\"\n else\n export MAGICK_CONFIGURE_PATH=\"$(dirname \"$0\")/magick-policy\"\n magick \"$tmp\" -resize '720x720>' -quality 85 \"$cache\" \\\n 2>/dev/null && [ -s \"$cache\" ] || rm -f \"$cache\"\n fi\n # A resize that failed leaves nothing behind: fall\n # back to the fetched file as-is, decoded by content.\n [ -s \"$cache\" ] || mv \"$tmp\" \"$cache\"\n else\n mv \"$tmp\" \"$cache\"\n fi\n local max_mb total old\n max_mb=\"${WH_THUMB_MAX_MB:-20}\"\n { [ \"$max_mb\" -gt 0 ] 2>/dev/null; } || max_mb=20\n total=$(du -sk \"$base\" 2>/dev/null | awk '{print $1}')\n while [ \"${total:-0}\" -gt $(( max_mb * 1024 )) ]; do\n old=$(find \"$base\" -maxdepth 1 -type f ! -name '.*' \\\n -printf '%T@ %p\\n' | sort -n | head -1 | cut -d' ' -f2-)\n [ -n \"$old\" ] || break\n rm -f \"$old\"\n total=$(du -sk \"$base\" 2>/dev/null | awk '{print $1}')\n done\n printf '%s\\n' \"$cache\"\n}\n\nsearch() {\n local query=\"${1:-}\" kind=\"${2:-all}\"\n [ -n \"$query\" ] || { printf '[]\\n'; return 0; }\n\n if [ \"$kind\" = \"motion\" ]; then\n search_moewalls \"$query\"\n return 0\n fi\n\n local q=\"$query\" f=\",,,\"\n case \"$kind\" in\n still) f=\"type:photo\" ;;\n esac\n\n local enc vqd raw\n enc=$(jq -rn --arg q \"$q\" '$q|@uri') || { printf '[]\\n'; return 0; }\n\n vqd=$(curl -s --max-time 10 \"https://duckduckgo.com/?q=${enc}&iax=images&ia=images\" -A \"$UA\" \\\n | grep -oP 'vqd=\\\\?\"?\\K[0-9-]+' | head -1)\n [ -n \"$vqd\" ] || { printf '[]\\n'; return 0; }\n\n raw=$(curl -s --max-time 10 \\\n \"https://duckduckgo.com/i.js?l=us-en&o=json&q=${enc}&vqd=${vqd}&f=${f}&p=-1\" \\\n -A \"$UA\" -H \"Referer: https://duckduckgo.com/\")\n [ -n \"$raw\" ] || { printf '[]\\n'; return 0; }\n\n printf '%s' \"$raw\" | jq -c --arg kind \"$kind\" '\n (.results // [])\n | if $kind == \"still\" then map(select(.image // \"\" | test(\"\\\\.gif(\\\\?|$)\"; \"i\") | not)) else . end\n | map({\n image: .image,\n thumb: (.thumbnail // .image),\n w: (.width // 0 | if . == null then 0 else . end),\n h: (.height // 0 | if . == null then 0 else . end)\n })\n | map(select(.image != null and .image != \"\"))\n | .[0:60]\n ' 2>/dev/null || printf '[]\\n'\n}\n\ndownload() {\n set -euo pipefail\n url=\"${1:-}\"\n [ -n \"$url\" ] || exit 1\n\n # This script copy belongs to the better bar, so the collection a\n # pick lands in is the better bar's own state: the stock shell's\n # better/flags.json carries its own (empty) wallpaper dir, which\n # would drop every pick into the autodetect fallback instead of the\n # folder the bar resolved.\n flags=\"${XDG_STATE_HOME:-$HOME/.local/state}/better/flags.json\"\n wpdir=$(jq -r '.wallpaperDir // \"\"' \"$flags\" 2>/dev/null || echo \"\")\n [ -n \"$wpdir\" ] || wpdir=$(cat \"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper-dir\" 2>/dev/null || true)\n [ -n \"$wpdir\" ] || wpdir=\"$HOME/Pictures/Wallpapers\"\n # Every pick lands directly in the collection root so it joins the shuffle\n # bag; wallhaven keeps its id, moewalls/DDG get stamped names. No subfolder\n # is ever created, so browsing never leaves an empty downloads/ dir behind.\n\n case \"$url\" in\n https://go.moewalls.com/download.php*)\n fn=$(curl -fsI --max-time 20 -A \"$UA\" -e \"https://moewalls.com/\" \"$url\" \\\n | grep -oiP 'filename=\\K[^\"\\r\\n;]+' | head -1 | tr -d '/\\\\')\n [ -n \"$fn\" ] || fn=\"moewalls-$(date +%s).mp4\"\n out=\"$wpdir/$fn\"\n curl -fsL --max-time 600 -A \"$UA\" -e \"https://moewalls.com/\" -o \"$out\" \"$url\" || exit 1\n [ -s \"$out\" ] || exit 1\n printf '%s\\n' \"$out\"\n exit 0\n ;;\n https://wall.alphacoders.com/big.php\\?i=*)\n # The listing cannot say whether a wallpaper is a jpg or a png --\n # both come off the same shape of path -- so the pick resolves the\n # real file from the wallpaper's own page. That is one extra request\n # per pick, which is the right way round: picks are deliberate and\n # rare, whereas guessing wrong 404s every png wallpaper.\n id=\"${url##*=}\"\n case \"$id\" in\n ''|*[!0-9]*) exit 1 ;;\n esac\n full=$(acresolve \"$url\")\n [ -n \"$full\" ] || exit 1\n fn=\"alphacoders-$id.${full##*.}\"\n out=\"$wpdir/$fn\"\n curl -fsL --max-time 600 -A \"$UA\" -e \"https://alphacoders.com/\" -o \"$out\" \"$full\" || exit 1\n [ -s \"$out\" ] || exit 1\n printf '%s\\n' \"$out\"\n exit 0\n ;;\n https://w.wallhaven.cc/*)\n # Picked wallhaven wallpaper lands in the collection root itself so\n # it joins the shuffle bag; the filename keeps the wallhaven id. A\n # pick is a wallhaven-bound request too, so it shares the pace gate\n # that protects the API and thumb CDN.\n wh_gate\n fn=$(basename \"$url\" | tr -d '/\\\\')\n [ -n \"$fn\" ] || exit 1\n out=\"$wpdir/$fn\"\n curl -fsL --max-time 600 -A \"$UA\" -e \"https://wallhaven.cc/\" -o \"$out\" \"$url\" || exit 1\n [ -s \"$out\" ] || exit 1\n printf '%s\\n' \"$out\"\n exit 0\n ;;\n esac\n\n tmp=$(mktemp \"${TMPDIR:-/tmp}/ddg-wp.XXXXXX\")\n trap 'rm -f \"$tmp\" \"$tmp.out\"' EXIT\n\n curl -fsL --max-time 60 -A \"$UA\" -e \"https://duckduckgo.com/\" -o \"$tmp\" \"$url\" || exit 1\n [ -s \"$tmp\" ] || exit 1\n\n export MAGICK_CONFIGURE_PATH=\"$(dirname \"$0\")/magick-policy\"\n\n fmt=$(magick identify -format '%m' \"${tmp}[0]\" 2>/dev/null | head -1) || exit 1\n\n case \"$fmt\" in\n JPEG) ext=jpg ;;\n PNG) ext=png ;;\n GIF) ext=gif ;;\n WEBP) ext=webp ;;\n *) ext=png ;;\n esac\n\n out=\"$wpdir/ddg-$(date +%s)-${RANDOM}.${ext}\"\n\n if [ \"$ext\" = \"png\" ] && [ \"$fmt\" != \"PNG\" ]; then\n magick \"${tmp}[0]\" -strip \"png:$tmp.out\" 2>/dev/null || exit 1\n [ -s \"$tmp.out\" ] || exit 1\n mv \"$tmp.out\" \"$out\"\n else\n cp \"$tmp\" \"$out\"\n fi\n\n [ -s \"$out\" ] || exit 1\n printf '%s\\n' \"$out\"\n}\n\ncase \"${1:-}\" in\n search) search \"${2:-}\" \"${3:-all}\" ;;\n whsearch) whsearch \"${2:-}\" \"${3:-1}\" \"${4:-}\" ;;\n # WallWidgy pages through the index: the bar passes category, page\n # size and the zero-based page. Without forwarding $4 every request\n # silently answered page 0, so the chevrons never moved.\n wwsearch) wwsearch \"${2:-}\" \"${3:-17}\" \"${4:-0}\" ;;\n # Alpha Coders: a category page, and the full-size URL for a picked\n # wallpaper (its detail page is the only place the real file appears, since\n # the listing gives no usable way to tell a jpg from a png).\n acsearch) acsearch \"${2:-}\" \"${3:-1}\" ;;\n acsearch) acsearch \"${2:-}\" \"${3:-1}\" ;;\n acresolve) acresolve \"${2:-}\" ;;\n thumbget) thumbget \"${2:-}\" ;;\n download) download \"${2:-}\" ;;\n *) printf '[]\\n'; exit 0 ;;\nesac\n", + "scripts/wallpaper-search.sh": "#!/usr/bin/env bash\n\nUA=\"Mozilla/5.0 (X11; Linux x86_64) Gecko/20100101 Firefox/126.0\"\n\nsearch_moewalls() {\n local query=\"${1:-}\"\n UA=\"$UA\" python3 - \"$query\" <<'PYEOF'\nimport concurrent.futures\nimport json\nimport os\nimport re\nimport sys\nimport urllib.parse\nimport urllib.request\n\nua = os.environ.get(\"UA\", \"Mozilla/5.0\")\n\ndef fetch(url, timeout=10):\n req = urllib.request.Request(url, headers={\"User-Agent\": ua, \"Referer\": \"https://moewalls.com/\"})\n with urllib.request.urlopen(req, timeout=timeout) as r:\n return r.read().decode(\"utf-8\", \"ignore\")\n\ndef post_entry(url):\n html = fetch(url)\n prev = re.search(r']*data-url=\"([^\"]+)\"', html)\n thumb = re.search(r'poster=\"([^\"]+)\"', html)\n if not prev or not token:\n return None\n res = re.search(r'resolutions-(\\d+)x(\\d+)', html)\n return {\n \"image\": \"https://go.moewalls.com/download.php?video=\" + token.group(1),\n \"thumb\": urllib.parse.urljoin(\"https://moewalls.com/\", thumb.group(1)) if thumb else \"\",\n \"preview\": urllib.parse.urljoin(\"https://moewalls.com/\", prev.group(1)),\n \"w\": int(res.group(1)) if res else 0,\n \"h\": int(res.group(2)) if res else 0,\n }\n\ntry:\n q = urllib.parse.quote(sys.argv[1])\n page = fetch(\"https://moewalls.com/?s=\" + q, timeout=12)\n posts = []\n for m in re.finditer(r'href=\"(https://moewalls\\.com/[a-z0-9-]+/[a-z0-9-]+-live-wallpaper/)\"', page):\n if m.group(1) not in posts:\n posts.append(m.group(1))\n out = []\n with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:\n for entry in ex.map(post_entry, posts[:24]):\n if entry:\n out.append(entry)\n print(json.dumps(out))\nexcept Exception:\n print(\"[]\")\nPYEOF\n}\n\nwh_state() {\n local base=\"${XDG_STATE_HOME:-$HOME/.local/state}/better\"\n mkdir -p \"$base\"\n printf '%s\\n' \"$base\"\n}\n\n# Shared rate gate for every wallhaven-bound request (API searches, thumbnail\n# fetches, picks), so the strip can never trip wallhaven's limits again: the\n# documented API cap is 45 calls/min (429 past it), and a Cloudflare WAF has\n# also banned whole IPs on request bursts \u2014 one such burst here took even a\n# cookie'd browser down with a 403. The gate is a rolling-window budget: it\n# lets a burst through (so a fresh page of thumbs loads in seconds instead of\n# trickling), but caps everything wallhaven-bound at WH_BUDGET (default 30)\n# requests per 60s, shared across all processes via a timestamp journal, and\n# latches a hard cooling-off period on any throttle/block signal.\nwh_state() {\n local base=\"${XDG_STATE_HOME:-$HOME/.local/state}/better\"\n mkdir -p \"$base\"\n printf '%s\\n' \"$base\"\n}\n\n# Suspend all wallhaven traffic for `secs` (default 60). Seeded by any 429/403\n# the fetchers see, so a throttle resets the whole pipeline's clock instead of\n# letting parts of the UI keep slipping requests through.\nwh_backoff() {\n local secs=\"${1:-60}\" base\n base=$(wh_state)\n printf '%s\\n' \"$(( $(date +%s) + secs ))\" > \"$base/wh-cooldown.until\"\n}\n\nwh_gate() {\n local base budget now oldest need_ms count\n base=$(wh_state)\n budget=\"${WH_BUDGET:-30}\"\n { [ \"$budget\" -gt 0 ] 2>/dev/null; } || budget=30\n exec 9>\"$base/wh-window.lock\"\n flock 9\n\n # Cooling-off latch: a recent 429/403 parks every wallhaven request until\n # the timestamp passes. The lock is held throughout so the whole pipeline\n # wakes together instead of trickling back in.\n local cooldown until now_s\n cooldown=\"$base/wh-cooldown.until\"\n if [ -f \"$cooldown\" ]; then\n until=$(cat \"$cooldown\" 2>/dev/null || echo 0)\n now_s=$(date +%s)\n if [ \"$now_s\" -lt \"$until\" ]; then\n sleep \"$(( until - now_s ))\"\n fi\n rm -f \"$cooldown\"\n fi\n\n window=\"$base/wh-window.ts\"\n while :; do\n now=$(date +%s%N)\n if [ -f \"$window\" ]; then\n awk -v now=\"$now\" ' $0 + 60000000000 > now ' \"$window\" > \"$window.tmp\" \\\n && mv \"$window.tmp\" \"$window\"\n count=$(wc -l < \"$window\")\n else\n count=0\n fi\n if [ \"$count\" -lt \"$budget\" ]; then\n printf '%s\\n' \"$now\" >> \"$window\"\n break\n fi\n # Budget exhausted: wait until the oldest in-window request ages out.\n oldest=$(head -1 \"$window\")\n need_ms=$(( 60000 - (now - oldest) / 1000000 ))\n if [ \"$need_ms\" -le 250 ]; then\n # Nearly expired anyway \u2014 nudge past without a clever sleep.\n sleep 0.3\n else\n sleep \"$(awk -v w=\"$need_ms\" 'BEGIN { printf \"%.3f\", w/1000 }')\"\n fi\n done\n flock -u 9\n}\n\n# Wallhaven browse/search. An empty query returns the default hot feed \u2014\n# clicking the strip's wallhaven chip lands there; a query tags it. The third\n# arg picks the sort bucket (hot, latest, top, random, favorites). Each maps to\n# the API's own sort, so the UI labels mean exactly what the site's tabs show:\n# hot -> the Hot feed (rolls over constantly), latest -> date_added, top ->\n# toplist over the last month (its topRange window rolls, so it is not frozen),\n# random -> random, favorites -> all-time Top Liked (kept for API parity, not\n# exposed in the UI because it never changes). A typed query keeps the chosen\n# sort \u2014 there is no silent favorites fallback, which used to make tag searches\n# show the same static most-favorited wallpapers forever. The API serves\n# ready-made thumbs, so results are URLs handed over to `thumbget` for a paced\n# local copy: nothing is downloaded until the strip actually shows it.\nwhsearch() {\n local query=\"${1:-}\" page=\"${2:-1}\" want=\"${3:-}\"\n case \"$page\" in\n ''|*[!0-9]*) page=1 ;;\n esac\n\n local enc sort extra raw code base key mapped\n enc=$(jq -rn --arg q \"$query\" '$q|@uri') || { printf '[]\\n'; return 0; }\n sort=\"hot\"\n extra=\"\"\n case \"$want\" in\n latest) sort=\"date_added\" ;;\n top) sort=\"toplist\"; extra=\"topRange=1M&\" ;;\n random) sort=\"random\" ;;\n favorites) sort=\"favorites\" ;;\n hot) sort=\"hot\" ;;\n esac\n # Hot is the default browse bucket and the API's real Hot sort: it rolls\n # over constantly, unlike toplist/views/favorites which sit on the same\n # mega-popular page one for weeks. Top maps to toplist (with a rolling 1M\n # window) so it changes over time instead of freezing on all-time views.\n # A typed query keeps the picked sort; there is no implied favorites.\n\n base=$(wh_state)\n key=$(printf '%s' \"$query|$page|$sort\" | sha1sum | cut -c1-24)\n cache=\"$base/wh-cache/$key.json\"\n # Dedupe: a repeat of the same query+page+sort within the window replays the\n # stored chunk without any network. The UI re-fires the current page on\n # picks, sort changes and surface re-entry, which used to be a fresh request\n # every time; now those are free.\n if [ -f \"$cache\" ] && [ $(( $(date +%s) - $(stat -c %Y \"$cache\") )) -lt 20 ]; then\n cat \"$cache\"\n return 0\n fi\n\n wh_gate\n raw=$(curl -s --max-time 15 -w $'\\n%{http_code}' -A \"$UA\" \\\n \"https://wallhaven.cc/api/v1/search?${query:+q=${enc}&}sorting=${sort}&${extra}order=desc&page=${page}\")\n code=\"${raw##*$'\\n'}\"\n raw=\"${raw%$'\\n'*}\"\n [ -n \"$code\" ] || code=000\n if [ \"$code\" = \"000\" ]; then\n # No HTTP response at all \u2014 offline, DNS failure, or a time-out. That\n # is a network hiccup, not wallhaven blocking us: don't latch a phantom\n # cooldown or a blocked chip, just hand back an empty page and let the\n # UI sit idle until connectivity returns.\n printf '[]\\n'\n return 0\n fi\n if [ \"$code\" != \"200\" ]; then\n # 429 = the documented rate cap (45/min); 403/5xx = WAF block or edge\n # hiccup. Either way latch a hard cooldown so no part of the UI can\n # keep requesting, and hand the UI a pause marker \u2014 its slow retry\n # timer owns the re-checks, and this is never cached.\n case \"$code\" in\n 429) wh_backoff 120 ;;\n *) wh_backoff 60 ;;\n esac\n printf '%s\\n' '{\"wallhaven\":\"blocked\"}'\n return 0\n fi\n [ -n \"$raw\" ] || { printf '%s\\n' '{\"wallhaven\":\"blocked\"}'; return 0; }\n\n # Map the wallhaven JSON to the strip's entry shape and keep the mapped\n # chunk as the dedupe cache line.\n mapped=$(printf '%s' \"$raw\" | jq -c '\n .data // []\n | map({\n image: .path,\n thumb: (.thumbs.large // .thumbs.original // \"\"),\n w: (.dimension_x // 0),\n h: (.dimension_y // 0)\n })\n | map(select(.image != null and .image != \"\"))\n ' 2>/dev/null || true)\n if [ -n \"$mapped\" ]; then\n mkdir -p \"$base/wh-cache\"\n printf '%s\\n' \"$mapped\" > \"$cache\"\n printf '%s\\n' \"$mapped\"\n else\n printf '%s\\n' '{\"wallhaven\":\"blocked\"}'\n fi\n}\n\n# ---------------------------------------------------------------------------\n# Alpha Coders\n# ---------------------------------------------------------------------------\n#\n# A third source, and the only one with no API at all: api.alphacoders.com is\n# gone (404), so a category page is scraped HTML. The site splits phone\n# wallpapers into separate `-phone-wallpapers` sections, so the\n# desktop sections are already free of them and no orientation filter is\n# needed here.\n#\n# Both pieces of a wallpaper live in different attributes of the same tile --\n# the id in the link to wall.alphacoders.com/big.php?i=, the thumbnail in\n# the picture's source -- so both are pulled per tile rather than one being\n# matched up to the other afterwards. Each id appears three times in the markup\n# (a source per breakpoint plus the img), so tiles are emitted once per unique\n# id; a naive extract returns the same wallpaper two or three times and the\n# strip fills with duplicates.\n#\n# The full-size file cannot be derived from the thumbnail URL. Alpha Coders\n# serves .jpg and .png from the same shape of path and nothing in the listing\n# says which, so a pick goes back to the wallpaper's own page for it. That\n# costs one request per pick, which is the right trade: picks are deliberate\n# and rare, and a strip full of tiles that cannot be downloaded is worthless.\n\n# One wallpaper's entry: the thumbnail the tile renders, and the page the pick\n# resolves through.\nAC_PAGE_URL='https://alphacoders.com'\nAC_VIEW_URL='https://wall.alphacoders.com/big.php?i='\n\n# True when $1 is one of the categories this source is browsed by. The site\n# has far more sections than the strip offers; these are the ones that line up\n# with what the other two sources already expose, so switching sources keeps\n# the meaning of the category row.\nac_category_ok() {\n case \"${1:-}\" in\n abstract|anime|amoled|architecture|art|cars|minimal|nature|tech) ;;\n *) return 1 ;;\n esac\n}\n\n# Parse a category page into the strip's entry shape. Reads the page on stdin.\n#\n# awk rather than grep -o here because the two fields are ordered differently\n# per tile -- the link precedes the picture in every tile seen so far, but a\n# regex that assumed it would silently drop the tail of a page the moment the\n# markup shifted. Matching the id anywhere in the tile and the thumb anywhere\n# in the same tile does not care about their order.\nac_parse_page() {\n awk '\n # New tile: a link to the wallpaper page carries its id.\n /big\\.php\\?i=[0-9]+/ {\n # The digits are matched directly rather than sliced out of a\n # wider match, so no offset arithmetic can drift and leave the\n # \"=\" or a stray character glued to the id.\n if (match($0, /big\\.php\\?i=[0-9]+/)) {\n line = $0\n sub(/.*big\\.php\\?i=/, \"\", line)\n sub(/[^0-9].*$/, \"\", line)\n id = line\n thumb = \"\"\n have = 1\n }\n }\n # The thumbnail for the tile being read. Kept as the last one seen so a\n # page that repeats the image per breakpoint still yields one thumb.\n have && /thumbbig-[0-9]+\\.webp/ {\n if (match($0, /https:\\/\\/images[0-9]*\\.alphacoders\\.com\\/[0-9]+\\/thumbbig-[0-9]+\\.webp/))\n thumb = substr($0, RSTART, RLENGTH)\n }\n # End of tile: the closes the link the id came from, which is the\n # only reliable boundary between one wallpaper and the next.\n have && /<\\/a>/ {\n if (thumb != \"\" && !(id in seen)) {\n seen[id] = 1\n printf \"{\\\"thumb\\\":\\\"%s\\\",\\\"image\\\":\\\"%s%s\\\"}\\n\", thumb, \"'\"$AC_VIEW_URL\"'\", id\n }\n id = \"\"\n thumb = \"\"\n have = 0\n }\n '\n}\n\n# Browse one category page. Output is JSON lines, which the caller turns into\n# an array; a page that cannot be fetched answers an empty array so the strip\n# shows its empty state rather than spinning.\nacsearch() {\n local cat=\"${1:-}\" page=\"${2:-1}\" base cache raw code mapped\n ac_category_ok \"$cat\" || cat=\"minimal\"\n case \"$page\" in\n ''|*[!0-9]*) page=1 ;;\n esac\n [ \"$page\" -lt 1 ] && page=1\n\n base=$(wh_state)\n cache=\"$base/ac-cache/$(printf '%s' \"$cat-$page\" | sha1sum | cut -c1-24).json\"\n\n # Cached for the same window as the wallhaven chunks: the strip re-fires a\n # page on every entry and category change, and the collection moves slowly\n # enough that a fresh fetch is almost never what is wanted.\n if [ -f \"$cache\" ] && [ $(( $(date +%s) - $(stat -c %Y \"$cache\") )) -lt 1200 ]; then\n cat \"$cache\"\n return 0\n fi\n\n # -L because four of the category names the strip uses are not the site's own:\n # it redirects art -> artistic, cars -> cars-(pixar), minimal ->\n # minimalist and tech -> technology. Without following, those four answer\n # 301 with an empty body, which parsed as \"this category has no\n # wallpapers\" and left four of the nine chips permanently blank.\n raw=$(curl -sL --max-time 20 -w $'\\n%{http_code}' -A \"$UA\" \\\n \"$AC_PAGE_URL/$cat-wallpapers?page=$page\")\n # The site serves an empty 200 for an out-of-range page rather than a 404,\n # so a page number past the end is a legitimate empty answer and not a\n # failure to report.\n code=\"${raw##*$'\\n'}\"\n raw=\"${raw%$'\\n'*}\"\n [ -n \"$code\" ] || code=000\n # 000 is offline or a timeout rather than the site refusing: no cooldown\n # latch here, because there is no rate budget to protect. An empty answer\n # lets the strip sit idle until connectivity returns.\n [ \"$code\" = \"200\" ] || { printf '[]\\n'; return 0; }\n\n # fromjson on each line: -R reads the awk output as raw strings, so without it\n# the array would hold the JSON as text and every consumer would get a string\n# where it expects an entry.\n mapped=$(printf '%s\\n' \"$raw\" | ac_parse_page \\\n | jq -R -s -c 'split(\"\\n\") | map(select(length > 0)) | map(fromjson)')\n\n if [ -z \"$mapped\" ] || [ \"$mapped\" = \"[]\" ]; then\n printf '[]\\n'\n return 0\n fi\n\n mkdir -p \"$(dirname \"$cache\")\"\n printf '%s\\n' \"$mapped\" > \"$cache\"\n printf '%s\\n' \"$mapped\"\n}\n\n# Recover the full-size image URL for a picked wallpaper.\n#\n# The detail page's og:image is the original file, named thumb-1920-.\n# because it is also what the page shows inline. The name is rewritten to\n# ., keeping the extension the site chose -- which is the whole point,\n# since guessing it wrong 404s on the png wallpapers.\nacresolve() {\n local url=\"${1:-}\" id raw full\n id=\"${url##*=}\"\n case \"$id\" in\n ''|*[!0-9]*) printf '\\n'; return 0 ;;\n esac\n\n raw=$(curl -s --max-time 20 -A \"$UA\" \"$url\")\n [ -n \"$raw\" ] || { printf '\\n'; return 0; }\n\n full=$(printf '%s\\n' \"$raw\" | grep -oE \\\n 'https://images[0-9]*\\.alphacoders\\.com/[0-9]+/thumb-1920-[0-9]+\\.(jpg|png)' \\\n | head -1 | sed -E 's#/thumb-1920-([0-9]+)\\.(jpg|png)$#/\\1.\\2#')\n\n printf '%s\\n' \"$full\"\n}\n\n# WallWidgy browse. The API's search endpoint only ever hands back a\n# handful of random picks, but its index endpoint lists the whole\n# collection with metadata (category, orientation, resolution,\n# timestamp). The index is cached for an hour; each call filters it\n# to desktop wallpapers of the chosen collection (or all of them),\n# newest first, and slices out the requested page. Results are JSON\n# in the strip's entry shape, like whsearch, plus the matching total\n# so the UI can page without asking the server.\nwwsearch() {\n local cat=\"${1:-}\" count=\"${2:-17}\" page=\"${3:-0}\"\n case \"$count\" in\n ''|*[!0-9]*) count=17 ;;\n esac\n [ \"$count\" -gt 2000 ] && count=2000\n [ \"$count\" -lt 1 ] && count=1\n case \"$page\" in\n ''|*[!0-9]*) page=0 ;;\n esac\n case \"$cat\" in\n all|\"\") cat=\"all\" ;;\n abstract|anime|amoled|architecture|art|cars|minimal|nature|tech) ;;\n *) cat=\"minimal\" ;;\n esac\n\n local base idx raw code\n base=$(wh_state)\n mkdir -p \"$base/ww-cache\"\n idx=\"$base/ww-index.json\"\n # The collection changes slowly, so the index is kept for an hour.\n # A stale or corrupt cache is re-fetched; with no response at all\n # a stale cache still serves, and only a cold cache yields an\n # empty page until connectivity returns.\n if ! { [ -f \"$idx\" ] && [ $(( $(date +%s) - $(stat -c %Y \"$idx\") )) -lt 3600 ] && jq -e 'type == \"array\"' \"$idx\" >/dev/null 2>&1; }; then\n raw=$(curl -s --max-time 20 -w $'\\n%{http_code}' -A \"$UA\" \\\n \"https://wallwidgy.vercel.app/api/wallpapers/index\")\n code=\"${raw##*$'\\n'}\"\n raw=\"${raw%$'\\n'*}\"\n [ -n \"$code\" ] || code=000\n if [ \"$code\" = \"000\" ]; then\n [ -f \"$idx\" ] || { printf '%s\\n' '{\"wallpapers\":[],\"total\":0}'; return 0; }\n elif [ \"$code\" != \"200\" ] || [ -z \"$raw\" ]; then\n printf '%s\\n' '{\"wallwidgy\":\"blocked\"}'\n return 0\n else\n printf '%s' \"$raw\" > \"$idx\"\n fi\n fi\n\n # Filter to desktop wallpapers of the collection, newest\n # first, then slice the page out. The thumb is the\n # collection's pre-scaled webp cache variant (a few tens\n # of KB) rather than the multi-megabyte master the image\n # field names \u2014 the strip renders tiles, not wallpapers,\n # and the master is fetched only when a pick is applied.\n jq -c --arg cat \"$cat\" --arg u \"https://raw.githubusercontent.com/not-ayan/storage/main/\" \\\n --argjson skip \"$(( page * count ))\" --argjson take \"$count\" '\n ([.[] | select(.orientation == \"Desktop\" and .file_main_name != null and .file_main_name != \"\")]\n | if $cat == \"all\" then .\n else map(select((.category // \"\") | ascii_downcase == (\"#\" + ($cat | ascii_downcase)))) end\n | sort_by(.timestamp) | reverse) as $all\n | {\n wallpapers: ($all[$skip : ($skip + $take)]\n | map({ image: ($u + \"main/\" + .file_main_name),\n thumb: (if (.file_cache_name // \"\") != \"\"\n then ($u + \"cache/\" + .file_cache_name)\n else ($u + \"main/\" + .file_main_name) end),\n w: (.width // 0), h: (.height // 0) })),\n total: ($all | length)\n }\n ' \"$idx\" 2>/dev/null || printf '%s\\n' '{\"wallwidgy\":\"blocked\"}'\n}\n\n# Fetch one wallhaven thumb into a disk cache at the same shared pace.\n# Cached hits are served instantly with no network and no gate (Qt decodes by\n# content, so the extensionless cache name is fine), so scrolling back over a\n# page costs zero wallhaven requests. The cache is kept under\n# WH_THUMB_MAX_MB (default 20): every fresh store prunes the least-recently\n# used thumbs (newest just saved is kept) until the directory fits again.\nthumbget() {\n local url=\"${1:-}\"\n [ -n \"$url\" ] || exit 1\n local base digest cache tmp\n base=\"${XDG_CACHE_HOME:-$HOME/.cache}/better/wh-thumbs\"\n digest=$(printf '%s\\n' \"$url\" | sha1sum | cut -c1-24)\n # The cache holds the resized JPEG, so the suffix is part\n # of the name. Qt decodes by content, and the LRU prune\n # below counts the directory either way.\n cache=\"$base/$digest.jpg\"\n # Cache check before mkdir \u2014 every hit skips the directory\n # creation entirely, which is the point of the disk cache.\n [ -s \"$cache\" ] && { printf '%s\\n' \"$cache\"; exit 0; }\n mkdir -p \"$base\"\n # The rate gate exists for wallhaven's API budget. The\n # WallWidgy thumbnails come from GitHub's raw CDN, which\n # has no such budget, so they fetch without it -- the\n # fetch pool on the QML side already bounds how many run\n # at once.\n case \"$url\" in\n *wallhaven.cc*) wh_gate ;;\n esac\n tmp=\"$base/.$digest.tmp\"\n trap 'rm -f \"$tmp\"' EXIT\n curl -fsSL --max-time 25 -A \"$UA\" -o \"$tmp\" \"$url\" \\\n || exit 1\n [ -s \"$tmp\" ] || exit 1\n # Shrink anything a tile never needs to a 720px JPEG\n # before caching it. Wallhaven serves ready-made thumbs\n # and WallWidgy's cache variant is a pre-scaled webp,\n # so most fetches are already inside the box and are\n # cached untouched -- no decode, no encode, no CPU. The\n # ones that are not go through vips when it is\n # installed: it resizes in a single pass at a fraction\n # of ImageMagick's CPU and memory, and writes JPEG, a\n # tenth the size of the PNG it replaces. ImageMagick\n # stays as the fallback.\n local dim w h\n if command -v vipsheader >/dev/null 2>&1; then\n # [0-9]+ (not *) so a bare \"x\" in the path -- the\n # home directory is /home/user -- cannot match\n # ahead of the real dimensions.\n dim=$(vipsheader \"$tmp\" 2>/dev/null | head -1 \\\n | grep -oE '[0-9]+x[0-9]+' | head -1 | tr 'x' ' ')\n fi\n if [ -z \"$dim\" ]; then\n export MAGICK_CONFIGURE_PATH=\"$(dirname \"$0\")/magick-policy\"\n dim=$(magick identify -format '%w %h' \"$tmp\" 2>/dev/null | head -1) || dim=\"\"\n case \"$dim\" in\n *[!0-9\\ ]*) dim=\"\" ;;\n esac\n fi\n w=${dim%% *}\n h=${dim##* }\n if [ -n \"$dim\" ] && { [ \"$w\" -gt 720 ] || [ \"$h\" -gt 720 ]; }; then\n if command -v vipsthumbnail >/dev/null 2>&1; then\n vipsthumbnail \"$tmp\" -s 720x720 -o \"$cache[Q=85]\" \\\n >/dev/null 2>&1 && [ -s \"$cache\" ] || rm -f \"$cache\"\n else\n export MAGICK_CONFIGURE_PATH=\"$(dirname \"$0\")/magick-policy\"\n magick \"$tmp\" -resize '720x720>' -quality 85 \"$cache\" \\\n 2>/dev/null && [ -s \"$cache\" ] || rm -f \"$cache\"\n fi\n # A resize that failed leaves nothing behind: fall\n # back to the fetched file as-is, decoded by content.\n [ -s \"$cache\" ] || mv \"$tmp\" \"$cache\"\n else\n mv \"$tmp\" \"$cache\"\n fi\n local max_mb total old\n max_mb=\"${WH_THUMB_MAX_MB:-20}\"\n { [ \"$max_mb\" -gt 0 ] 2>/dev/null; } || max_mb=20\n total=$(du -sk \"$base\" 2>/dev/null | awk '{print $1}')\n while [ \"${total:-0}\" -gt $(( max_mb * 1024 )) ]; do\n old=$(find \"$base\" -maxdepth 1 -type f ! -name '.*' \\\n -printf '%T@ %p\\n' | sort -n | head -1 | cut -d' ' -f2-)\n [ -n \"$old\" ] || break\n rm -f \"$old\"\n total=$(du -sk \"$base\" 2>/dev/null | awk '{print $1}')\n done\n printf '%s\\n' \"$cache\"\n}\n\nsearch() {\n local query=\"${1:-}\" kind=\"${2:-all}\"\n [ -n \"$query\" ] || { printf '[]\\n'; return 0; }\n\n if [ \"$kind\" = \"motion\" ]; then\n search_moewalls \"$query\"\n return 0\n fi\n\n local q=\"$query\" f=\",,,\"\n case \"$kind\" in\n still) f=\"type:photo\" ;;\n esac\n\n local enc vqd raw\n enc=$(jq -rn --arg q \"$q\" '$q|@uri') || { printf '[]\\n'; return 0; }\n\n vqd=$(curl -s --max-time 10 \"https://duckduckgo.com/?q=${enc}&iax=images&ia=images\" -A \"$UA\" \\\n | grep -oP 'vqd=\\\\?\"?\\K[0-9-]+' | head -1)\n [ -n \"$vqd\" ] || { printf '[]\\n'; return 0; }\n\n raw=$(curl -s --max-time 10 \\\n \"https://duckduckgo.com/i.js?l=us-en&o=json&q=${enc}&vqd=${vqd}&f=${f}&p=-1\" \\\n -A \"$UA\" -H \"Referer: https://duckduckgo.com/\")\n [ -n \"$raw\" ] || { printf '[]\\n'; return 0; }\n\n printf '%s' \"$raw\" | jq -c --arg kind \"$kind\" '\n (.results // [])\n | if $kind == \"still\" then map(select(.image // \"\" | test(\"\\\\.gif(\\\\?|$)\"; \"i\") | not)) else . end\n | map({\n image: .image,\n thumb: (.thumbnail // .image),\n w: (.width // 0 | if . == null then 0 else . end),\n h: (.height // 0 | if . == null then 0 else . end)\n })\n | map(select(.image != null and .image != \"\"))\n | .[0:60]\n ' 2>/dev/null || printf '[]\\n'\n}\n\ndownload() {\n set -euo pipefail\n url=\"${1:-}\"\n [ -n \"$url\" ] || exit 1\n\n # This script copy belongs to the better bar, so the collection a\n # pick lands in is the better bar's own state: the stock shell's\n # better/flags.json carries its own (empty) wallpaper dir, which\n # would drop every pick into the autodetect fallback instead of the\n # folder the bar resolved.\n flags=\"${XDG_STATE_HOME:-$HOME/.local/state}/better/flags.json\"\n wpdir=$(jq -r '.wallpaperDir // \"\"' \"$flags\" 2>/dev/null || echo \"\")\n [ -n \"$wpdir\" ] || wpdir=$(cat \"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper-dir\" 2>/dev/null || true)\n [ -n \"$wpdir\" ] || wpdir=\"$HOME/Pictures/Wallpapers\"\n # Every pick lands directly in the collection root so it joins the shuffle\n # bag; wallhaven keeps its id, moewalls/DDG get stamped names. No subfolder\n # is ever created, so browsing never leaves an empty downloads/ dir behind.\n\n case \"$url\" in\n https://go.moewalls.com/download.php*)\n fn=$(curl -fsI --max-time 20 -A \"$UA\" -e \"https://moewalls.com/\" \"$url\" \\\n | grep -oiP 'filename=\\K[^\"\\r\\n;]+' | head -1 | tr -d '/\\\\')\n [ -n \"$fn\" ] || fn=\"moewalls-$(date +%s).mp4\"\n out=\"$wpdir/$fn\"\n curl -fsL --max-time 600 -A \"$UA\" -e \"https://moewalls.com/\" -o \"$out\" \"$url\" || exit 1\n [ -s \"$out\" ] || exit 1\n printf '%s\\n' \"$out\"\n exit 0\n ;;\n https://wall.alphacoders.com/big.php\\?i=*)\n # The listing cannot say whether a wallpaper is a jpg or a png --\n # both come off the same shape of path -- so the pick resolves the\n # real file from the wallpaper's own page. That is one extra request\n # per pick, which is the right way round: picks are deliberate and\n # rare, whereas guessing wrong 404s every png wallpaper.\n id=\"${url##*=}\"\n case \"$id\" in\n ''|*[!0-9]*) exit 1 ;;\n esac\n full=$(acresolve \"$url\")\n [ -n \"$full\" ] || exit 1\n fn=\"alphacoders-$id.${full##*.}\"\n out=\"$wpdir/$fn\"\n curl -fsL --max-time 600 -A \"$UA\" -e \"https://alphacoders.com/\" -o \"$out\" \"$full\" || exit 1\n [ -s \"$out\" ] || exit 1\n printf '%s\\n' \"$out\"\n exit 0\n ;;\n https://w.wallhaven.cc/*)\n # Picked wallhaven wallpaper lands in the collection root itself so\n # it joins the shuffle bag; the filename keeps the wallhaven id. A\n # pick is a wallhaven-bound request too, so it shares the pace gate\n # that protects the API and thumb CDN.\n wh_gate\n fn=$(basename \"$url\" | tr -d '/\\\\')\n [ -n \"$fn\" ] || exit 1\n out=\"$wpdir/$fn\"\n curl -fsL --max-time 600 -A \"$UA\" -e \"https://wallhaven.cc/\" -o \"$out\" \"$url\" || exit 1\n [ -s \"$out\" ] || exit 1\n printf '%s\\n' \"$out\"\n exit 0\n ;;\n esac\n\n tmp=$(mktemp \"${TMPDIR:-/tmp}/ddg-wp.XXXXXX\")\n trap 'rm -f \"$tmp\" \"$tmp.out\"' EXIT\n\n curl -fsL --max-time 60 -A \"$UA\" -e \"https://duckduckgo.com/\" -o \"$tmp\" \"$url\" || exit 1\n [ -s \"$tmp\" ] || exit 1\n\n export MAGICK_CONFIGURE_PATH=\"$(dirname \"$0\")/magick-policy\"\n\n fmt=$(magick identify -format '%m' \"${tmp}[0]\" 2>/dev/null | head -1) || exit 1\n\n case \"$fmt\" in\n JPEG) ext=jpg ;;\n PNG) ext=png ;;\n GIF) ext=gif ;;\n WEBP) ext=webp ;;\n *) ext=png ;;\n esac\n\n out=\"$wpdir/ddg-$(date +%s)-${RANDOM}.${ext}\"\n\n if [ \"$ext\" = \"png\" ] && [ \"$fmt\" != \"PNG\" ]; then\n magick \"${tmp}[0]\" -strip \"png:$tmp.out\" 2>/dev/null || exit 1\n [ -s \"$tmp.out\" ] || exit 1\n mv \"$tmp.out\" \"$out\"\n else\n cp \"$tmp\" \"$out\"\n fi\n\n [ -s \"$out\" ] || exit 1\n printf '%s\\n' \"$out\"\n}\n\ncase \"${1:-}\" in\n search) search \"${2:-}\" \"${3:-all}\" ;;\n whsearch) whsearch \"${2:-}\" \"${3:-1}\" \"${4:-}\" ;;\n # WallWidgy pages through the index: the bar passes category, page\n # size and the zero-based page. Without forwarding $4 every request\n # silently answered page 0, so the chevrons never moved.\n wwsearch) wwsearch \"${2:-}\" \"${3:-17}\" \"${4:-0}\" ;;\n # Alpha Coders: a category page, and the full-size URL for a picked\n # wallpaper (its detail page is the only place the real file appears, since\n # the listing gives no usable way to tell a jpg from a png).\n acsearch) acsearch \"${2:-}\" \"${3:-1}\" ;;\n acsearch) acsearch \"${2:-}\" \"${3:-1}\" ;;\n acresolve) acresolve \"${2:-}\" ;;\n thumbget) thumbget \"${2:-}\" ;;\n download) download \"${2:-}\" ;;\n *) printf '[]\\n'; exit 0 ;;\nesac\n", "scripts/wallpaper-thumbs.sh": "#!/bin/sh\nMAGICK_CONFIGURE_PATH=\"$(dirname \"$0\")/magick-policy\"\nexport MAGICK_CONFIGURE_PATH\n\nSTATE=\"${XDG_STATE_HOME:-$HOME/.local/state}\"\nflags=\"$STATE/better/flags.json\"\nraw=$(jq -r '.wallpaperDir // \"\"' \"$flags\" 2>/dev/null || echo \"\")\n[ -n \"$raw\" ] || raw=$(cat \"$STATE/better-wallpaper-dir\" 2>/dev/null || true)\n[ -n \"$raw\" ] || raw=\"$HOME/Pictures/Wallpapers\"\n# Drop any trailing slash so a flags/state trailing-slash drift cannot spawn a\n# second cache directory (the folder hash must match the pill's listing hash).\nwpdir=$(printf %s \"$raw\" | sed 's#/*$##')\ncache=\"${XDG_CACHE_HOME:-$HOME/.cache}/better/wp-thumbs\"\n# Each wallpaper folder gets its own subdirectory keyed by the hash of its\n# normalized path, so files that share a basename across folders never stomp\n# each other and switching folders cannot show a stale thumb from the other\n# folder. The same hash is reproduced by the pill's listing command.\nkey=$(printf %s \"$wpdir\" | md5sum | cut -d' ' -f1)\ndir=\"$cache/$key\"\nmkdir -p \"$dir\"\n# Store the folder this cache dir belongs to so the sweep below can tell\n# drift-duplicates and vanished folders apart from folders still in use.\nprintf %s \"$wpdir\" > \"$dir/.srcdir\"\n\nsources() { # $1 = source folder; prints basenames of its wallpapers, sorted\n find \"$1\" -type f \\( -iname '*.jpg' -o -iname '*.png' -o -iname '*.gif' \\\n -o -iname '*.webp' -o -iname '*.mp4' -o -iname '*.webm' \\\n -o -iname '*.mkv' -o -iname '*.mov' \\) -printf '%f\\n' | sort -u\n}\n\nthumbs() { # $1 = cache subdir; prints its thumb basenames sans .png, sorted\n find \"$1\" -maxdepth 1 -type f -name '*.png' -printf '%f\\n' \\\n | sed 's/\\.png$//' | sort -u\n}\n\n# Keep a cache subdir down to thumbs whose source file still exists. The old\n# per-thumb `find` spawned a process per file, which dominated a whole refresh\n# on big folders; collecting basenames once and diffing catches every\n# rename/delete with two finds instead of one per file.\nprune_dir() { # $1 = thumb dir, $2 = source folder\n s=$(mktemp)\n h=$(mktemp)\n sources \"$2\" > \"$s\"\n thumbs \"$1\" > \"$h\"\n comm -23 \"$h\" \"$s\" | while IFS= read -r base; do\n rm -f \"$1/$base.png\"\n done\n rm -f \"$s\" \"$h\"\n}\n\n# Active folder: prune stale thumbs, then regenerate missing or outdated ones.\nprune_dir \"$dir\" \"$wpdir\"\n\nfind \"$wpdir\" -type f \\( -iname '*.jpg' -o -iname '*.png' -o -iname '*.gif' \\\n -o -iname '*.webp' -o -iname '*.mp4' -o -iname '*.webm' \\\n -o -iname '*.mkv' -o -iname '*.mov' \\) | while IFS= read -r src; do\n thumb=\"$dir/$(basename \"$src\").png\"\n if [ ! -s \"$thumb\" ] || [ \"$src\" -nt \"$thumb\" ]; then\n case \"$src\" in\n *.[Mm][Pp]4|*.[Ww][Ee][Bb][Mm]|*.[Mm][Kk][Vv]|*.[Mm][Oo][Vv])\n ffmpeg -y -loglevel quiet -i \"$src\" -frames:v 1 -vf 'scale=512:-2' -f image2 -c:v png \"$thumb.tmp\" 2>/dev/null\n ;;\n *)\n magick \"${src}[0]\" -strip -resize 512x \"png:$thumb.tmp\" 2>/dev/null\n ;;\n esac\n if [ -s \"$thumb.tmp\" ]; then\n mv \"$thumb.tmp\" \"$thumb\"\n else\n rm -f \"$thumb.tmp\"\n fi\n fi\ndone\n\n# Sweep every other cache subdir so the cache never holds thumbs that no\n# wallpaper still needs. A subdir survives only when its own folder exists and\n# differs from the active one; it is pruned against that folder's current\n# files (no regeneration \u2014 it warms up again if it is ever activated). Every\n# other subdir is dropped whole: drift-duplicates of the active folder (the\n# hash of their raw path matches, trailing slash or not), folders that have\n# since moved or vanished, and marker-less strays. The pill's listing and the\n# strip resolve the same key, so after a sweep thumb pngs match the wallpaper\n# count exactly.\nraw_flags=$(jq -r '.wallpaperDir // \"\"' \"$flags\" 2>/dev/null || echo \"\")\nraw_state=$(cat \"$STATE/better-wallpaper-dir\" 2>/dev/null || true)\nfor d in \"$cache\"/*/; do\n [ -d \"$d\" ] || continue\n k=$(basename \"$d\")\n [ \"$k\" = \"$key\" ] && continue\n if [ -f \"$d/.srcdir\" ]; then\n src=$(cat \"$d/.srcdir\")\n else\n # Legacy subdir (pre-marker): attribute it by hashing the raw path\n # values we know, any of which may have had a trailing slash.\n src=\"\"\n for r in \"$raw_flags\" \"$raw_state\"; do\n [ -n \"$r\" ] || continue\n if [ \"$(printf %s \"$r\" | md5sum | cut -d' ' -f1)\" = \"$k\" ]; then\n src=\"$r\"\n break\n fi\n done\n fi\n nsrc=$(printf %s \"$src\" | sed 's#/*$##')\n if [ -n \"$nsrc\" ] && [ -d \"$nsrc\" ] && [ \"$nsrc\" != \"$wpdir\" ]; then\n printf %s \"$nsrc\" > \"$d/.srcdir\"\n prune_dir \"$d\" \"$nsrc\"\n if [ -z \"$(find \"$d\" -maxdepth 1 -type f -name '*.png' -print -quit)\" ]; then\n rm -rf \"$d\"\n fi\n else\n rm -rf \"$d\"\n fi\ndone", "scripts/wallpaper.sh": "#!/usr/bin/env bash\nset -euo pipefail\n\nflags_file=\"${XDG_STATE_HOME:-$HOME/.local/state}/better/flags.json\"\nWPDIR=$(jq -r '.wallpaperDir // \"\"' \"$flags_file\" 2>/dev/null || echo \"\")\nFIT=$(jq -r '.wallpaperFit // \"crop\"' \"$flags_file\" 2>/dev/null || echo crop)\ncase \"$FIT\" in no|crop|fit|stretch) ;; *) FIT=crop ;; esac\nif [ -z \"$WPDIR\" ]; then\n # No explicit folder set: adopt an existing collection in the usual spots.\n # Two or more images counts as a collection, a single stray file does not,\n # so an incidental picture never hijacks the default.\n for cand in \"$HOME/Pictures/Wallpapers\" \"$HOME/Pictures/wallpapers\" \"$HOME/Wallpapers\" \"$HOME/wallpapers\"; do\n [ -d \"$cand\" ] || continue\n n=$(find \"$cand\" -maxdepth 1 -type f \\( -iname '*.jpg' -o -iname '*.png' -o -iname '*.gif' -o -iname '*.webp' -o -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mkv' -o -iname '*.mov' \\) | awk 'NR<=2' | wc -l)\n if [ \"$n\" -ge 2 ]; then WPDIR=\"$cand\"; break; fi\n done\n [ -n \"$WPDIR\" ] || WPDIR=\"$HOME/Pictures/Wallpapers\"\nfi\nRESOLVED=\"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper-dir\"\nprintf '%s\\n' \"$WPDIR\" > \"$RESOLVED\"\n# No-op mode for the QML side: re-resolve the folder and exit before touching any daemon state.\n[ \"${1:-}\" = \"resolve\" ] && exit 0\nSTATE=\"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper\"\n# Wallpapers the user has picked, one per line. Read by wallpaper_owner so a\n# pick that landed inside a theme's own backgrounds folder still counts as the\n# user's -- see the note there.\nPICK_MARKER=\"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper-picks\"\nMAP=\"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper-map\"\nBAG=\"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper-bag\"\nSTILL=\"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper-still.png\"\nFIT_STATE=\"${XDG_STATE_HOME:-$HOME/.local/state}/better-wallpaper-fit\"\nWLOG=\"${XDG_STATE_HOME:-$HOME/.local/state}/better/wallcolors.log\"\n\nis_video() {\n case \"${1##*.}\" in\n [Mm][Pp]4|[Ww][Ee][Bb][Mm]|[Mm][Kk][Vv]|[Mm][Oo][Vv]) return 0 ;;\n *) return 1 ;;\n esac\n}\n\n# mpvpaper keeps its real process name only when it runs as a bare ELF; distro\n# wrappers (NixOS private env, FHS shims...) run it under a different comm, so\n# exact-name matches silently miss it and a video lingers on after switching\n# back to a still. Match the command line instead, with the [m] bracket so the\n# pattern never matches the pgrep/pkill call itself.\nMPV_PAT='[m]pvpaper'\nmpv_running() { pgrep -f \"$MPV_PAT\" >/dev/null 2>&1; }\nmpv_list() { pgrep -af \"$MPV_PAT\" || true; }\nmpv_kill() { pkill -f \"$MPV_PAT\" 2>/dev/null || true; }\n\n# Soft-kill first so mpv can flush its quit bookkeeping, then escalate to\n# SIGKILL. A decoder wedged on the frame queue otherwise lingers with its full\n# buffer pool while the next video spawns on top, so a rapid video-to-video\n# switch ratchets the footprint up instead of swapping one player for another.\nstop_mpv() {\n mpv_running || return 0\n mpv_kill\n for _ in $(seq 1 10); do\n mpv_running || return 0\n sleep 0.1\n done\n pkill -9 -f \"$MPV_PAT\" 2>/dev/null || true\n for _ in $(seq 1 10); do\n mpv_running || return 0\n sleep 0.1\n done\n}\n\n# Fit intent mapped to mpv flags (videos have no awww --resize): cover zooms\n# with panscan, contain letterboxes, stretch distorts, center stays native, all\n# mirroring what aww's --resize does for stills.\nopts_for_fit() {\n case \"$FIT\" in\n no) printf '%s' \"no-audio loop-file=inf hwdec=auto video-unscaled=yes panscan=0\" ;;\n fit) printf '%s' \"no-audio loop-file=inf hwdec=auto panscan=0\" ;;\n stretch) printf '%s' \"no-audio loop-file=inf hwdec=auto keepaspect=no panscan=0\" ;;\n *) printf '%s' \"no-audio loop-file=inf hwdec=auto panscan=1.0\" ;;\n esac\n}\n\nensure_daemon() {\n awww query >/dev/null 2>&1 && return 0\n # Give a daemon the session started itself a moment to answer before\n # concluding there is none. The install docs put `exec-once = awww-daemon`\n # next to the shell's own exec-once, so both are spawned at compositor\n # start: if the daemon is still binding its socket when the shell first asks,\n # spawning our own races it for the same socket, and awww-daemon aborts on a\n # failed connect rather than declining politely. Waiting costs a second only\n # when nothing is running at all, which is the case that has to start one.\n local i\n for i in $(seq 1 5); do\n sleep 0.2\n awww query >/dev/null 2>&1 && return 0\n done\n local attempt\n for attempt in 1 2 3 4 5; do\n awww-daemon >/dev/null 2>&1 &\n for i in $(seq 1 15); do\n awww query >/dev/null 2>&1 && return 0\n sleep 0.2\n done\n done\n return 1\n}\n\nlist_pics() {\n find \"$WPDIR\" -type f \\( -iname '*.jpg' -o -iname '*.png' -o -iname '*.gif' -o -iname '*.webp' -o -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mkv' -o -iname '*.mov' \\)\n}\n\nrefill_bag() {\n local current=\"\" shuffled\n [ -r \"$STATE\" ] && current=$(cat \"$STATE\")\n shuffled=$(list_pics | shuf)\n [ -n \"$shuffled\" ] || return 0\n if [ \"$(printf '%s\\n' \"$shuffled\" | head -n1)\" = \"$current\" ] && [ \"$(printf '%s\\n' \"$shuffled\" | wc -l)\" -gt 1 ]; then\n shuffled=$(printf '%s\\n' \"$shuffled\" | tail -n +2; printf '%s\\n' \"$current\")\n fi\n mkdir -p \"$(dirname \"$BAG\")\"\n printf '%s\\n' \"$shuffled\" > \"$BAG\"\n}\n\npop_bag() {\n local line refilled=false\n mkdir -p \"$(dirname \"$BAG\")\"\n (\n flock 9\n while :; do\n if [ ! -s \"$BAG\" ]; then\n [ \"$refilled\" = true ] && exit 1\n refill_bag\n refilled=true\n [ -s \"$BAG\" ] || exit 1\n fi\n line=$(head -n1 \"$BAG\")\n tail -n +2 \"$BAG\" > \"$BAG.tmp\" && mv \"$BAG.tmp\" \"$BAG\"\n if [ -f \"$line\" ]; then\n printf '%s\\n' \"$line\"\n exit 0\n fi\n done\n ) 9>\"$BAG.lock\"\n}\n\n# True when the daemon is up AND already painting something. init needs this to\n# tell a healthy screen apart from an empty one: both answer `awww query`\n# successfully, so the old daemon_was_running test could not. A fresh login is\n# the case that matters \u2014 Hyprland starts awww-daemon at session start with no\n# image set, so the daemon is up, the desktop is black, and \"restore\" was being\n# skipped as unnecessary. jq answers it precisely; the grep fallback keeps it\n# right on a box without jq.\ndaemon_painted() {\n local js\n js=$(awww query -j 2>/dev/null) || return 1\n if command -v jq >/dev/null 2>&1; then\n printf '%s' \"$js\" \\\n | jq -e '[ .[]?[]?.displaying?.image? | select(type == \"string\" and length > 0) ] | length > 0' \\\n >/dev/null 2>&1\n return $?\n fi\n printf '%s' \"$js\" | grep -qE '\"image\"[[:space:]]*:[[:space:]]*\"[^\"]+\"'\n}\n\noutputs() {\n hyprctl monitors -j 2>/dev/null | jq -r '.[].name'\n}\n\nfocused_output() {\n hyprctl monitors -j 2>/dev/null | jq -r '[.[] | select(.focused)] | first.name // empty'\n}\n\ncursor_output() {\n local pos cx cy hit\n pos=$(hyprctl cursorpos 2>/dev/null) || { focused_output; return; }\n cx=${pos%%,*}\n cy=${pos##*, }\n hit=$(hyprctl monitors -j 2>/dev/null | jq -r --argjson cx \"$cx\" --argjson cy \"$cy\" \\\n 'map(select(\n $cx >= .x and $cx < .x + ((if (.transform % 2) == 1 then .height else .width end) / .scale) and\n $cy >= .y and $cy < .y + ((if (.transform % 2) == 1 then .width else .height end) / .scale)\n )) | first.name // empty')\n [ -n \"$hit\" ] && printf '%s\\n' \"$hit\" || focused_output\n}\n\nmap_get() {\n awk -F'\\t' -v o=\"$1\" '$1 == o { print $2; exit }' \"$MAP\" 2>/dev/null || true\n}\n\nmap_put() {\n mkdir -p \"$(dirname \"$MAP\")\"\n { awk -F'\\t' -v o=\"$1\" '$1 != o' \"$MAP\" 2>/dev/null || true; printf '%s\\t%s\\n' \"$1\" \"$2\"; } > \"$MAP.tmp\"\n mv \"$MAP.tmp\" \"$MAP\"\n}\n\nmap_put_all() {\n local o\n mkdir -p \"$(dirname \"$MAP\")\"\n : > \"$MAP.tmp\"\n for o in $(outputs); do\n printf '%s\\t%s\\n' \"$o\" \"$1\" >> \"$MAP.tmp\"\n done\n mv \"$MAP.tmp\" \"$MAP\"\n}\n\nmake_still() {\n ffmpeg -y -loglevel error -i \"$1\" -frames:v 1 -f image2 -c:v png \"$2.tmp\" && mv \"$2.tmp\" \"$2\"\n}\n\n# Animated picks wave in over their own first frame, then swap to the live\n# source with no transition: the frames are identical, so the gif restart and\n# the mpvpaper spawn stop reading as a flicker at the end of the wave.\napply_visual() {\n local pic=\"$1\" out=\"${2:-}\" show=\"$1\" st\n local -a oflag=()\n [ -n \"$out\" ] && oflag=(--outputs \"$out\")\n case \"${pic##*.}\" in\n [Mm][Pp]4|[Ww][Ee][Bb][Mm]|[Mm][Kk][Vv]|[Mm][Oo][Vv]|[Gg][Ii][Ff])\n st=\"$STILL\"\n [ -n \"$out\" ] && st=\"${STILL%.png}-$out.png\"\n make_still \"$pic\" \"$st\" && show=\"$st\"\n ;;\n esac\n awww img ${oflag[@]+\"${oflag[@]}\"} \"$show\" \\\n --resize \"$FIT\" \\\n --transition-type wave \\\n --transition-angle 30 \\\n --transition-wave \"60,30\" \\\n --transition-fps 60 \\\n --transition-step 90\n if [ \"$show\" != \"$pic\" ] && ! is_video \"$pic\"; then\n sleep 0.9\n awww img ${oflag[@]+\"${oflag[@]}\"} \"$pic\" --resize \"$FIT\" --transition-type none\n fi\n}\n\n# The desired video set comes from the map, collapsed to one '*' instance when\n# every output plays the same file so a shared video decodes once. The running\n# instances are compared first and the kill/respawn skipped on a match, so\n# changing one monitor's still never restarts the other monitor's video. The mpv\n# scaling follows the fit flag: a fit change keeps the same pics, but the stored\n# fit diverging from the running one forces the respawn so the videos re-arm\n# under the new options.\nsync_videos() {\n local desired=\"\" actual=\"\" o pic outs n_out n_vid VOPTS\n outs=$(outputs)\n for o in $outs; do\n pic=$(map_get \"$o\")\n [ -n \"$pic\" ] && [ -f \"$pic\" ] && is_video \"$pic\" || continue\n desired+=\"$o\"$'\\t'\"$pic\"$'\\n'\n done\n n_out=$(printf '%s\\n' \"$outs\" | sed '/^$/d' | wc -l)\n n_vid=$(printf '%s' \"$desired\" | sed '/^$/d' | wc -l)\n if [ \"$n_vid\" -gt 0 ] && [ \"$n_vid\" = \"$n_out\" ] && [ \"$(printf '%s' \"$desired\" | cut -f2 | sort -u | wc -l)\" = 1 ]; then\n desired=\"*\"$'\\t'\"$(printf '%s' \"$desired\" | head -n1 | cut -f2)\"$'\\n'\n fi\n desired=$(printf '%s' \"$desired\" | sort)\n # Running set keyed by the output, keeping the whole trailing path so a file\n # name with spaces can never read as a different video and force a kill-and-\n # respawn loop (each cycle re-decodes the clip and re-grows the buffer pools).\n actual=$(for o in $outs; do\n mpv_list | awk -v o=\"$o\" '\n { n = 0; for (i = 1; i <= NF; i++) if ($i == o || $i == \"*\") n = i }\n n { for (j = 1; j <= n; j++) $j = \"\"; sub(/^ +/, \"\"); print o \"\\t\" $0 }'\n done | sort -u)\n # When the desired set is the collapsed shared instance ('*'), fold the\n # running set to the same shape whenever every running video is that same\n # file: mpvpaper only reports real output names, so without this a shared\n # video would restart on every sync even though nothing changed.\n if [ \"$(printf '%s' \"$desired\" | head -n1 | cut -f1)\" = \"*\" ] \\\n && [ \"$(printf '%s' \"$actual\" | cut -f2 | sort -u | wc -l)\" = 1 ] \\\n && [ -n \"$(printf '%s' \"$actual\" | cut -f2 | head -n1)\" ]; then\n actual=\"*\"$'\\t'\"$(printf '%s' \"$actual\" | cut -f2 | sort -u)\"\n fi\n VOPTS=$(opts_for_fit)\n if [ \"$(cat \"$FIT_STATE\" 2>/dev/null || true)\" != \"$VOPTS\" ]; then\n if mpv_running; then\n stop_mpv\n actual=\"\"\n fi\n fi\n mkdir -p \"$(dirname \"$FIT_STATE\")\"\n printf '%s\\n' \"$VOPTS\" > \"$FIT_STATE.tmp\" && mv \"$FIT_STATE.tmp\" \"$FIT_STATE\"\n [ \"$desired\" = \"$actual\" ] && return 0\n if mpv_running; then\n stop_mpv\n fi\n [ -n \"$desired\" ] || return 0\n sleep 0.8\n while IFS=$'\\t' read -r o pic; do\n [ -n \"$o\" ] || continue\n setsid -f mpvpaper -p -o \"$VOPTS\" \"$o\" \"$pic\" >/dev/null 2>&1\n done <<< \"$desired\"\n}\n\n# The palette follows the focused monitor: whatever hangs there drives matugen,\n# the global state file and the global still, so the Settings dynamic re-run\n# and the strip's current marker stay coherent with what the user looks at.\npalette_update() {\n local pmode focused pic show mh md\n focused=$(focused_output)\n pic=\"\"\n [ -n \"$focused\" ] && pic=$(map_get \"$focused\")\n [ -n \"$pic\" ] || pic=$(cat \"$STATE\" 2>/dev/null || true)\n [ -n \"$pic\" ] && [ -f \"$pic\" ] || return 0\n show=\"$pic\"\n if is_video \"$pic\"; then\n make_still \"$pic\" \"$STILL\" && show=\"$STILL\" || return 0\n fi\n mkdir -p \"$(dirname \"$STATE\")\"\n printf '%s\\n' \"$pic\" > \"$STATE\"\n pmode=$(jq -r '.paletteMode // \"static\"' \"$flags_file\" 2>/dev/null || echo static)\n mkdir -p \"$(dirname \"$WLOG\")\"\n # Always refresh the shared wallpaper palette (colors.json) so both dynamic\n # modes (pill and dock) track the wallpaper. In manual mode the rice side\n # effects on top follow the pill's hue through --hue, which no longer\n # rewrites colors.json.\n python3 \"$(dirname \"$0\")/wallcolors.py\" \"$show\" >>\"$WLOG\" 2>&1 || true\n if [ \"$pmode\" = \"manual\" ]; then\n mh=$(jq -r '.manualHue // 30' \"$flags_file\" 2>/dev/null || echo 30)\n md=$(jq -r 'if .manualDark == false then \"light\" else \"dark\" end' \"$flags_file\" 2>/dev/null || echo dark)\n ms=$(jq -r '.manualSat // 0.5' \"$flags_file\" 2>/dev/null || echo 0.5)\n python3 \"$(dirname \"$0\")/wallcolors.py\" --hue \"$mh\" \"$md\" \"$ms\" >>\"$WLOG\" 2>&1 || true\n fi\n hyprctl reload >/dev/null 2>&1 || true\n busctl --user call com.mitchellh.ghostty /com/mitchellh/ghostty org.gtk.Actions \\\n Activate \"sava{sv}\" reload-config 0 0 >/dev/null 2>&1 || true\n # kitty: remote-control reload (needs allow_remote_control in kitty.conf);\n # silently skipped when kitty is missing, not running, or IPC is disabled.\n # The call can hang forever when kitty is installed but no instance is up, so\n # it is walled in a timeout. The -k is what makes the wall real: plain\n # `timeout` only sends SIGTERM and then waits indefinitely for the target to\n # die, so a kitty client that ignores it left this script (and the QML\n # Process that spawned it) sitting in the process list forever.\n command -v kitty >/dev/null 2>&1 \\\n && timeout -k 1 5 kitty @ set-colors \"${XDG_CACHE_HOME:-$HOME/.cache}/better/kitty-colors\" >/dev/null 2>&1 || true\n}\n\nmap_has_video() {\n local o pic\n for o in $(outputs); do\n pic=$(map_get \"$o\")\n if [ -n \"$pic\" ] && [ -f \"$pic\" ] && is_video \"$pic\"; then\n return 0\n fi\n done\n return 1\n}\n\n# Refit without re-animating: unlike apply_visual's wave, a fit-mode change\n# re-images the current stills with --transition-type none so toggling the\n# strip's fit control rescales the screen in place. Videos briefly show their\n# first frame again, then sync_videos restarts them under the new mpv scaling.\nsilent_reapply() {\n local o pic st\n for o in $(outputs); do\n pic=$(map_get \"$o\")\n [ -n \"$pic\" ] && [ -f \"$pic\" ] || pic=$(cat \"$STATE\" 2>/dev/null || true)\n [ -n \"$pic\" ] && [ -f \"$pic\" ] || continue\n if is_video \"$pic\"; then\n st=\"$STILL\"\n [ -n \"$o\" ] && st=\"${STILL%.png}-$o.png\"\n make_still \"$pic\" \"$st\" && pic=\"$st\"\n fi\n awww img --outputs \"$o\" --resize \"$FIT\" --transition-type none \"$pic\" >/dev/null 2>&1 || true\n done\n}\n\nrestore_all() {\n local o pic any=false\n for o in $(outputs); do\n pic=$(map_get \"$o\")\n [ -n \"$pic\" ] && [ -f \"$pic\" ] || pic=$(cat \"$STATE\" 2>/dev/null || true)\n [ -n \"$pic\" ] && [ -f \"$pic\" ] || pic=$(pop_bag) || continue\n map_put \"$o\" \"$pic\"\n apply_visual \"$pic\" \"$o\"\n any=true\n done\n [ \"$any\" = true ] || exit 0\n sync_videos\n palette_update\n exit 0\n}\n\ncmd=\"${1:-}\"\ntarget=\"\"\n\n# ---------------------------------------------------------------------------\n# wallpaper ownership\n# ---------------------------------------------------------------------------\n#\n# Who a wallpaper belongs to, which is what decides whether an incoming\n# wallpaper is allowed to replace the one on screen.\n#\n# The reason this exists: omarchy-theme-set repoints\n# current/background at one of the new theme's own backgrounds on every theme\n# switch, and both the wallpaper poll in ThemeSync and the theme-set hook feed\n# that path straight into `set`. So a wallpaper the user had picked was\n# replaced by the theme's every time a theme changed, with nothing on either\n# side able to tell a theme switch from a deliberate choice. The bar kept\n# painting, so it looked like the wallpaper had quietly reverted.\n#\n# Ownership separates the two cases. A path inside a theme's own backgrounds\n# folder is the theme's to choose, so it may take over freely -- that is how\n# switching themes is supposed to change the wallpaper. Anything else is a file\n# the user put there, so a theme wallpaper does not get to discard it.\n#\n# Both theme locations count as the theme's. current/theme/backgrounds is the\n# stock set; ~/.config/omarchy/backgrounds/ is where omarchy-theme-set\n# also looks (omarchy-theme-set:79), so a wallpaper a user drops there to\n# customise a theme is still that theme's to switch between. Reading only one\n# of the two would let a theme wallpaper overwrite the other one's pick.\n#\n# Prints \"theme\", \"user\", or \"none\" for a path that resolves to nothing --\n# a wallpaper that has been deleted, or was never a file. Callers treat \"none\"\n# as \"nothing worth protecting\", which is what lets a theme wallpaper through\n# once the file it would replace is gone.\nwallpaper_owner() {\n local path=\"$1\" resolved theme_name\n\n # -f follows symlinks, so current/background resolves to the real file\n # rather than reporting on the link itself.\n resolved=$(readlink -f -- \"$path\" 2>/dev/null) || resolved=\"\"\n [ -n \"$resolved\" ] && [ -f \"$resolved\" ] || { printf 'none\\n'; return 0; }\n\n # A recorded pick is the user's whatever folder it landed in. Checked\n # before the path test, because the common case is a pick that landed in\n # the theme's own backgrounds folder: sync_theme.py points the bar's picker\n # there so the chooser shows the theme's set, which means most picks are\n # theme-owned by path and a path test alone would let the next theme switch\n # take them over -- the wallpaper disappearing again, one theme later.\n if [ -f \"$PICK_MARKER\" ] && grep -qxF \"$resolved\" \"$PICK_MARKER\" 2>/dev/null; then\n printf 'user\\n'\n return 0\n fi\n\n theme_name=$(cat \"$HOME/.local/state/omarchy/current/theme.name\" 2>/dev/null) || theme_name=\"\"\n\n case \"$resolved\" in\n \"$HOME/.local/state/omarchy/current/theme/backgrounds/\"*) printf 'theme\\n' ;;\n \"$HOME/.config/omarchy/backgrounds/$theme_name/\"*) printf 'theme\\n' ;;\n *) printf 'user\\n' ;;\n esac\n}\n\n# Record a wallpaper as the user's own pick.\n#\n# Called from the strip's apply path, which is the only place a wallpaper is\n# chosen on purpose. The marker is what lets ownership survive the pick landing\n# inside a theme's backgrounds folder -- see wallpaper_owner.\n#\n# Appended rather than replaced, and only while the file is one this session can\n# vouch for: a stale entry naming a deleted wallpaper would keep protecting a\n# path that no longer exists, so entries are pruned on every write instead of\n# accumulating. The marker is a convenience, not the record of what is on\n# screen -- that stays $STATE.\nmark_pick() {\n local pic=\"${1:-}\" resolved keep existing\n\n resolved=$(readlink -f -- \"$pic\" 2>/dev/null) || return 0\n [ -n \"$resolved\" ] && [ -f \"$resolved\" ] || return 0\n\n mkdir -p \"$(dirname \"$PICK_MARKER\")\" || return 0\n\n keep=$(mktemp \"$PICK_MARKER.XXXXXX\") || return 0\n : > \"$keep\"\n if [ -f \"$PICK_MARKER\" ]; then\n while IFS= read -r existing; do\n [ -n \"$existing\" ] || continue\n [ \"$existing\" = \"$resolved\" ] && continue\n [ -f \"$existing\" ] || continue\n printf '%s\\n' \"$existing\" >> \"$keep\"\n done < \"$PICK_MARKER\"\n fi\n printf '%s\\n' \"$resolved\" >> \"$keep\"\n mv -f \"$keep\" \"$PICK_MARKER\" 2>/dev/null || rm -f \"$keep\"\n}\n\n# May $1 replace the wallpaper currently on screen? Exit 0 for yes.\n#\n# The rule in one line: a theme wallpaper may not replace a wallpaper the user\n# owns. Everything else -- another theme wallpaper, the user's own file, an\n# empty state, a file that has since been deleted -- may apply.\n#\n# --force skips the check, and the wallpaper surface passes it for a pick made\n# in the strip. A user who taps a theme's own wallpaper in the strip is making\n# that choice deliberately, and it must not be second-guessed here; only the\n# wallpaper arriving on its own, from a theme switch, is ever refused.\nshould_apply() {\n local candidate=\"$1\" force=\"${2:-}\" current\n\n [ \"$force\" = \"--force\" ] && return 0\n\n [ \"$(wallpaper_owner \"$candidate\")\" = \"theme\" ] || return 0\n\n current=$(cat \"$STATE\" 2>/dev/null) || current=\"\"\n [ -n \"$current\" ] || return 0\n [ \"$(wallpaper_owner \"$current\")\" = \"user\" ] || return 0\n\n return 1\n}\n\n# Report ownership, for the surface and for tests. Answering this without\n# touching the daemon is the point: the surface asks on every wallpaper change\n# to decide whether to follow, and that must not start or wait on awww.\nif [ \"$cmd\" = \"owner\" ]; then\n wallpaper_owner \"${2:-}\"\n exit 0\nfi\n\n# Record a pick. Reached before the daemon, because marking must work even when\n# awww is missing or wedged: the whole point is that the wallpaper survives\n# later, and a wallpaper that failed to paint is still the one the user chose.\nif [ \"$cmd\" = \"mark-pick\" ]; then\n mark_pick \"${2:-}\"\n exit 0\nfi\n\n# The guard on its own, for the same reason. Exits 0 when the wallpaper may\n# apply, so a caller can use it as a plain condition.\nif [ \"$cmd\" = \"should-apply\" ]; then\n should_apply \"${2:-}\" \"${3:-}\"\n exit $?\nfi\n\n# regen: refresh the shared wallpaper palette (colors.json, in the better cache\n# dir) from the current wallpaper, without touching the daemon or any wallpaper\n# state. Fired when a dynamic mode is picked, so switching to dynamic re-derives\n# from the live wallpaper even when the cached palette went stale \u2014 e.g. written\n# by an older install that stored the manual hue in colors.json.\nif [ \"$cmd\" = \"regen\" ]; then\n palette_update\n exit 0\nfi\n\ndaemon_was_running=true\nawww query >/dev/null 2>&1 || daemon_was_running=false\nensure_daemon || exit 0\n\nif [ \"$cmd\" = \"init\" ]; then\n if [ ! -s \"$MAP\" ] && [ -s \"$STATE\" ]; then\n pic=$(cat \"$STATE\")\n [ -f \"$pic\" ] && map_put_all \"$pic\"\n fi\n if [ \"$daemon_was_running\" = true ]; then\n if map_has_video && ! mpv_running; then\n sync_videos\n fi\n # Up is not the same as painted. When the daemon came up empty, put the\n # recorded wallpaper back; the old check only ever restored a daemon\n # that was down, which a session-managed one never is at this point.\n # Gated on a wallpaper actually being on record: with nothing recorded\n # there is nothing to restore, and restore_all would otherwise reach for\n # the bag and paint a random pick nobody asked for. When the daemon\n # already shows the right image this is skipped, so reloading the shell\n # never replays the wave transition over a correct desktop.\n if { [ -s \"$STATE\" ] || [ -s \"$MAP\" ]; } && ! daemon_painted; then\n restore_all\n fi\n exit 0\n fi\n restore_all\nelif [ \"$cmd\" = \"set\" ]; then\n pic=\"${2:-}\"\n [ -f \"$pic\" ] || exit 1\n # The output may be omitted (\"set \") or given as \"all\", and --force\n # may sit on either side of it, so both are pulled out of the argument\n # list rather than read positionally. Reading $3 as the target would miss\n # a trailing --force, and the guard would then refuse a wallpaper the user\n # had just picked in the strip.\n shift # drop \"set\"\n force=\"\"\n target=\"\"\n for arg in \"$@\"; do\n case \"$arg\" in\n \"$pic\") ;; # the wallpaper, already read\n --force) force=\"--force\" ;;\n *) [ -z \"$target\" ] && target=\"$arg\" ;;\n esac\n done\n [ \"$target\" = \"all\" ] && target=\"\"\n\n # A pick is recorded before the wallpaper is painted, not after: the paint\n # can fail (a missing codec, a full disk) and the wallpaper is still the\n # one the user chose, so the marker must not depend on the paint landing.\n [ -n \"$force\" ] && mark_pick \"$pic\"\n\n # A wallpaper the user owns outranks a theme wallpaper arriving on its\n # own, so refuse and put the symlink back. Both halves matter: without the\n # repoint, current/background keeps advertising the theme's wallpaper, so\n # the next poll re-offers it and the wallpaper looks like it keeps\n # snapping back. omarchy-theme-set wrote that link, and it is the state\n # every other wallpaper reader trusts, so it is left agreeing with what is\n # actually on screen.\n if ! should_apply \"$pic\" \"$force\"; then\n kept=$(cat \"$STATE\" 2>/dev/null) || kept=\"\"\n if [ -n \"$kept\" ] && [ -f \"$kept\" ]; then\n ln -nsf \"$kept\" \"$HOME/.local/state/omarchy/current/background\" 2>/dev/null || true\n printf 'better: kept your wallpaper, ignoring the theme default\\n' >&2\n fi\n exit 0\n fi\nelif [ \"$cmd\" = \"fit\" ]; then\n mode=\"${2:-crop}\"\n case \"$mode\" in no|crop|fit|stretch) ;; *) mode=crop ;; esac\n if command -v jq >/dev/null 2>&1; then\n jq --arg v \"$mode\" '.wallpaperFit = $v' \"$flags_file\" > \"$flags_file.tmp\" 2>/dev/null \\\n && mv \"$flags_file.tmp\" \"$flags_file\" || true\n fi\n FIT=\"$mode\"\n silent_reapply\n sync_videos\n exit 0\nelse\n scope=$(jq -r '.randomScope // \"all\"' \"$flags_file\" 2>/dev/null || echo all)\n if [ \"$scope\" = \"cursor\" ]; then\n target=$(cursor_output)\n fi\n pic=$(pop_bag) || exit 0\nfi\n\n[ -n \"$pic\" ] || exit 0\n\nif [ -n \"$target\" ]; then\n map_put \"$target\" \"$pic\"\nelse\n map_put_all \"$pic\"\nfi\n\napply_visual \"$pic\" \"$target\"\nsync_videos\npalette_update\n", "shell.qml": "//@ pragma UseQApplication\n\nimport QtQuick\nimport Quickshell\nimport Quickshell.Io\nimport Quickshell.Wayland\nimport Quickshell.Hyprland\nimport \"Singletons\"\nimport \"components\"\nimport \"surfaces\"\n\n/**\n * Better top shell. Each monitor carries two layer-shell windows:\n *\n * - `reserve` is a zero-content strip that only claims an exclusive zone the\n * height of the rest pill, so tiled windows always sit below the pill even\n * while it is expanded or a surface is open.\n * - `overlay` is a full-screen transparent Overlay layer hosting the single\n * morphing pill anchored at top-centre. The pill never moves windows and is\n * never re-parented; it just grows in place, so every surface grows out of\n * the rest pill instead of popping up as a separate panel.\n *\n * Input is routed by the window mask. While the pill is collapsed the mask is\n * the pill rect only, so the rest of the screen clicks through to windows.\n * While the pill is expanded (hovered/pinned) or a surface is open the mask is\n * cleared so the whole layer catches clicks. A backdrop press dismisses, and\n * keyboard focus is taken on demand so Escape closes the open surface.\n */\nShellRoot {\n id: root\n\n property string openMon: \"\"\n property string openSurface: \"\"\n property string peekMon: \"\"\n\n /**\n * Menu submenu the launcher should open at, set by the `menu` IPC handler\n * for the keys that used to summon `omarchy-menu toggle `. Empty\n * means the launcher's root. Read by the Launcher surface on open.\n */\n property string menuRoute: \"\"\n\n /**\n * The pill's resting height and corner radius, published so the dock can\n * match them. The dock lives in a sibling PanelWindow and cannot read the\n * `pill` id directly; this is the channel between them.\n *\n * One value rather than one per monitor: every Pill here is sized from the\n * same `s` on identically-configured outputs, so they agree anyway. Mixed\n * resolution or scale would make this a shared approximation, and it would\n * need to become a map keyed on output name.\n */\n property real pillBarHeight: 0\n property real pillBarRadius: 0\n\n /**\n * Battery notification latches, change-triggered by UPower (never polled).\n * Low battery escalates down the levels \u2014 25% then 20% fire once each as a\n * normal warning, and 15% opens a critical announcement that repeats every\n * ten minutes until the battery is plugged in. The latch re-arms when the\n * battery charges or rises back above 25%. Full fires once when the battery\n * reports fully charged, so charge-limited systems (e.g. an 80% cut-off)\n * announce at their actual full point.\n */\n property int battNotifiedBelow: 100\n property bool fullBattNotified: false\n\n function battNote(urgency, summary, body) {\n if (battNoteProc.running)\n return;\n battNoteProc.command = urgency.length > 0\n ? [\"notify-send\", \"-a\", \"Better Bar\", \"-u\", urgency, summary, body]\n : [\"notify-send\", \"-a\", \"Better Bar\", summary, body];\n battNoteProc.running = true;\n }\n\n /**\n * One-shot level crossings on the way down, lowest threshold first, so a\n * battery already below several levels (e.g. booting at 18%) only announces\n * the most urgent one it has passed \u2014 20% there, never 25% and 20% together.\n * At or below the critical level the repeat timer takes over.\n */\n function battCheck() {\n if (!Battery.present)\n return;\n if (!Battery.discharging || Battery.pct >= 25) {\n root.battNotifiedBelow = 100;\n if (root.battRepeatTimer)\n root.battRepeatTimer.stop();\n return;\n }\n var levels = [[15, \"critical\"], [20, \"normal\"], [25, \"normal\"]];\n for (var i = 0; i < levels.length; i++) {\n if (Battery.pct <= levels[i][0] && levels[i][0] < root.battNotifiedBelow) {\n root.battNotifiedBelow = levels[i][0];\n var critical = levels[i][1] === \"critical\";\n root.battNote(critical ? \"critical\" : \"normal\",\n critical ? \"Battery critical\" : \"Low battery\",\n Battery.pct + \"% remaining \u2014 plug in your charger\"\n + (critical ? \" now.\" : \" soon.\"));\n break;\n }\n }\n if (Battery.pct <= 15 && root.battRepeatTimer && !root.battRepeatTimer.running)\n root.battRepeatTimer.start();\n }\n\n function refresh() {\n Hyprland.refreshMonitors();\n Hyprland.refreshWorkspaces();\n Hyprland.refreshToplevels();\n }\n\n Component.onCompleted: {\n refresh();\n Devices.restore();\n void GameMode.active;\n root.battCheck();\n wallpaperBootProc.running = true;\n void Walls.count;\n }\n\n /**\n * Boot wallpaper restore. Hyprland starts awww-daemon at login, but a daemon\n * that has just come up has no image set, so the desktop came back black\n * after every reboot even though the state file and the per-output map were\n * written correctly the whole time \u2014 nothing ever read them back at startup.\n * This fires from the shell root rather than from the Walls singleton on\n * purpose: a `pragma Singleton` is only constructed the first time something\n * references it, and the only referencers are the wallpaper strip, the theme\n * settings page and the lock surface, all of which are loaded on demand. In\n * the singleton that hook would not run until the strip was first opened,\n * which is exactly the thing being fixed.\n *\n * wallpaper.sh init re-applies the recorded wallpaper only when the daemon is\n * painting nothing, so a plain shell restart against a correct desktop stays\n * silent instead of replaying the transition over it.\n */\n Process {\n id: wallpaperBootProc\n command: [\"bash\", Config.hyprPath(\"scripts\", \"wallpaper.sh\"), \"init\"]\n }\n\n Process {\n id: battNoteProc\n }\n\n Timer {\n id: battRepeatTimer\n interval: 10 * 60 * 1000\n repeat: true\n onTriggered: {\n if (!Battery.present || !Battery.discharging || Battery.pct > 15) {\n stop();\n return;\n }\n root.battNote(\"critical\", \"Battery critical\",\n Battery.pct + \"% remaining \u2014 plug in your charger now.\");\n }\n }\n\n Connections {\n target: Battery\n function onPctChanged() { root.battCheck(); }\n function onDischargingChanged() { root.battCheck(); }\n function onFullChanged() {\n if (!Battery.present)\n return;\n if (Battery.full && !root.fullBattNotified) {\n root.fullBattNotified = true;\n root.battNote(\"normal\", \"Battery full\",\n Battery.pct + \"% \u2014 you can unplug.\");\n } else if (!Battery.full) {\n root.fullBattNotified = false;\n }\n }\n }\n\n /**\n * After an update relaunches the shell, raise a one-shot toast naming what\n * landed, so the apply ends in a confirmation instead of a silent restart. The\n * updater drops the marker just before it restarts; the short delay lets the\n * notification server own the bus before we post to it, and the marker is\n * removed as it is read so the toast only ever fires once.\n */\n Timer {\n interval: 2500\n running: true\n onTriggered: updatedToast.running = true\n }\n Process {\n id: updatedToast\n command: [\"sh\", \"-c\",\n \"m=\\\"${XDG_STATE_HOME:-$HOME/.local/state}/better/updated\\\"; [ -f \\\"$m\\\" ] || exit 0; \"\n + \"b=$(cat \\\"$m\\\"); rm -f \\\"$m\\\"; \"\n + \"gdbus call --session --dest org.freedesktop.Notifications \"\n + \"--object-path /org/freedesktop/Notifications \"\n + \"--method org.freedesktop.Notifications.Notify \"\n + \"Pill 0 '' 'Pill updated' \\\"$b\\\" '[]' '{}' 5000 >/dev/null 2>&1\"]\n }\n\n PanelWindow {\n id: inhibitWin\n visible: Flags.keepAwake\n implicitWidth: 1\n implicitHeight: 1\n color: \"transparent\"\n exclusionMode: ExclusionMode.Ignore\n WlrLayershell.layer: WlrLayer.Background\n WlrLayershell.namespace: \"better-inhibit\"\n WlrLayershell.keyboardFocus: WlrKeyboardFocus.None\n anchors { top: true; left: true }\n IdleInhibitor { window: inhibitWin; enabled: Flags.keepAwake }\n }\n\n /**\n * The Wayland IdleInhibitor above only pauses the compositor's own idle\n * (DPMS); hypridle runs its own timer and never sees it, so the lock still\n * fired with keep-awake on. A logind idle inhibitor is the wire hypridle\n * does respect, so hold one for as long as the flag is set.\n */\n /** True once the stale-inhibitor sweep has run; gates our own lock. */\n property bool inhibitSwept: false\n\n Process {\n id: inhibitSweep\n running: !root.inhibitSwept\n command: [\"sh\", \"-c\",\n \"for p in $(pgrep -x systemd-inhibit); do case \\\"$(tr '\\\\0' ' ' < /proc/$p/cmdline 2>/dev/null)\\\" in *\\\"--who=Better Bar\\\"*) kill $p 2>/dev/null ;; esac; done; exit 0\"]\n onExited: root.inhibitSwept = true\n }\n\n Process {\n running: Flags.keepAwake && root.inhibitSwept\n command: [\"systemd-inhibit\", \"--what=idle:sleep\", \"--who=Better Bar\",\n \"--why=keep awake\", \"--mode=block\", \"sleep\", \"infinity\"]\n }\n\n /**\n * omarchy's idle service \u2014 the screensaver-and-lock timers in the\n * stock shell \u2014 runs its own clock and watches only its stay-awake\n * indicator file, so neither inhibitor above reaches it: the\n * screensaver kept firing with keep-awake on, and the compositor\n * inhibitor vanishes the moment this daemon restarts. The indicator\n * file is the wire it does watch, so mirror the flag onto it: while\n * the flag is set the file exists and the idle service stays\n * disarmed; on startup with the flag off the file is dropped, so a\n * daemon that died mid-keep-awake cannot pin idle off forever.\n */\n Process {\n running: Flags.keepAwake && root.inhibitSwept\n command: [\"bash\", \"-c\",\n \"mkdir -p \\\"$HOME/.local/state/omarchy/indicators\\\" && \"\n + \"touch \\\"$HOME/.local/state/omarchy/indicators/stay-awake\\\"\"]\n }\n\n Process {\n running: !Flags.keepAwake && root.inhibitSwept\n command: [\"bash\", \"-c\",\n \"rm -f \\\"$HOME/.local/state/omarchy/indicators/stay-awake\\\"\"]\n }\n\n /**\n * Only these raw events can change what the pill renders (per-monitor\n * active workspace, minimized toplevels, monitor hotplug). Everything\n * else (window drags, resizes, title spam) must not trigger the triple\n * model refresh, which costs three Hyprland IPC round-trips.\n */\n readonly property var refreshEvents: ({\n workspace: true, workspacev2: true,\n createworkspace: true, createworkspacev2: true,\n destroyworkspace: true, destroyworkspacev2: true,\n moveworkspace: true, moveworkspacev2: true,\n renameworkspace: true, activespecial: true,\n focusedmon: true, focusedmonv2: true,\n openwindow: true, closewindow: true,\n movewindow: true, movewindowv2: true,\n fullscreen: true,\n monitoradded: true, monitoraddedv2: true, monitorremoved: true\n })\n\n Connections {\n target: Hyprland\n function onRawEvent(event) {\n if (root.refreshEvents[event.name])\n root.refresh();\n }\n }\n\n /**\n * Raised when the settings index's Dock Settings tile is picked.\n * The dock's id lives inside each monitor's dock window delegate,\n * so the root cannot call it directly; every delegate listens\n * here and opens its own panel when the monitor matches the pill\n * that asked.\n */\n signal dockSettingsRequested(string mon)\n\n /**\n * An empty monitor argument resolves to the focused monitor here, so the\n * keybind scripts skip their hyprctl+jq round trip and a surface open costs\n * one IPC call instead of three process spawns.\n */\n function toggleSurface(mon, surface) {\n if (!mon || mon.length === 0)\n mon = Hyprland.focusedMonitor ? Hyprland.focusedMonitor.name : \"\";\n // A capability handed to a plugin is rendered by that plugin\n // now; opening Better Bar's own surface for it as well would\n // put two of a kind on screen at once.\n if (Plugins.surfaceDisabled(surface))\n return;\n if (surface === \"dock\") {\n // The dock's settings panel is hosted in the dock window, not\n // the pill, so a \"dock\" nav from the settings index folds the\n // pill's settings back and opens the panel the gear used to.\n // Routed through the signal above: `dock` is an id inside\n // the per-monitor dock window delegate, invisible from the\n // root's scope, so the delegate opens its own panel when\n // the monitor matches the pill that asked.\n root.dockSettingsRequested(mon);\n root.close();\n return;\n }\n if (root.openMon === mon && root.openSurface === surface) {\n root.close();\n return;\n }\n root.openMon = mon;\n root.openSurface = surface;\n }\n\n function close() {\n root.openMon = \"\";\n root.openSurface = \"\";\n root.menuRoute = \"\";\n }\n\n /**\n * How tall the band must be while `mon` has a surface open.\n *\n * The band is sized by the reserve window, which is a sibling of the pill\n * and cannot see it, so the open pill's own height is published here by\n * each monitor's Pill through `surfaceBandHeight`. Reading `pill.height`\n * directly from the reserve would be a ReferenceError: `pill` is scoped to\n * the overlay delegate. 0 means \"no surface is open on that monitor\".\n */\n property var surfaceBandHeight: ({})\n\n function openSurfaceHeight(mon) {\n var h = surfaceBandHeight[mon];\n return typeof h === \"number\" && h > 0 ? h : 0;\n }\n\n function peek(mon) {\n root.peekMon = root.peekMon === mon ? \"\" : mon;\n }\n\n /**\n * Open the launcher at a menu route.\n *\n * Three cases, and the middle one is the subtle one:\n *\n * not open open it, with the route already set so the launcher\n * never shows the root for a frame\n * open, same route toggle it shut, so a key never feels stuck open\n * open, other route move it. It must NOT go through `toggleSurface`,\n * which only looks at monitor + surface name: the\n * launcher is already open there, so it would read as\n * \"same surface\" and close the very thing the key\n * was asking to navigate.\n */\n function openMenuRoute(mon, route) {\n if (!mon || mon.length === 0)\n mon = Hyprland.focusedMonitor ? Hyprland.focusedMonitor.name : \"\";\n var alreadyOpen = root.openMon === mon && root.openSurface === \"launcher\";\n if (alreadyOpen && root.menuRoute === (route || \"\")) {\n root.close();\n return;\n }\n root.menuRoute = route || \"\";\n if (alreadyOpen)\n return;\n root.toggleSurface(mon, \"launcher\");\n }\n\n /**\n * True while the named monitor's active workspace reports a fullscreen\n * client. One definition, because the pill's band and the dock's band both\n * have to agree with their own bar about when that bar is on screen: the\n * pill and the dock each retract off their edge, and a band kept reserved\n * for a bar that has gone is a hole in the desktop.\n */\n function fullscreenOn(name) {\n if (!name)\n return false;\n var mons = Hyprland.monitors.values;\n for (var i = 0; i < mons.length; i++) {\n if (mons[i].name === name) {\n var ws = mons[i].activeWorkspace;\n var o = ws ? ws.lastIpcObject : null;\n return o ? !!o.hasfullscreen : false;\n }\n }\n return false;\n }\n\n /**\n * Whether the dock bar is on screen on this monitor: enabled, and not\n * retracted by a fullscreen client or by game mode. The bar window and the\n * band that reserves its space both read this, so the two can never disagree\n * about whether the dock is showing -- which is what left a reserved hole in\n * the desktop whenever the dock hid while the band did not.\n */\n function dockBarShown(mon) {\n return Flags.dockEnabled && !root.fullscreenOn(mon) && !Flags.gameMode;\n }\n\n IpcHandler {\n target: \"better\"\n function mixer(mon: string): void { root.toggleSurface(mon, \"mixer\"); }\n function calendar(mon: string): void { root.toggleSurface(mon, \"calendar\"); }\n function launcher(mon: string): void { root.toggleSurface(mon, \"launcher\"); }\n function power(mon: string): void { root.toggleSurface(mon, \"power\"); }\n function link(mon: string): void { root.toggleSurface(mon, \"link\"); }\n function battery(mon: string): void { root.toggleSurface(mon, \"battery\"); }\n function gameMode(mon: string): void { Flags.gameMode = !Flags.gameMode; }\n function sysmon(mon: string): void { root.toggleSurface(mon, \"sysmon\"); }\n function system(mon: string): void { root.toggleSurface(mon, \"sysmon\"); }\n function clipboard(mon: string): void { root.toggleSurface(mon, \"clipboard\"); }\n function wallpaper(mon: string): void { root.toggleSurface(mon, \"wallpaper\"); }\n function media(mon: string): void {\n if (Players.list.length > 0)\n root.toggleSurface(mon, \"media\");\n }\n function peek(mon: string): void { root.peek(mon); }\n function hide(): void { root.close(); }\n\n /**\n * Memory saver door: drop every closed surface on every monitor right\n * away, regardless of how much of its 30s tail is left. The open\n * surface is never touched; reopening a dropped surface rebuilds it.\n */\n function unloadAll(): void { Surfaces.unloadClosed(); }\n\n /** Opens any surface by name, settings sub-pages included; dev and scripting door. */\n function page(mon: string, name: string): void { root.toggleSurface(mon, name); }\n\n /**\n * The launcher opened at a menu route. Omarchy's menu plugin is\n * disabled on this desktop, so the stock keys aimed at it do nothing;\n * the pill's launcher hosts the same omarchy-menu.jsonc tree, so a route\n * resolves to the same submenu it used to.\n *\n * Accepts an id (\"setup.default.browser\") or an alias (\"power-menu\"),\n * matching `omarchy menu summon `. An unknown route opens the\n * launcher at its root rather than not at all.\n */\n function menu(mon: string, route: string): void { root.openMenuRoute(mon, route); }\n\n /**\n * The two halves of the SUPER+M minimize toggle, driven by the\n * minimize-toggle script which has already read the focused window. A\n * desktop window drops into the minimized stash; a window already stashed\n * comes back to the workspace it is handed, so the same key hides and\n * restores. Both target the window by address so they act on the one the\n * user pressed on, not whatever the compositor calls active afterwards.\n */\n function minimizeWindow(addr: string): void {\n Hyprland.dispatch('hl.dsp.window.move({ workspace = \"special:minimized\", follow = false, window = \"address:' + addr + '\" })');\n }\n function restoreWindow(arg: string): void {\n var p = arg.split(\"|\");\n if (p.length < 2 || p[0].length === 0)\n return;\n Hyprland.dispatch('hl.dsp.window.move({ workspace = \"' + p[1] + '\", window = \"address:' + p[0] + '\" })');\n }\n }\n\n Variants {\n model: Quickshell.screens\n\n PanelWindow {\n id: reserve\n required property var modelData\n readonly property real s: modelData ? (modelData.height / 1080) * Flags.uiScale : 1\n readonly property real topGap: 8 * Flags.topGap * s\n /**\n * Reserved-band ceiling with auto-hide off. A full-footprint reserve\n * (hover 58, quick-record 76) cost too much window space, so this is\n * just the resting face plus the transient OSD ring (44): the flashes\n * that actually cover windows (workspace/volume/brightness/record)\n * stay clear, while the cursor-driven hover (58) may still dip past\n * the band by a few pixels.\n */\n readonly property real restFaceH: 44 * s\n\n /** Trimming the reserved band below the pill's bottom lets windows climb, so App gap sets the pill-to-window air without touching the desktop gaps_out. The strip face docks flush to the screen top (its own topGap is zero), so it never adds the margin. */\n readonly property real reservedH: Flags.mainDisplay === \"strip\"\n ? Math.max(0, restFaceH - 12 * (1 - Flags.appGap) * s)\n : Math.max(0, restFaceH + topGap - 12 * (1 - Flags.appGap) * s)\n\n readonly property real gameBarH: 34 * s\n\n /**\n * The band is reserved only while the pill is on screen. Game mode\n * keeps the pill up as a slim bar, so it keeps a slim band; a\n * fullscreen client slides the pill clean off the top edge, and that\n * case used to fall through to reservedH and leave a hole in the\n * desktop with nothing in it, the same defect the dock's band had.\n * The condition is named once because it drove both exclusiveZone and\n * implicitHeight, which must agree.\n */\n readonly property bool monFullscreen: root.fullscreenOn(modelData.name)\n readonly property bool offCursor: CursorTrack.offCursor(modelData.name)\n readonly property bool surfaceOpenHere: root.openMon === modelData.name && root.openSurface.length > 0\n readonly property real bandH: monFullscreen ? 0\n : (surfaceOpenHere ? root.openSurfaceHeight(modelData.name)\n : (Flags.gameMode ? gameBarH : ((Flags.autoHide || offCursor) ? 0 : reservedH)))\n\n screen: modelData\n color: \"transparent\"\n exclusionMode: ExclusionMode.Normal\n exclusiveZone: bandH\n aboveWindows: true\n\n anchors { top: true; left: true; right: true }\n implicitHeight: bandH\n\n mask: emptyReserve\n Region { id: emptyReserve }\n }\n }\n\n Variants {\n model: Quickshell.screens\n\n PanelWindow {\n id: dockReserve\n required property var modelData\n readonly property real s: modelData ? (modelData.height / 1080) * Flags.uiScale : 1\n /**\n * Bottom band the dock sits in: just the bar's footprint plus its\n * float gap, so tiled windows climb above the resting dock but the\n * strips on either side stay usable. With dock auto-hide on nothing\n * is reserved at all and the dock floats over the desktop until the\n * edge is touched; while the dock is retracted empty (no pins, no\n * running apps, no usage-history shelf \u2014 DockState.empty) the band\n * is released too, so windows may tile all the way down. Kept in\n * step with DockBar.dockH (components/DockBar.qml): minimal chips\n * are shorter than titled ones, and the float lip mirrors the\n * pill's topGap at half scale.\n */\n readonly property real dockH: root.pillBarHeight > 0\n ? Math.max(root.pillBarHeight, 44 * s)\n : (Flags.dockMinimal ? 58 : 68) * s\n readonly property real dockGap: 4 * Flags.topGap * s\n readonly property real reservedH: dockH + dockGap\n\n /** Whether the dock bar is actually on screen here; mirrors dockWin.suppressed. */\n readonly property bool barShown: root.dockBarShown(modelData.name)\n\n /**\n * The band is reserved only while the bar that fills it is on screen.\n * This used to key off dockEnabled and auto-hide alone, so the space\n * survived every state that hides the dock: game mode and a\n * fullscreen client both retract the bar, and the band stayed, a hole\n * in the desktop with nothing in it. Keyed to barShown, the same\n * predicate dockWin uses to decide suppression, so the two cannot\n * disagree. A once-duplicated condition, now named once.\n */\n readonly property real bandH: (barShown && !Flags.dockAutoHide && !DockState.empty) ? reservedH : 0\n\n screen: modelData\n color: \"transparent\"\n exclusionMode: ExclusionMode.Normal\n exclusiveZone: bandH\n aboveWindows: true\n\n anchors { bottom: true; left: true; right: true }\n implicitHeight: bandH\n\n mask: emptyDockReserve\n Region { id: emptyDockReserve }\n }\n }\n\n Variants {\n model: Quickshell.screens\n\n PanelWindow {\n id: overlay\n required property var modelData\n readonly property real s: modelData ? (modelData.height / 1080) * Flags.uiScale : 1\n readonly property real topGap: 8 * Flags.topGap * s\n readonly property string surface: root.openMon === modelData.name ? root.openSurface : \"\"\n readonly property bool surfaceOpen: surface.length > 0\n readonly property bool modal: surfaceOpen || pill.held || pill.expandLatch\n\n /**\n * True while this monitor's active workspace reports a fullscreen\n * client. The pill then retracts off the top edge and the whole\n * layer becomes click-through so fullscreen content owns the screen.\n */\n readonly property bool monFullscreen: root.fullscreenOn(modelData.name)\n\n onMonFullscreenChanged: if (monFullscreen) {\n if (root.openMon === modelData.name) root.close();\n if (root.peekMon === modelData.name) root.peekMon = \"\";\n pill.pinned = false;\n pill.expandLatch = false;\n }\n\n screen: modelData\n color: \"transparent\"\n exclusionMode: ExclusionMode.Ignore\n WlrLayershell.layer: WlrLayer.Overlay\n WlrLayershell.keyboardFocus: (surfaceOpen && !pill.pluginSurfaceOpen) ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None\n WlrLayershell.namespace: \"better\"\n\n anchors { top: true; left: true; right: true; bottom: true }\n\n mask: monFullscreen ? hiddenRegion : (modal ? fullRegion : (pill.mode === \"game\" ? pillRegion : (Flags.autoHide ? (pill.revealSession || pill.transientLive ? revealPillRegion : (pill.expanded ? pillRegion : revealRegion)) : (pill.hidden ? hiddenRegion : pillRegion))))\n Region { id: hiddenRegion }\n\n /**\n * The only input left alive while the pill is auto-hidden: a thin\n * top-centre edge strip the pointer can always find. Hovering it\n * slides the pill back in, whether it is resting on a focused\n * monitor or retracted off a non-focused one. Kept to a few pixels\n * so the pill only ever appears when the cursor actually touches the\n * screen edge \u2014 passing through the top area deeper down triggers\n * nothing, and (because the strip doubles as the reveal input mask)\n * no invisible click-blocking band lingers below the visible pill.\n */\n Region {\n id: revealRegion\n readonly property real revealW: pill.stripBar ? Math.max(420 * pill.s, pill.stripFaceW) : 420 * pill.s\n readonly property real revealH: 10 * pill.s\n x: Math.max(0, overlay.width / 2 - revealW / 2)\n y: 0\n width: revealW\n height: revealH\n }\n Region {\n id: pillRegion\n readonly property real baseW: Math.max(pill.width, pill.targetW)\n x: pill.x + (pill.width - baseW) / 2\n y: pill.y\n width: baseW + pill.inputPadRight\n height: Math.max(pill.height, pill.targetH)\n\n /**\n * A strip layout menu hangs below the pill, outside `pillRegion`,\n * so the pill would retract and the card would refuse clicks the\n * instant the cursor leaves the pill body. While any card is open\n * the pill latches itself expanded (`stripMenuOpen`); this box\n * brings the whole drop span into the input mask so the pointer\n * can glide down into the menu and its rows stay clickable.\n */\n Region {\n x: pill.x\n y: pill.y + pill.height\n width: pill.width\n height: pill.stripMenuOpen ? 150 * s : 0\n }\n }\n\n /**\n * Mask while the pill is being pulled in from the reveal strip. The\n * plain pillRegion alone would flicker: it follows the pill's morphing\n * geometry, so a cursor waiting in the strip below the still-growing\n * pill slips out of the mask, drops the hover, and re-triggers the\n * reveal in a loop. Unioning the fixed strip keeps the cursor covered\n * for the whole pull-in; the pill part grows to catch it on the way up.\n */\n Region {\n id: revealPillRegion\n x: revealRegion.x\n y: revealRegion.y\n width: revealRegion.width\n height: revealRegion.height\n\n Region {\n x: pillRegion.x\n y: pillRegion.y\n width: pillRegion.width\n height: pillRegion.height\n }\n }\n Region {\n id: fullRegion\n width: overlay.width\n height: overlay.height\n }\n\n MouseArea {\n anchors.fill: parent\n enabled: overlay.modal\n acceptedButtons: Qt.AllButtons\n onPressed: (mouse) => {\n if (overlay.surfaceOpen) {\n var inside = mouse.x >= pillRegion.x && mouse.x <= pillRegion.x + pillRegion.width\n && mouse.y >= pillRegion.y && mouse.y <= pillRegion.y + pillRegion.height;\n if (!inside)\n root.close();\n else if (mouse.y <= pillRegion.y + 40 * pill.s\n && mouse.x <= pillRegion.x + 52 * pill.s)\n pill.surfaceBack();\n } else {\n pill.pinned = false;\n pill.expandLatch = false;\n root.peekMon = \"\";\n }\n }\n }\n\n Connections {\n target: Flags\n function onAutoHideChanged() {\n if (!Flags.autoHide) {\n pill.revealSession = false;\n pill.hovered = false;\n pill.hoverLatch = false;\n } else {\n pill.pinned = false;\n }\n }\n }\n\n FocusScope {\n id: focusScope\n anchors.fill: parent\n focus: overlay.surfaceOpen\n\n HoverHandler {\n enabled: !overlay.surfaceOpen && !pill.pinned\n onHoveredChanged: if (enabled) pill.hovered = hovered\n }\n Keys.onEscapePressed: {\n if (pill.stripMenuOpen) {\n pill.closeStripMenus();\n } else if (pill.wallpaperMenuOpen) {\n pill.wallpaperMenuClose();\n } else {\n root.close();\n }\n }\n Keys.onUpPressed: (e) => {\n if (pill.wallpaperMenuOpen) { pill.wallpaperMenuMove(-1); e.accepted = true; }\n else e.accepted = pill.mixerStep(1) || pill.settingsMove(-1);\n }\n Keys.onDownPressed: (e) => {\n if (pill.wallpaperMenuOpen) { pill.wallpaperMenuMove(1); e.accepted = true; }\n else e.accepted = pill.mixerStep(-1) || pill.settingsMove(1);\n }\n Keys.onLeftPressed: (e) => {\n if (pill.wallpaperMenuOpen) { e.accepted = true; }\n else if (pill.mixerOpen) { pill.mixerFocusMove(-1); e.accepted = true; }\n else if (pill.wallpaperOpen) { pill.wallpaperMove(-1); e.accepted = true; }\n else if (pill.powerOpen) { pill.powerMove(-1); e.accepted = true; }\n else if (pill.settingsLike) { pill.settingsAdjust(-1); e.accepted = true; }\n }\n Keys.onRightPressed: (e) => {\n if (pill.wallpaperMenuOpen) { e.accepted = true; }\n else if (pill.mixerOpen) { pill.mixerFocusMove(1); e.accepted = true; }\n else if (pill.wallpaperOpen) { pill.wallpaperMove(1); e.accepted = true; }\n else if (pill.powerOpen) { pill.powerMove(1); e.accepted = true; }\n else if (pill.settingsLike) { pill.settingsAdjust(1); e.accepted = true; }\n }\n\n /**\n * Return/Enter/Space: the wallpaper strip applies its focused\n * thumb on every press; the power surface fires a safe tile on\n * the first press and, for a destructive tile, holds the heat\n * fill across autorepeat presses (drained on release). Autorepeat\n * is swallowed for everything else so a held key never re-fires.\n */\n Keys.onPressed: (e) => {\n if (pill.wallpaperMenuOpen) {\n if (e.key === Qt.Key_Return || e.key === Qt.Key_Enter || e.key === Qt.Key_Space) {\n if (!e.isAutoRepeat) pill.wallpaperMenuPick();\n e.accepted = true;\n } else if (e.text.length === 1) {\n e.accepted = true;\n }\n return;\n }\n if (pill.wallpaperWh && !pill.wallpaperWhTyping) {\n if (e.key === Qt.Key_Backspace) {\n pill.wallpaperWhBackspace();\n e.accepted = true;\n return;\n }\n if (e.text.length === 1 && e.text > \" \") {\n pill.wallpaperWhType(e.text);\n e.accepted = true;\n return;\n }\n }\n if (pill.wallpaperOpen && !pill.wallpaperSearching && !pill.wallpaperWh\n && e.text.length === 1 && e.text > \" \") {\n pill.wallpaperType(e.text);\n e.accepted = true;\n return;\n }\n if (e.key !== Qt.Key_Return && e.key !== Qt.Key_Enter && e.key !== Qt.Key_Space)\n return;\n if (pill.wallpaperOpen) {\n if (!e.isAutoRepeat) pill.wallpaperActivate();\n e.accepted = true;\n } else if (pill.powerOpen) {\n if (!e.isAutoRepeat) pill.powerPress();\n e.accepted = true;\n } else if (pill.settingsLike) {\n if (!e.isAutoRepeat) pill.settingsActivate();\n e.accepted = true;\n }\n }\n Keys.onReleased: (e) => {\n if (e.isAutoRepeat)\n return;\n if ((e.key === Qt.Key_Return || e.key === Qt.Key_Enter || e.key === Qt.Key_Space)\n && pill.powerOpen) {\n pill.powerRelease();\n e.accepted = true;\n }\n }\n\n /**\n * Drag-and-drop gateway for the auto-hidden pill. The reveal\n * strip keeps its input while the pill is retracted, but drops\n * are routed to drop targets, not to the passive HoverHandler\n * that opens the strip \u2014 so a hidden pill would never see a\n * dragged file. This target shadows the strip's geometry, pulls\n * the pill in on drag enter and hands the drop to the same\n * install flow as the resting pill. Sits below the pill in the\n * scene so drops on the visible pill itself keep winning.\n */\n DropArea {\n id: stripDrop\n width: pill.stripBar ? Math.max(420 * overlay.s, pill.width) : 420 * overlay.s\n height: 8 * overlay.s\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.top: parent.top\n enabled: (Flags.autoHide || (Flags.cursorFollow && pill.hidden))\n && !pill.surfaceOpen && !Flags.gameMode\n visible: enabled\n keys: [\"text/uri-list\"]\n onEntered: (drag) => {\n drag.acceptProposedAction();\n pill.revealSession = true;\n pill.dropEntered(drag.urls);\n }\n onExited: {\n pill.dropExited();\n pill.revealSession = false;\n }\n onDropped: (drop) => {\n drop.acceptProposedAction();\n pill.dropDropped(drop.urls);\n pill.revealSession = false;\n }\n }\n\n Pill {\n id: pill\n /** Submenu the launcher should open at; set by `menu`. */\n property string menuRoute: root.menuRoute\n anchors.top: parent.top\n anchors.topMargin: (pill.stripBar || pill.mode === \"game\") ? 0 : overlay.topGap\n anchors.horizontalCenter: parent.horizontalCenter\n\n Behavior on anchors.topMargin {\n NumberAnimation {\n duration: Motion.morph\n easing.type: Motion.easeMorph\n easing.bezierCurve: Motion.morphCurve\n }\n }\n s: overlay.s\n screenName: overlay.modelData.name\n barWindow: overlay\n surface: overlay.surface\n forcePinned: root.peekMon === overlay.modelData.name\n\n opacity: (overlay.monFullscreen && !pill.transientLive) ? 0 : (osdPopup.active ? 0 : 1)\n Behavior on opacity {\n NumberAnimation {\n duration: Motion.morph\n easing.type: Motion.easeMorph\n easing.bezierCurve: Motion.morphCurve\n }\n }\n transform: Translate {\n y: ((overlay.monFullscreen && !pill.transientLive) || pill.hidden) ? -(pill.height + overlay.topGap) : 0\n Behavior on y {\n NumberAnimation {\n duration: Motion.morph\n easing.type: Motion.easeMorph\n easing.bezierCurve: Motion.morphCurve\n }\n }\n }\n\n readonly property bool bandFollowsSurface: overlay.surfaceOpen\n onBandFollowsSurfaceChanged: {\n var h = Object.assign({}, root.surfaceBandHeight);\n h[pill.screenName] = overlay.surfaceOpen ? pill.height : 0;\n root.surfaceBandHeight = h;\n }\n\n onRequestSurface: (name) => root.toggleSurface(overlay.modelData.name, name)\n onRequestPluginSurface: (pluginId, settingsMode) => root.toggleSurface(overlay.modelData.name, \"plugin:\" + pluginId + (settingsMode ? \":panel\" : \"\"))\n onRequestClose: root.close()\n }\n\n OsdPopup {\n id: osdPopup\n anchors.top: parent.top\n anchors.topMargin: (pill.stripBar || pill.mode === \"game\") ? 0 : overlay.topGap\n anchors.horizontalCenter: parent.horizontalCenter\n s: overlay.s\n screenName: overlay.modelData.name\n expanded: pill.expanded\n topFlat: (pill.mode === \"game\" || pill.stripBar) ? 1 : 0\n suppressed: overlay.surfaceOpen || pill.held\n || pill.mode === \"game\" || (pill.toastActive && Notifs.toastCritical)\n }\n }\n\n onSurfaceOpenChanged: if (surfaceOpen) focusScope.forceActiveFocus()\n\n Connections {\n target: pill\n function onWallpaperSearchingChanged() {\n if (!pill.wallpaperSearching && overlay.surfaceOpen)\n focusScope.forceActiveFocus();\n }\n }\n }\n }\n\n /**\n * Per-monitor dock, mirroring the pill's two-window split: `dockReserve`\n * claims the bottom band as an exclusive zone while the dock is persistent\n * (enabled and not auto-hiding), and this full-screen overlay hosts the\n * `DockBar` pinned to the bottom edge. Its mask is the bar rect while the\n * dock is shown; with auto-hide on, a thin bottom-centre strip stays live\n * so the pointer can always pull the bar back in, and the whole layer goes\n * click-through while the monitor runs fullscreen or game mode is active\n * (surfaces do not suppress it: opening the launcher or a settings page\n * keeps the dock on screen and usable). Keyboard focus is never taken, so\n * the dock can not steal focus from a tiled window below.\n */\n Variants {\n model: Quickshell.screens\n\n PanelWindow {\n id: dockWin\n required property var modelData\n readonly property real s: modelData ? (modelData.height / 1080) * Flags.uiScale : 1\n /** Float gap between the resting dock and the screen's bottom edge: a subtle lip, smaller than the pill's topGap float. */\n readonly property real dockGap: 4 * Flags.topGap * s\n readonly property string surface: root.openMon === modelData.name ? root.openSurface : \"\"\n readonly property bool surfaceOpen: surface.length > 0\n\n /**\n * The dock is off screen here, and retracts off the bottom edge: it\n * is switched off, or a fullscreen client owns the screen, or game\n * mode has quieted the desktop. Read from the same predicate the\n * band that reserves this bar's space uses, so the bar and the space\n * it occupies can never come apart.\n */\n readonly property bool suppressed: !root.dockBarShown(modelData.name)\n\n /**\n * The one state where suppression must NOT take the panel with it.\n *\n * The dock's settings panel carries its own \"Dock\" switch, and that\n * switch turns off the very bar whose gear opened the panel. Hosting\n * the panel here, as a sibling of the bar rather than a child of it,\n * is what makes that survivable: the panel stays put while the bar\n * goes, so the panel is still a way back for the few seconds it takes\n * to change your mind.\n *\n * The pill's Display surface also carries a \"Dock\" switch\n * (`dockRow` there), which is the real way back and needs none of\n * this. This is the belt to that pair of braces, so switching the\n * dock off from the dock's own settings never becomes a one-way door\n * \u2014 and it is scoped narrowly, so fullscreen and game mode still\n * hide everything and nothing else can pin a panel to the screen.\n */\n readonly property bool dockForcedOpen: dock.settingsOpen && !Flags.dockEnabled\n\n /**\n * The block the panel and the bar occupy together, and the whole of\n * the input region while the panel is open. Dismissal is NOT decided\n * here: it rides the bar's existing \"the pointer has left\" signal \u2014\n * the same `hovered` flag and the same 350ms grace that drive the\n * dock's own auto-hide \u2014 so the panel and the bar cannot disagree\n * about when the pointer went away. See `revealTimer` in DockBar.\n *\n * This is not the arrangement that was here first, and the reason is\n * worth keeping because the wrong version looked defensible. It\n * asked the panel for a `pointerInside` flag and treated that as a\n * VETO on dismissing, which made it unreliable: the panel is opened\n * from the gear, which sits on the bar, so on the ordinary path the\n * pointer never crosses the panel and the veto is never satisfied.\n * It fired only when the pointer happened to travel through the\n * panel on its way somewhere else \u2014 which is the \"sometimes\" exactly.\n *\n * The part of that diagnosis that was wrong, and that a sentinel\n * outline was built on: leave events are not the problem. A\n * per-item hover flag does go stale, because leaving is the absence\n * of an event rather than an event, so a flag can only ever say \"I\n * think it left\" and never \"it left\". But the same signal drives the\n * bar's auto-hide, which demonstrably works, so the honest reading\n * is that stale flags were never what made this intermittent. The\n * fix is to decide from the one flag the bar already acts on, not to\n * stand a second mechanism up beside it.\n *\n * The region is the block itself, with no margin grown around it.\n * Extra margin buys a hover-based dismissal nothing \u2014 the pointer\n * only has to leave the block to be gone \u2014 and it is not free: every\n * pixel of margin is screen this window takes from whatever is\n * underneath. A bounding box is not a union, though, so the block\n * does carry dead space beside the panel and in the gap above the\n * bar, and the click floor below is what answers for that.\n */\n readonly property rect dismissBase: dockForcedOpen\n ? Qt.rect(dockPanelRegion.x, dockPanelRegion.y, dockPanelRegion.width, dockPanelRegion.height)\n : Qt.rect(dockSettingsUnion.x, dockSettingsUnion.y, dockSettingsUnion.width, dockSettingsUnion.height)\n\n screen: modelData\n color: \"transparent\"\n exclusionMode: ExclusionMode.Ignore\n WlrLayershell.layer: WlrLayer.Overlay\n WlrLayershell.keyboardFocus: (dock.settingsOpen)\n ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None\n WlrLayershell.namespace: \"better-dock\"\n\n anchors { top: true; left: true; right: true; bottom: true }\n\n /**\n * The dock panel's keyboard host. The window takes keyboard focus\n * only while its panel is open (see `keyboardFocus` above); this\n * scope holds the focus for that lifetime so keys routed here land\n * on an item instead of vanishing, and forwards the keys the panel\n * rows otherwise have nowhere to go. The app-search field's own\n * `Keys.onPressed` consumes what it wants, so it never leaks up\n * here. Without this an open panel is a keyboard black hole.\n */\n FocusScope {\n anchors.fill: parent\n focus: dock.settingsOpen\n Keys.onEscapePressed: dock.closeSettings()\n Keys.onPressed: (e) => {\n var panel = dockPanel.item;\n if (!panel)\n return;\n if (e.key === Qt.Key_Up) {\n panel.kbMove(-1);\n e.accepted = true;\n } else if (e.key === Qt.Key_Down) {\n panel.kbMove(1);\n e.accepted = true;\n } else if (e.key === Qt.Key_Left) {\n panel.kbAdjust(-1);\n e.accepted = true;\n } else if (e.key === Qt.Key_Right) {\n panel.kbAdjust(1);\n e.accepted = true;\n } else if (e.key === Qt.Key_Return || e.key === Qt.Key_Enter || e.key === Qt.Key_Space) {\n panel.kbActivate();\n e.accepted = true;\n }\n }\n }\n\n /**\n * The dock's settings panel floats above the bar, so it needs its own\n * region or it draws without taking clicks. Unioned with the bar\n * itself: the gear that opened it stays clickable to close it, and the\n * chips stay live underneath.\n */\n Region {\n id: dockSettingsUnion\n readonly property real l: Math.min(dockRegion.x, dockPanelRegion.x)\n readonly property real t: Math.min(dockRegion.y, dockPanelRegion.y)\n x: l\n y: t\n width: Math.max(dockRegion.x + dockRegion.width, dockPanelRegion.x + dockPanelRegion.width) - l\n height: Math.max(dockRegion.y + dockRegion.height, dockPanelRegion.y + dockPanelRegion.height) - t\n }\n\n Region {\n id: dockPanelRegion\n x: dockPanel.x\n y: dockPanel.y\n width: dockPanel.width\n height: dockPanel.height\n }\n\n /**\n * The panel is a sibling of the bar, not a child, so it is NOT\n * translated when the bar slides away. That is deliberate and is what\n * `dockForcedOpen` above exists for: switching the dock off from\n * inside its own settings must not strand the user.\n *\n * While the panel is open the region is `dismissBase`: the panel and\n * the bar as one rect. It is a single rect rather than the two it\n * stands in for, because a bounding box is what `hovered` needs to\n * agree with \u2014 the pointer can cross the gap between the panel and the\n * bar on its way from one to the other without that reading as a\n * departure, which is what you want. The cost is dead space beside\n * the panel, and that is what the click floor exists to cover: it is\n * exactly the space where a click would be delivered to this window\n * and hit nothing at all.\n *\n * The rest of the mask, and what each state needs to keep reachable:\n *\n * - Suppressed or empty: nothing, so the screen is entirely free.\n * - Auto-hide on: the reveal strip alone while retracted, so the\n * pointer can always find the bar again; the strip unioned with\n * the pop band once it is up, so the pull-in cannot flicker.\n * - Auto-hide off: the bar can never retract, so no reveal strip is\n * needed at any point. Naming the pop band alone covers the bar\n * plus the space above it \u2014 it already contains the bar, whose\n * width it spans and whose bottom edge it stops at.\n */\n mask: dock.settingsOpen\n ? dockDismissRegion\n : (suppressed || dock.empty ? dockHiddenRegion\n : (Flags.dockAutoHide ? ((dock.revealSession || dock.hovered) ? dockRevealUnion : dockRevealRegion)\n : (dock.hovered || dock.previewOpen ? dockPopBand : dockRegion)))\n Region { id: dockHiddenRegion }\n\n /**\n * The region behind the panel: the block, and nothing grown around it.\n * It is the same rect `dismissBase` describes, and it is the whole of\n * what `hovered` is measured against while the panel is open.\n */\n Region {\n id: dockDismissRegion\n x: dockWin.dismissBase.x\n y: dockWin.dismissBase.y\n width: dockWin.dismissBase.width\n height: dockWin.dismissBase.height\n }\n\n /**\n * The thin strip along the bottom edge kept in the input mask while\n * the dock is retracted, so the pointer can always find it; hovering\n * slides the bar back up.\n *\n * FULL WIDTH, not a bottom-CENTRE strip the way the pill's top edge\n * is one. It is the only input surface that can raise a retracted\n * dock, so its width decides how much of the screen can summon one\n * at all: at uiScale 0.9 the centred 560px strip left 37% of the\n * bottom dead on each side, and whether the bar appeared depended\n * entirely on where the pointer happened to cross the edge. That is\n * the whole of \"sometimes the dock isn't showing\" \u2014 the bar was not\n * failing, it was simply never being asked for. A dock is a\n * bottom-edge affordance, and the bottom edge is where the pointer\n * goes to summon one; the pill keeps a narrow strip because a\n * top-CENTRE bar is looked up on purpose, by moving to the middle.\n */\n Region {\n id: dockRevealRegion\n readonly property real revealW: dockWin.width\n readonly property real revealH: 8 * dock.s\n x: 0\n y: dockWin.height - revealH\n width: revealW\n height: revealH\n }\n\n /**\n * Mask while the bar is up: the dock's own footprint, so the rest\n * of the screen clicks through to windows.\n */\n Region {\n id: dockRegion\n x: dock.x\n y: dock.y\n width: dock.width\n height: dock.height\n }\n\n /**\n * The area above the bar that has to stay live while the bar is up.\n *\n * This is the distance the pointer must travel before the dock will\n * let go, so it is not decoration \u2014 it IS the hide threshold, and it\n * was set for the tallest thing that can float above the bar (a\n * window preview, ~190px) and then applied unconditionally. With\n * nothing floating, that meant 190px of screen stayed hot and the\n * dock hung around long after the pointer had clearly left it.\n *\n * So the band is sized to what is actually there:\n *\n * - A preview is open: the full 190, and 100px past each end,\n * because the cursor genuinely walks up into it and clicks a\n * window row. That needs input, and the preview is wider than\n * the bar.\n * - Otherwise: just past the tallest chip tooltip (~44px, and\n * non-interactive, so this is about the dock not blinking out\n * from under a tooltip rather than about taking clicks). The\n * side margin is near zero for the same reason \u2014 a tooltip is\n * centred on a chip, so it can overhang the bar's end, but it\n * never needs to be clicked.\n *\n * `previewOpen` rather than \"is the pointer over a chip\", because\n * the deep band exists for the preview's benefit alone; claiming it\n * while merely hovering a chip would reinstate the long threshold\n * for the most common interaction there is.\n */\n Region {\n id: dockPopBand\n readonly property bool deep: dock.previewOpen\n readonly property real bandH: (deep ? 190 : 44) * dock.s\n readonly property real sideW: (deep ? 100 : 6) * dock.s\n x: Math.max(0, dock.x - sideW)\n y: Math.max(0, dock.y - bandH)\n width: dock.width + sideW * 2\n height: bandH + dock.height\n }\n\n /**\n * Mask while the bar is up with auto-hide ON, which is the only case\n * that needs the reveal strip: the bar retracts, so the strip is what\n * keeps the pointer able to find and re-reveal it.\n *\n * The union exists so the pointer stays covered for the whole\n * pull-in: the strip alone is 18px tall and the bar rises out of\n * below it, so a cursor waiting under the growing bar would fall out\n * of the mask, drop the hover, and re-trigger the reveal in a loop.\n * Adding the bar's own pop band covers the space it travels through.\n *\n * It used to be justified by a second reason \u2014 the strip was a\n * centred box narrower than the screen, so a cursor on its outer\n * edge could slip off mid-slide \u2014 and that reason is gone now the\n * strip spans the full edge. The union stays: the first reason was\n * never about the strip's shape.\n */\n Region {\n id: dockRevealUnion\n x: dockRevealRegion.x\n y: dockRevealRegion.y\n width: dockRevealRegion.width\n height: dockRevealRegion.height\n\n Region {\n x: dockPopBand.x\n y: dockPopBand.y\n width: dockPopBand.width\n height: dockPopBand.height\n }\n }\n\n DockBar {\n id: dock\n\n /**\n * Above the settings panel, which sits at z 200.\n *\n * This inverts the popover relationship, and deliberately. The\n * panel is anchored to the bar's TOP, so the two never overlap\n * \u2014 nothing the bar paints in its own rectangle can cover the\n * panel. What DOES overlap is what the bar floats UP out of\n * itself: the chip tooltips and the multi-window preview, both\n * anchored above their chip, which is to say inside the panel.\n *\n * As siblings those were unreachable whenever the panel was open:\n * hovering a chip to read its name showed a tooltip painted\n * behind an opaque panel, so it simply was not there. A z value\n * is per-branch and there is no \"escape to the window root\", so\n * the bar has to come above the panel as a whole to lift its own\n * decorations with it.\n *\n * The tooltips are the reason this is right rather than merely\n * convenient: the panel being open must not cost the user the\n * names of the apps they are pointing at. Input is unaffected \u2014\n * a tooltip is non-interactive by design, so it never claims a\n * click from a panel row underneath it.\n */\n z: 250\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.bottom: parent.bottom\n anchors.bottomMargin: dockWin.dockGap\n s: dockWin.s\n // Same height and corner as the pill: both are bar objects on the\n // same desktop, and each display mode resizes the pill, so\n // sourcing the dock from the pill keeps them matching for free.\n //\n // Read through `root`, not `pill` directly. They are sibling\n // PanelWindows, so `pill` \u2014 which is declared inside the overlay\n // window's own scope \u2014 is not visible from here and resolved to\n // undefined, leaving the dock on its fallback height and radius\n // (a ReferenceError on every reload) instead of matching. `root`\n // encloses both windows and is visible to each.\n matchHeight: root.pillBarHeight\n matchRadius: root.pillBarRadius\n suppressed: suppressed\n screenName: dockWin.modelData.name\n\n /**\n * Slide the bar below the screen edge while the dock is\n * retracted (monitor fullscreen, game mode, disabled, or\n * auto-hidden after the pointer leaves) and while it has\n * nothing to show \u2014 no pins, no running apps and no usage\n * history for a frequent-app shelf (`empty`). The translate\n * covers the bar plus its float gap, so nothing peeks back\n * above the edge while hidden.\n */\n transform: Translate {\n // Covers the dock plus its float gap, plus a small allowance so\n // antialiased edges and the drop shadow cannot leave a sliver.\n y: dock.hidden || dock.empty || suppressed\n ? dock.height + dockWin.dockGap + 4 * dockWin.s : 0\n Behavior on y {\n NumberAnimation {\n duration: Motion.morph\n easing.type: Motion.easeMorph\n easing.bezierCurve: Motion.morphCurve\n }\n }\n }\n }\n\n /**\n * The root's dock-settings signal, picked up here. The dock's\n * id is scoped to this window's delegate and invisible to the\n * root, so the root raises the signal instead of calling it,\n * and only this monitor's panel opens: the signal carries the\n * name of the monitor whose pill asked.\n */\n Connections {\n target: root\n function onDockSettingsRequested(mon) {\n if (mon === dockWin.modelData.name)\n dock.openSettings();\n }\n }\n\n /**\n * The dock's OWN settings panel, hosted here rather than inside\n * DockBar for one reason: it must survive the bar being translated\n * off the bottom edge, because the panel holds the \"Dock\" switch and\n * the bar holds the gear. Two things make that work.\n *\n * It is a SIBLING of the bar, and it anchors to the bar's layout\n * position \u2014 a Transform moves the painting, not `x`/`y`, so\n * anchoring here reads the untranslated position and the panel holds\n * still while the bar slides away.\n *\n * And the shell, not the dock, decides the panel's palette input and\n * its input-mask region, because the mask has to cover the panel\n * alone in `dockForcedOpen` \u2014 the bar is gone, so the union would be\n * wrong.\n *\n * Loaded, not instantiated, so the app list's desktop-entry scan is\n * not paid for while the panel is closed. Its size is left entirely\n * to the Loader's own implicit sizing, which follows the page's\n * `implicitWidth`/`implicitHeight`: binding `width` to `item.width`\n * looks equivalent and is not \u2014 the Loader resizes a loaded item to\n * its own width, so on the tick the item appears the width reads 0,\n * the Loader resizes the page to 0, and the two pin each other at\n * zero. That is the panel's own input-mask region, so a silent zero\n * there is a panel that draws and takes no clicks.\n */\n Loader {\n id: dockPanel\n active: dock.settingsOpen\n visible: dock.settingsOpen\n z: 200\n anchors.horizontalCenter: parent.horizontalCenter\n anchors.bottom: dock.top\n /* A POSITIVE bottom margin lifts the panel clear of the bar, as\n * it does for every other margin: the item's bottom sits that\n * many pixels above the anchor line. */\n anchors.bottomMargin: dock.panelGap\n\n sourceComponent: Component {\n DockSurface {\n s: dock.s\n pal: dock.dockPal\n open: true\n onRequestClose: dock.closeSettings()\n }\n }\n }\n\n /**\n * The other half of click-away: a click that lands on THIS window but\n * on neither the panel nor the bar.\n *\n * The region while the panel is open is one rect that encloses both,\n * which leaves dead space beside the panel and in the gap between\n * panel and bar. A click in any of it is delivered to this window\n * and hits nothing, so it deserves a direct answer rather than\n * waiting on a hover that may not come. Note what this floor is\n * standing in for: the panel's own dismissal is the bar's\n * `revealTimer`, and the pointer has to LEAVE the block for that to\n * fire, which a click never does on its own. This is what answers\n * the click, so the two are not redundant.\n *\n * z is BELOW the bar (which is 0) and far below the panel (200), so\n * this never sees a click meant for a chip or a row \u2014 it is a floor,\n * not a lid.\n */\n MouseArea {\n z: -1\n anchors.fill: parent\n visible: dock.settingsOpen\n onClicked: dock.closeSettings()\n }\n\n /**\n * The one hover feed for the whole dock window, and with it the\n * panel's dismissal: while the panel is open the mask is the block,\n * so `hovered` reads as \"over the panel or the bar\" and the bar's\n * `revealTimer` closes the panel once the pointer has left.\n *\n * It stays enabled while `suppressed`, which looks wrong and is not.\n * `suppressed` covers the dock being switched off, and that is\n * reachable from inside the open panel \u2014 the panel is a sibling of\n * the bar precisely so it survives the bar sliding away. Pause the\n * feed there and the one case that most needs a dismissal signal\n * loses it, with the flag frozen at whatever it last read. DockBar\n * clears the flags on the way in, so nothing is left latched.\n */\n HoverHandler {\n enabled: !suppressed || dock.settingsOpen\n onEnabledChanged: if (enabled) dock.hovered = hovered\n onHoveredChanged: if (enabled) dock.hovered = hovered\n }\n\n Connections {\n target: Flags\n function onDockAutoHideChanged() {\n if (!Flags.dockAutoHide) {\n dock.revealSession = false;\n dock.hovered = false;\n }\n }\n function onDockEnabledChanged() {\n if (!Flags.dockEnabled) {\n dock.revealSession = false;\n dock.hovered = false;\n }\n }\n }\n }\n }\n}\n",