diff --git a/bin/omarchy-branding-screensaver b/bin/omarchy-branding-screensaver index cf031a6117b2..4ca56c9a4b99 100755 --- a/bin/omarchy-branding-screensaver +++ b/bin/omarchy-branding-screensaver @@ -3,26 +3,79 @@ # omarchy:summary=Edit, set, or reset screensaver branding # omarchy:group=branding # omarchy:name=screensaver -# omarchy:args= -# omarchy:examples=omarchy branding screensaver image | omarchy branding screensaver text | omarchy branding screensaver reset +# omarchy:args= [path] +# omarchy:examples=omarchy branding screensaver images ~/Pictures/giants | omarchy branding screensaver folder ~/Pictures/ascii | omarchy branding screensaver image | omarchy branding screensaver text | omarchy branding screensaver reset set -euo pipefail +source omarchy-shell-config + +select_source() { + commit 'if type != "object" then error("shell config must be an object") else . end + | if $source == "" then del(.screensaver.source) + else .screensaver.source = $source end' --arg source "$1" +} + +# Single-file artwork only needs the config written when a collection would hide it. +clear_source() { + jq -e '.screensaver.source? // empty' "$CONFIG_FILE" &>/dev/null || return 0 + select_source "" +} + case "${1:-}" in +images) + directory=${2:-} + [[ -n $directory ]] || directory=$(omarchy-file-select --title "Pick screensaver image folder" --directory) + omarchy-notification-send "Preparing screensaver" "Converting the image folder to text artwork" || true + errors=$(mktemp) + trap 'rm -f -- "$errors"; cleanup_shell_config_tmp' EXIT + status=0 + collection=$(timeout 130s omarchy-screensaver-import "$directory" 2>"$errors") || status=$? + cat -- "$errors" >&2 + if ((status != 0)); then + # Name the importer's own reason, such as the image that failed. + reason=$(sed -n 's/^omarchy-screensaver-import: //p' "$errors" | tail -n 1) + ((status != 124)) || reason="the import took too long; selection unchanged" + # Notification bodies render markup, and filenames are untrusted text. + reason=${reason//'&'/'&'} + reason=${reason//'<'/'<'} + reason=${reason//'>'/'>'} + omarchy-notification-send "Screensaver import failed" "${reason:-The previous selection is unchanged}" || true + exit 1 + fi + select_source "$collection" + omarchy-launch-screensaver force >/dev/null 2>&1 + ;; +folder) + directory=${2:-} + [[ -n $directory ]] || directory=$(omarchy-file-select --title "Pick screensaver text folder" --directory) + directory=$(realpath -e -- "$directory") + [[ -d $directory ]] || fail "select a text directory" + validation=$(mktemp -d) + trap 'rm -rf -- "$validation"; cleanup_shell_config_tmp' EXIT + timeout 5s omarchy-screensaver-prepare "$directory" "$validation" + select_source "$directory" + omarchy-launch-screensaver force >/dev/null 2>&1 + ;; image) - image=$(omarchy-file-select --title "Pick PNG or SVG for screensaver" --extensions "png svg") + image=$(omarchy-file-select --title "Pick screensaver image" --extensions "png jpg jpeg webp svg") if omarchy-transcode-ascii "$image" ~/.config/omarchy/branding/screensaver.txt; then + clear_source omarchy-launch-screensaver force >/dev/null 2>&1 fi ;; text) - omarchy-launch-editor ~/.config/omarchy/branding/screensaver.txt >/dev/null 2>&1 && omarchy-launch-screensaver force >/dev/null 2>&1 + omarchy-launch-editor ~/.config/omarchy/branding/screensaver.txt >/dev/null 2>&1 + clear_source + omarchy-launch-screensaver force >/dev/null 2>&1 ;; reset) - cp "$OMARCHY_PATH/logo.txt" ~/.config/omarchy/branding/screensaver.txt && omarchy-launch-screensaver force >/dev/null 2>&1 + cp "$OMARCHY_PATH/logo.txt" ~/.config/omarchy/branding/screensaver.txt + clear_source + omarchy-launch-screensaver force >/dev/null 2>&1 ;; *) - echo "Usage: omarchy-branding-screensaver " >&2 + echo "Usage: omarchy-branding-screensaver [path]" >&2 exit 1 ;; esac diff --git a/bin/omarchy-screensaver b/bin/omarchy-screensaver index acd3868364a8..da29252ce89b 100755 --- a/bin/omarchy-screensaver +++ b/bin/omarchy-screensaver @@ -2,14 +2,56 @@ # omarchy:summary=Run the Omarchy screensaver using random effects from TTE. +artworks=("$HOME/.config/omarchy/branding/screensaver.txt") +playback_directory="" + +cleanup_artwork() { + [[ -z $playback_directory ]] || rm -rf -- "$playback_directory" +} +trap cleanup_artwork EXIT +trap 'exit 0' SIGINT SIGTERM SIGHUP SIGQUIT + +# No setting preserves the existing, live-editable single-file behavior. +source_path=$(jq -er '.screensaver.source | select(type == "string" and length > 0)' "$HOME/.config/omarchy/shell.json" 2>/dev/null) || source_path="" +if [[ -n $source_path ]]; then + if playback_directory=$(mktemp -d); then + if timeout 5s omarchy-screensaver-prepare "$source_path" "$playback_directory"; then + artworks=("$playback_directory"/*.txt) + fi + fi +fi +[[ -s ${artworks[0]} ]] || artworks=("$OMARCHY_PATH/logo.txt") +artwork_index=0 +effect_pid="" + screensaver_in_focus() { - hyprctl activewindow -j | jq -e '.class == "org.omarchy.screensaver"' >/dev/null 2>&1 + local window + # An unavailable compositor or unreadable reply is not a dismissal. A reply of + # {} means no window has focus, which is. + window=$(hyprctl activewindow -j 2>/dev/null) || return 0 + jq -e 'type == "object"' <<<"$window" &>/dev/null || return 0 + jq -e '.class == "org.omarchy.screensaver"' <<<"$window" &>/dev/null } exit_screensaver() { + trap "" SIGINT SIGTERM SIGHUP SIGQUIT hyprctl eval 'hl.config({ cursor = { invisible = false } })' &>/dev/null || hyprctl keyword cursor:invisible false &>/dev/null || true - pkill -x ttfx 2>/dev/null - pkill -f '[o]rg.omarchy.screensaver' 2>/dev/null + if [[ -n $effect_pid ]]; then + kill "$effect_pid" 2>/dev/null || true + for ((attempt = 0; attempt < 20; attempt++)); do + kill -0 "$effect_pid" 2>/dev/null || break + sleep 0.1 + done + if kill -0 "$effect_pid" 2>/dev/null; then kill -KILL "$effect_pid" 2>/dev/null || true; fi + wait "$effect_pid" 2>/dev/null || true + fi + # Close actual screensaver windows, never processes whose command lines merely + # contain the class name. Each window's renderer reaps its own effect child. + while IFS= read -r address; do + [[ $address =~ ^0x[[:xdigit:]]+$ ]] || continue + hyprctl dispatch "hl.dsp.window.close({ window = \"address:$address\" })" >/dev/null 2>&1 || + hyprctl dispatch closewindow "address:$address" >/dev/null 2>&1 || true + done < <(hyprctl clients -j 2>/dev/null | jq -r '.[] | select(.class == "org.omarchy.screensaver") | .address') exit 0 } @@ -20,8 +62,6 @@ printf '\033]11;rgb:00/00/00\007' # Set background color to black hyprctl eval 'hl.config({ cursor = { invisible = true } })' &>/dev/null || hyprctl keyword cursor:invisible true &>/dev/null -tty=$(tty 2>/dev/null) - # Terminals allocate the pty at the default 80x24 and only resize it once the # compositor has told the window how big it is. ttfx measures the terminal once, # at startup, so starting it before the resize lands sizes an 80x24 canvas and @@ -36,13 +76,30 @@ wait_for_terminal_resize() { wait_for_terminal_resize while true; do - ttfx -i ~/.config/omarchy/branding/screensaver.txt \ + # Artwork carrying colour sequences settles on its own colours after the + # effect (dynamic). Plain text keeps the effect's final gradient (ignore); + # dynamic would settle it on the terminal default instead. + color_handling=ignore + if grep -q -F $'\e[' -- "${artworks[artwork_index]}"; then + color_handling=dynamic + fi + ttfx -i "${artworks[artwork_index]}" \ + --existing-color-handling "$color_handling" \ --frame-rate 120 --canvas-width 0 --canvas-height 0 --reuse-canvas --anchor-canvas c --anchor-text c\ --random-effect --no-eol --no-restore-cursor & - while pgrep -t "${tty#/dev/}" -x ttfx >/dev/null; do + effect_pid=$! + + while kill -0 "$effect_pid" 2>/dev/null; do if read -n1 -t 1 || ! screensaver_in_focus; then exit_screensaver fi done + if ! wait "$effect_pid"; then + # A broken effect must neither busy-loop nor close the idle window. + read -n1 -t 1 && exit_screensaver + fi + effect_pid="" + screensaver_in_focus || exit_screensaver + artwork_index=$(( (artwork_index + 1) % ${#artworks[@]} )) done diff --git a/bin/omarchy-screensaver-import b/bin/omarchy-screensaver-import new file mode 100755 index 000000000000..cdce1f6a46cf --- /dev/null +++ b/bin/omarchy-screensaver-import @@ -0,0 +1,161 @@ +#!/bin/bash + +# omarchy:summary=Convert a local raster image folder into a screensaver text collection +# omarchy:hidden=true +# omarchy:args= [--mode ] + +python3 - "$@" <<'PY' +import errno +import json +import os +from pathlib import Path +import re +import shutil +import signal +import stat +import subprocess +import sys +import tempfile +import time + + +def interrupted(number, _frame): + raise SystemExit(128 + number) + + +for number in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): + signal.signal(number, interrupted) + + +def convert(command, environment, deadline, name): + remaining = deadline - time.monotonic() + child = subprocess.Popen(command, env=environment, stdout=subprocess.DEVNULL, + start_new_session=True) + try: + if child.wait(timeout=max(0.01, min(15, remaining))) != 0: + raise ValueError(f"could not convert {name!r}; selection unchanged") + except subprocess.TimeoutExpired: + # Blame the image only when it had its full per-image allowance. + if remaining < 15: + raise ValueError("import exceeds batch resource limit") from None + raise ValueError(f"{name!r} took too long to convert; selection unchanged") from None + finally: + # Reap only this converter's process group, including ImageMagick on timeout. + if child.poll() is None: + os.killpg(child.pid, signal.SIGKILL) + child.wait() + + +def main(): + arguments = sys.argv[1:] + mode = 'color' + if '--mode' in arguments: + position = arguments.index('--mode') + mode = arguments[position + 1] if position + 1 < len(arguments) else '' + arguments = arguments[:position] + arguments[position + 2:] + if len(arguments) != 1 or mode not in ('color', 'braille', 'block'): + raise ValueError("expected an image directory and optionally --mode color|braille|block") + source = Path(arguments[0]).expanduser().resolve(strict=True) + root = os.open(source, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + base = Path.home() / '.local/share/omarchy/screensavers' + base.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix='import-', dir=base)) + try: + names = [] + with os.scandir(root) as entries: + for index, entry in enumerate(entries): + if index >= 4096: + raise ValueError("folder exceeds 4096 entries") + # Links, folders and special files are skipped below, so they do not count. + if (not entry.name.startswith('.') and Path(entry.name).suffix.lower() in ('.png', '.jpg', '.jpeg', '.webp') + and entry.is_file(follow_symlinks=False)): + names.append(entry.name) + # Numeric filenames such as 1, 2, ... 18 keep their expected order. + names.sort(key=lambda name: [((0, int(p)) if p.isdigit() else (1, os.fsencode(p))) + for p in re.split(r'([0-9]+)', name)]) + if not names or len(names) > 128: + raise ValueError("choose a folder with 1–128 PNG, JPEG or WebP images") + deadline = time.monotonic() + 120 + total = 0 + records = [] + with tempfile.TemporaryDirectory(prefix='omarchy-image-import-') as temporary: + scratch = Path(temporary) + # Keep the native converter, but restrict this batch to raster coders and + # bounded resources. No delegates, SVG external references or URL coders. + # WebP decodes every frame before the converter keeps the first, so the + # list length bounds animation frames (one more than the 128 allowed). + (scratch / 'policy.xml').write_text(''' + + + + + + + + + + + + +''') + environment = dict(os.environ, MAGICK_CONFIGURE_PATH=str(scratch), + MAGICK_TEMPORARY_PATH=str(scratch)) + for name in names: + # The scan kept only regular files, so anything else here means the + # folder changed during import. Fail rather than select a partial set. + try: + fd = os.open(name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, dir_fd=root) + except OSError as error: + if error.errno in (errno.ENOENT, errno.ELOOP, errno.ENOTDIR): + raise ValueError(f"{name!r} changed during import; selection unchanged") from None + raise ValueError(f"cannot read {name!r} ({os.strerror(error.errno)}); selection unchanged") from None + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode): + os.close(fd) + raise ValueError(f"{name!r} changed during import; selection unchanged") + with os.fdopen(fd, 'rb') as stream: + if not 0 < before.st_size <= 20 * 1024 * 1024: + raise ValueError(f"{name!r} exceeds 20 MiB; selection unchanged") + data = stream.read(20 * 1024 * 1024 + 1) + after = os.fstat(stream.fileno()) + if len(data) != before.st_size or (before.st_mtime_ns, before.st_ctime_ns) != (after.st_mtime_ns, after.st_ctime_ns): + raise ValueError(f"{name!r} changed during read") + total += len(data) + if total > 256 * 1024 * 1024 or time.monotonic() > deadline: + raise ValueError("import exceeds batch resource limit") + if data.startswith(b'\x89PNG\r\n\x1a\n'): + suffix = '.png' + elif data.startswith(b'\xff\xd8\xff'): + suffix = '.jpg' + elif data.startswith(b'RIFF') and data[8:12] == b'WEBP': + suffix = '.webp' + else: + raise ValueError(f"{name!r} is not a PNG, JPEG or WebP image; selection unchanged") + snapshot = scratch / ('input' + suffix) + snapshot.write_bytes(data) + target = output / f'{len(records):03d}.txt' + convert(['omarchy-transcode-ascii', str(snapshot), str(target), '--mode', mode], environment, deadline, name) + snapshot.unlink() + records.append({'source': name, 'artwork': target.name}) + print(f'Converted {len(records)}/{len(names)}', file=sys.stderr) + # Apply exactly the same text validation used at playback startup. + with tempfile.TemporaryDirectory(dir=scratch) as validation: + subprocess.run(['omarchy-screensaver-prepare', str(output), validation], + check=True, timeout=5, stdout=subprocess.DEVNULL) + if len(list(Path(validation).glob('*.txt'))) != len(records): + raise ValueError("converted artwork failed text validation") + (output / 'manifest.json').write_text(json.dumps({'source': str(source), 'mode': mode, 'images': records}, indent=2)) + print(output) + except BaseException: + shutil.rmtree(output) + raise + finally: + os.close(root) + + +try: + main() +except (OSError, ValueError, subprocess.SubprocessError) as error: + print(f'omarchy-screensaver-import: {error}', file=sys.stderr) + sys.exit(1) +PY diff --git a/bin/omarchy-screensaver-prepare b/bin/omarchy-screensaver-prepare new file mode 100755 index 000000000000..b12932d905bd --- /dev/null +++ b/bin/omarchy-screensaver-prepare @@ -0,0 +1,114 @@ +#!/bin/bash + +# omarchy:summary=Copy a text screensaver source into a private playback directory +# omarchy:hidden=true +# omarchy:args= + +python3 - "$@" <<'PY' +import os +import re +import stat +import sys +import unicodedata + +MAX_ENTRIES = 4096 +MAX_ARTWORKS = 128 +MAX_BYTES = 1048576 +# Colour is allowed, nothing else: SGR sequences (ESC [ params m) whose +# parameters are the attribute and colour forms ttfx accepts. Anything ttfx +# would refuse or overflow on (values above 255, wrong 38/48 arity) rejects +# the file here instead of failing in the renderer. +# Validate the bounded grammar in the regex engine rather than parsing every +# colour escape in Python. A full collection can contain millions of escapes. +VALUE = r"(?:[0-9]{1,2}|[01][0-9]{2}|2[0-4][0-9]|25[0-5])" +ATTRIBUTE = rf"(?!(?:0?38|0?48)(?:;|m)){VALUE}" +COLOUR = rf"(?:0?38|0?48);(?:5;{VALUE}|2;{VALUE};{VALUE};{VALUE})" +PARAMETER = rf"(?:{COLOUR}|{ATTRIBUTE})" +SGR = re.compile(rf"\x1b\[(?=[0-9;]{{0,64}}m)(?!(?:[0-9]+;){{16}})" + rf"(?:{PARAMETER}(?:;{PARAMETER})*)?m") + + +def read_artwork(path, directory=None): + # Open first, then check the same descriptor we read. A swapped symlink is + # refused, and a FIFO cannot block between enumeration and validation. + if path is None: + fd = os.dup(directory) + else: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + with os.fdopen(fd, "rb") as source: + before = os.fstat(source.fileno()) + if not stat.S_ISREG(before.st_mode) or not 0 < before.st_size <= MAX_BYTES: + return None + data = source.read(MAX_BYTES + 1) + after = os.fstat(source.fileno()) + if len(data) > MAX_BYTES or (before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_size, after.st_mtime_ns, after.st_ctime_ns): + return None + text = data.decode("utf-8").replace("\r\n", "\n") + # Artwork is data, not terminal commands (including OSC clipboard sequences). + # Colour sequences are checked and removed first; the size limits apply to + # what is actually visible, and any other control or format character rejects + # the file. The cheap line checks run before the per-character scan so a + # large file cannot stall preparation. + visible = SGR.sub("", text) + lines = visible.splitlines() + if not visible.strip() or len(lines) > 128 or any(len(line.expandtabs(4)) > 512 for line in lines): + return None + if any(unicodedata.category(char).startswith("C") and char not in "\n\t" for char in visible): + return None + return text.encode("utf-8") + + +def prepare(source, destination): + if source.startswith("~/"): + source = os.path.join(os.environ["HOME"], source[2:]) + if not os.path.isabs(source): + raise ValueError("source must be an absolute path or start with ~/") + + # Resolve the explicitly selected root once. Children are opened relative to + # its descriptor, never by re-traversing a directory that can be replaced. + source = os.path.realpath(source) + root = os.open(source, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW) + try: + if stat.S_ISDIR(os.fstat(root).st_mode): + names = [] + with os.scandir(root) as entries: + for index, entry in enumerate(entries): + if index >= MAX_ENTRIES: + raise ValueError("collection exceeds 4096 directory entries") + if entry.name.lower().endswith(".txt") and not entry.name.startswith("."): + names.append(entry.name) + candidates = [(name, root) for name in sorted(names, key=os.fsencode)] + else: + candidates = [(None, root)] + + count = 0 + for path, directory in candidates: + try: + data = read_artwork(path, directory) + except (OSError, UnicodeError): + continue + if data is None: + continue + # The caller owns this freshly created private directory. Fixed names + # keep source filenames out of both shell parsing and the renderer. + output = os.path.join(destination, f"{count:03d}.txt") + fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "wb") as target: + target.write(data) + count += 1 + if count == MAX_ARTWORKS: + break + if not count: + raise ValueError("source contains no usable text artwork") + finally: + os.close(root) + + +try: + if len(sys.argv) != 3: + raise ValueError("expected a source and private playback directory") + prepare(sys.argv[1], sys.argv[2]) +except (OSError, ValueError) as error: + print(f"omarchy-screensaver-prepare: {error}", file=sys.stderr) + sys.exit(1) +PY diff --git a/bin/omarchy-shell-config b/bin/omarchy-shell-config index 5cf0f639693c..36eb28a91360 100755 --- a/bin/omarchy-shell-config +++ b/bin/omarchy-shell-config @@ -53,10 +53,13 @@ trap cleanup_shell_config_tmp EXIT commit() { local program="$1" shift - mkdir -p "$(dirname "$CONFIG_FILE")" - _SHELL_CONFIG_TMP=$(mktemp) + local target + target=$(realpath -m -- "$CONFIG_FILE") + mkdir -p "$(dirname "$target")" + _SHELL_CONFIG_TMP=$(mktemp "$(dirname "$target")/.shell-config.XXXXXX") jq -S -e "$@" "$program" "$(source_file)" >"$_SHELL_CONFIG_TMP" || fail "could not update shell config" - mv "$_SHELL_CONFIG_TMP" "$CONFIG_FILE" + if [[ -f $target ]]; then chmod --reference="$target" "$_SHELL_CONFIG_TMP"; fi + mv -- "$_SHELL_CONFIG_TMP" "$target" _SHELL_CONFIG_TMP="" refresh_shell_config } diff --git a/bin/omarchy-transcode-ascii b/bin/omarchy-transcode-ascii index 0ce19acfc3ed..0d0c70c6ee4d 100755 --- a/bin/omarchy-transcode-ascii +++ b/bin/omarchy-transcode-ascii @@ -3,21 +3,23 @@ # omarchy:summary=Transcode an image into ASCII/Unicode art text # omarchy:group=transcode # omarchy:name=ascii -# omarchy:args= [--width ] [--height ] [--mode ] [--threshold ] [--invert] +# omarchy:args= [--width ] [--height ] [--mode ] [--threshold ] [--invert] # omarchy:examples=omarchy transcode ascii ~/logo.svg /tmp/logo.txt | omarchy transcode ascii ~/logo.png ~/.config/omarchy/branding/screensaver.txt --width 80 set -o pipefail usage() { cat <<'EOF' -Usage: omarchy-transcode-ascii [options] +Usage: omarchy-transcode-ascii [options] Transcodes an image into ASCII/Unicode art text. Options: -w, --width Maximum output width in terminal columns (default: 80) -H, --height Maximum output height in terminal rows (default: 26) - -m, --mode Output style (default: braille) + -m, --mode + Output style (default: braille); color keeps the + image's colours as truecolour quadrant blocks -t, --threshold Pixel threshold from 0-100 (default: 50) --invert Treat light pixels as the logo instead of dark pixels --no-trim Preserve surrounding whitespace/background @@ -91,8 +93,8 @@ if [[ -z $image_path || -z $output_path ]]; then exit 1 fi -if [[ $mode != "braille" && $mode != "block" ]]; then - echo "Invalid mode: $mode (expected braille or block)" >&2 +if [[ $mode != "braille" && $mode != "block" && $mode != "color" ]]; then + echo "Invalid mode: $mode (expected braille, block or color)" >&2 exit 1 fi @@ -101,7 +103,7 @@ if [[ ! -f $image_path ]]; then exit 1 fi -if [[ $mode == "braille" ]]; then +if [[ $mode == "braille" || $mode == "color" ]]; then pixel_width=$((width * 2)) pixel_height=$((height * 4)) else @@ -109,7 +111,105 @@ else pixel_height=$((height * 2)) fi -alpha_range=$(magick -background none "$image_path" -alpha extract -format '%[fx:minima] %[fx:maxima]' info: 2>/dev/null) || { +# Bound large photos before trimming or thresholding, so a phone-camera image +# is never held at full size twice. JPEG decodes directly at a reduced scale. +# Point sampling to a fixed box is cheap and leaves room for trim to find a +# small logo on a large canvas. +prescale=2048 +input_args=(-define "jpeg:size=${prescale}x${prescale}" "$image_path") +shrink_args=(-sample "${prescale}x${prescale}>") + +if [[ $mode == "color" ]]; then + # Fit inside the same 2x4-per-cell box as braille, then halve the height so + # every cell gets a 2x2 colour sample. A Python pass picks, per cell, the + # quadrant glyph and the two colours that best split the sample. + # First frame only: an animated WebP would otherwise write several rasters. + color_args=(-limit memory 256MiB -limit map 512MiB -background black "${input_args[@]}" -auto-orient -delete 1--1 + "${shrink_args[@]}" -alpha remove -alpha off -colorspace sRGB) + if [[ $trim == "true" ]]; then + color_args+=(-bordercolor black -border 1 -trim +repage) + fi + tmp_output=$(mktemp) + tmp_raster=$(mktemp) + trap 'rm -f "$tmp_output" "$tmp_raster"' EXIT + color_args+=(-filter Lanczos -resize "${pixel_width}x${pixel_height}" -resize '100%x50%!' -depth 8 "ppm:$tmp_raster") + if ! magick "${color_args[@]}" || ! python3 - "$tmp_raster" <<'PY' >"$tmp_output"; then +import sys + +QUADRANTS = {1: "▘", 2: "▝", 3: "▀", 4: "▖", 5: "▌", 6: "▞", 7: "▛", 8: "▗", 9: "▚", 10: "▐", + 11: "▜", 12: "▄", 13: "▙", 14: "▟", 15: "█"} +with open(sys.argv[1], "rb") as raster: + data = raster.read(64 * 1024 * 1024) +fields, pos = [], 0 +while len(fields) < 4: + while data[pos:pos + 1].isspace(): + pos += 1 + if data[pos:pos + 1] == b"#": + pos = data.index(b"\n", pos) + 1 + continue + start = pos + while data[pos:pos + 1] and not data[pos:pos + 1].isspace(): + pos += 1 + fields.append(data[start:pos]) +if fields[0] != b"P6" or fields[3] != b"255": + sys.exit("unexpected raster format") +width, height = int(fields[1]), int(fields[2]) +pixels = data[pos + 1:] +# Playback allows 512 columns by 128 rows, so two samples per cell each way. +if not (0 < width <= 1024 and 0 < height <= 256) or len(pixels) != width * height * 3: + sys.exit("unexpected raster size") + + +def mean(colors): + return tuple(sum(c[i] for c in colors) // len(colors) for i in range(3)) + + +def error(colors, center): + return sum((c[i] - center[i]) ** 2 for c in colors for i in range(3)) + + +def px(x, y): + # Repeat the edge sample when a fitted raster has an incomplete 2x2 cell. + i = (min(y, height - 1) * width + min(x, width - 1)) * 3 + return pixels[i], pixels[i + 1], pixels[i + 2] + + +for cy in range((height + 1) // 2): + line, current = [], None + for cx in range((width + 1) // 2): + samples = [px(cx * 2, cy * 2), px(cx * 2 + 1, cy * 2), px(cx * 2, cy * 2 + 1), px(cx * 2 + 1, cy * 2 + 1)] + whole = mean(samples) + best = (error(samples, whole), 15, whole, whole) + if best[0]: + for mask in range(1, 15): + on = [samples[i] for i in range(4) if mask & (1 << i)] + off = [samples[i] for i in range(4) if not mask & (1 << i)] + fg, bg = mean(on), mean(off) + err = error(on, fg) + error(off, bg) + if err < best[0]: + best = (err, mask, fg, bg) + _, mask, fg, bg = best + if (fg, bg) != current: + line.append("\x1b[38;2;%d;%d;%d;48;2;%d;%d;%dm" % (fg + bg)) + current = (fg, bg) + line.append(QUADRANTS[mask]) + line.append("\x1b[0m") + print("".join(line)) +PY + echo "Unable to convert image: $image_path" >&2 + exit 1 + fi + if [[ ! -s $tmp_output ]]; then + echo "No image pixels found in: $image_path" >&2 + exit 1 + fi + mkdir -p "$(dirname "$output_path")" + cp "$tmp_output" "$output_path" + echo "Wrote colour block art to $output_path" + exit 0 +fi + +alpha_range=$(magick -background none "${input_args[@]}" -delete 1--1 "${shrink_args[@]}" -alpha extract -format '%[fx:minima] %[fx:maxima]' info: 2>/dev/null) || { echo "Unable to read logo image: $image_path" >&2 exit 1 } @@ -120,7 +220,7 @@ if awk -v min="$alpha_min" -v max="$alpha_max" 'BEGIN { exit !(min < 0.999 && ma use_alpha=true fi -magick_args=(-background none "$image_path" -auto-orient) +magick_args=(-background none "${input_args[@]}" -auto-orient -delete 1--1 "${shrink_args[@]}") if [[ $use_alpha == "true" ]]; then magick_args+=(-alpha extract -alpha off) diff --git a/default/omarchy/omarchy-menu.jsonc b/default/omarchy/omarchy-menu.jsonc index 7583d8d8ce95..b0c02fe05d22 100644 --- a/default/omarchy/omarchy-menu.jsonc +++ b/default/omarchy/omarchy-menu.jsonc @@ -120,6 +120,8 @@ "style.about.default": {"icon":"","label":"Restore Default","action":"omarchy-branding-about reset"}, "style.screensaver.text": {"icon":"","label":"Edit Text","action":"omarchy-branding-screensaver text"}, "style.screensaver.image": {"icon":"","label":"Set From Image","action":"omarchy-branding-screensaver image"}, + "style.screensaver.images": {"icon":"","label":"Set Image Folder","action":"omarchy-branding-screensaver images"}, + "style.screensaver.folder": {"icon":"","label":"Set Text Folder","action":"omarchy-branding-screensaver folder"}, "style.screensaver.default": {"icon":"","label":"Restore Default","action":"omarchy-branding-screensaver reset"}, // Setup diff --git a/manual/13-toggles-idle-screensaver.md b/manual/13-toggles-idle-screensaver.md index 2effdac1e690..0ca1d19acb14 100644 --- a/manual/13-toggles-idle-screensaver.md +++ b/manual/13-toggles-idle-screensaver.md @@ -92,7 +92,7 @@ You can start it on demand from _System > Screensaver_ (`Super + Esc`), which fo `omarchy toggle screensaver` is what turns the idle one off, if you'd rather go straight from working to locked. It needs a terminal it knows how to configure — Alacritty, Foot, Ghostty, or Kitty — and will tell you so if your default terminal is something else. -The logo it draws is yours to change, under _Style > Screensaver_. Upload a png or svg and Omarchy converts it to ASCII. See [branding](41-branding.md). +The logo it draws is yours to change, under _Style > Screensaver_. Pick a PNG, JPEG, WebP or SVG image, or a folder of images, and Omarchy converts it to text art. See [branding](41-branding.md). ### The lock screen diff --git a/manual/41-branding.md b/manual/41-branding.md index cdbe828db919..de98b53b744e 100644 --- a/manual/41-branding.md +++ b/manual/41-branding.md @@ -16,19 +16,50 @@ Then apply the setup with `omarchy plymouth set '#1d2021' '#ebdbb2' logo.png`, w ### Screensaver -You can change the logo used for the screensaver under _Style > Screensaver_. It's an ASCII logo, so you can edit the text directly, but you can also hand it a png or svg image, and we'll convert that to ASCII. It looks pretty cool. +You can change the logo used for the screensaver under _Style > Screensaver_. It's an ASCII logo, so you can edit the text directly, but you can also hand it a PNG, JPEG, WebP or SVG image, and we'll convert that to ASCII. It looks pretty cool. ![branding-screensaver](images/branding-screensaver.webp) -There are three entries in that menu: +The screensaver menu offers these choices: - **Edit Text** opens `~/.config/omarchy/branding/screensaver.txt` in your editor. Type or paste whatever you like — ASCII art, your name, a rude word. Save and quit, and the screensaver fires up immediately so you can see it. -- **Set From Image** opens a file picker for a png or svg, converts it to ASCII, and shows you the result. Logos with a clear silhouette work far better than photos. -- **Restore Default** puts the Omarchy logo back. +- **Set From Image** opens a file picker for PNG, JPEG, WebP or SVG, converts it to ASCII, and shows you the result. Logos with a clear silhouette work far better than photos. +- **Set Image Folder** converts a folder of PNG, JPEG or WebP images using the same converter, then plays the resulting text collection. +- **Set Text Folder** selects an existing folder of ASCII or braille `.txt` artworks. +- **Restore Default** puts the Omarchy logo back and clears any collection selection. + +**Set From Image** and **Edit Text** also clear the collection selection after conversion or editor launch succeeds. Canceling the picker or a failed conversion leaves the selection unchanged. + +#### Text collections + +Use **Set Image Folder** to choose a folder, or run: + +```bash +omarchy branding screensaver images ~/Pictures/giants +omarchy branding screensaver folder ~/Pictures/screensaver-art +``` + +Image folders are imported once into `~/.local/share/omarchy/screensavers/import-*`. Files are ordered numerically within their names (`1`, `2`, …, `18`); the generated text collection preserves that order. Each image is converted in colour by default (truecolour quadrant blocks at the converter's 80×26 maximum size); `omarchy-screensaver-import ~/Pictures/giants --mode braille` creates the monochrome style and prints the new folder without selecting it; choose that folder with **Set Text Folder** or set it as `screensaver.source` below. Source images are unchanged. Run the import again to include later changes; conversion does not run during idle startup. Prior imports are retained so an existing selection is never deleted; you may remove unused import folders yourself. + +Batch import accepts up to 128 visible PNG, JPEG or WebP images, with a 20 MiB limit per image. It skips hidden files, subfolders, symlinks and special files. Animated WebP images use their first frame and may have up to 128 frames. JPEG photos are decoded at reduced size, so phone-camera images import. Very large PNG or WebP images, roughly 20 to 60 megapixels depending on their colour type, can exceed the converter's memory limit. An unsupported or unconvertible image aborts the import, the notification names it, and the previous selection is preserved. SVG remains available through **Set From Image**. + +To configure a text source directly, add a `screensaver` block to `~/.config/omarchy/shell.json` alongside `idle`: + +```json +"screensaver": { + "source": "~/Pictures/screensaver-art" +} +``` + +The source can be an absolute path or a path starting with `~/`, pointing to either one text file or a directory of `.txt` files. A directory plays in filename order, advancing after each animation finishes and wrapping at the end. Each monitor runs its own animations, so changes are not synchronized between monitors. The existing `idle.screensaver` setting still controls when the screensaver starts. + +Collections contain UTF-8 text, including braille and block characters. Convert images with `omarchy transcode ascii` first; `--mode color` keeps their colours. Colour travels as SGR sequences (attributes, 256-colour and truecolour forms with values up to 255) and is the only terminal control allowed: files containing any other escape sequence are skipped, as are empty, invalid, or oversized files. Plain text artwork keeps the effect's own final colours; artwork with colour settles on its colours. Each file may be at most 1 MiB, 128 lines, and 512 visible characters per line after tab expansion. Up to 128 artworks are loaded from a directory with at most 4096 entries. Hidden files, nested directories, symbolic-link entries, and special files are not played. The selected source itself may be a symbolic link. + +The collection is copied for playback when the screensaver starts; edits appear the next time it opens. Omarchy never modifies the source. An unavailable or unusable source falls back to your existing screensaver logo. Remove `screensaver.source` to return to the live-editable logo, or choose **Set From Image**, **Edit Text**, or **Restore Default**. These menu actions clear the selection without deleting the collection. ### About screen -The same three options are under _Style > About_ for the _About_ screen you get from the Omarchy menu, and they work identically — the file is `~/.config/omarchy/branding/about.txt`, and the About window pops up after each change. The About art is converted to a smaller size than the screensaver's, since it has to fit in a window rather than fill your display. +**Edit Text**, **Set From Image**, and **Restore Default** are also under _Style > About_ for the _About_ screen you get from the Omarchy menu, and they work identically — the file is `~/.config/omarchy/branding/about.txt`, and the About window pops up after each change. The About art is converted to a smaller size than the screensaver's, since it has to fit in a window rather than fill your display. While the window is open a glint of green leans across the art every few seconds and then leaves it still again. Your own art gets it too, as long as every character in it is one column wide — anything _Set From Image_ produces is. Art built from emoji or double-width characters stays still instead, and so does the screen if you keep a fastfetch config of your own: a still logo in those cases is the animation keeping out of the way rather than failing, since sliding a glint across them would land the rest of the line in the wrong place. @@ -42,7 +73,7 @@ Both of the _Set From Image_ options are just calling `omarchy transcode ascii`, omarchy transcode ascii ~/logo.svg ~/.config/omarchy/branding/screensaver.txt --width 100 ``` -It takes `--width` and `--height` in terminal columns and rows, a `--mode` of either `braille` (the default, and much finer) or `block`, a `--threshold` percentage for deciding which pixels count as part of the logo, and `--invert` for when your logo is light on a dark background. If a conversion comes out as a blob, the threshold is usually the knob to turn. +It takes `--width` and `--height` in terminal columns and rows, a `--mode` of `braille` (the default, and much finer), `block`, or `color` (truecolour quadrant blocks that keep the image's colours), a `--threshold` percentage for deciding which pixels count as part of the logo, and `--invert` for when your logo is light on a dark background. If a conversion comes out as a blob, the threshold is usually the knob to turn. ### Words instead of a logo diff --git a/test/acceptance.d/screensaver-test.sh b/test/acceptance.d/screensaver-test.sh new file mode 100644 index 000000000000..174cfa27ed11 --- /dev/null +++ b/test/acceptance.d/screensaver-test.sh @@ -0,0 +1,147 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +# Play a text collection in a live screensaver window, then dismiss it twice: +# once by moving focus to an empty workspace, once with a key. The renderer +# runs with a throwaway HOME, so the session's own shell.json and branding are +# never read or written. +# +# The class is passed to jq through the environment, never as an argument: +# the launcher treats any process whose command line contains it as a running +# screensaver. +export SCREENSAVER_CLASS="org.omarchy.screensaver" + +workdir=$(mktemp -d) +start_workspace=$(hyprctl -j activeworkspace | jq -r '.id') + +focus_workspace() { + hyprctl dispatch "hl.dsp.focus({ workspace = \"$1\" })" >/dev/null 2>&1 || hyprctl dispatch workspace "$1" >/dev/null +} + +screensaver_addresses() { + hyprctl -j clients | jq -r '.[] | select(.class == env.SCREENSAVER_CLASS) | .address' +} + +screensaver_present() { + [[ -n $(screensaver_addresses) ]] +} + +screensaver_absent() { + ! screensaver_present +} + +screensaver_focused() { + hyprctl -j activewindow | jq -e '.class == env.SCREENSAVER_CLASS' +} + +effect_running() { + pgrep -x ttfx +} + +effect_stopped() { + ! effect_running +} + +effect_args_contain() { + pgrep -a -x ttfx | grep -F -- "$1" +} + +colour_effect_pid() { + pgrep -a -x ttfx | awk '/--existing-color-handling dynamic/ { print $1; exit }' +} + +# Count screen pixels within 3% of the artwork colour while one colour effect +# runs for the whole capture. Wait briefly while the plain artwork plays. +colour_on_screen() { + local pid count + pid=$(colour_effect_pid) + if [[ -z $pid ]]; then + sleep 0.05 + return 1 + fi + timeout 10 grim "$workdir/colour.png" 2>/dev/null || return 1 + count=$(magick "$workdir/colour.png" -alpha off -fuzz 3% -fill black +opaque "$colour" \ + -fill white -opaque "$colour" -format '%[fx:round(mean*w*h)]' info:) || return 1 + [[ $(colour_effect_pid) == "$pid" ]] && ((count >= 2000)) +} + +cleanup() { + local address + while read -r address; do + [[ $address =~ ^0x[[:xdigit:]]+$ ]] || continue + hyprctl dispatch "hl.dsp.window.close({ window = \"address:$address\" })" >/dev/null 2>&1 || + hyprctl dispatch closewindow "address:$address" >/dev/null 2>&1 || true + done < <(screensaver_addresses 2>/dev/null) + [[ -z $start_workspace ]] || focus_workspace "$start_workspace" || true + rm -rf -- "$workdir" +} +trap cleanup EXIT + +if pgrep -x ttfx >/dev/null || screensaver_present; then + fail "no screensaver is already running before the test" +fi + +home="$workdir/home" +collection="$workdir/collection" +playback="$workdir/playback" +mkdir -p "$home/.config/omarchy/branding" "$collection" "$playback" +printf 'FALLBACK\n' >"$home/.config/omarchy/branding/screensaver.txt" +printf 'OMARCHY ACCEPTANCE PLAIN\n' >"$collection/01-plain.txt" +# Solid blocks in a colour no effect palette uses, so the screen can be checked +# for the artwork's own colour once an effect settles. +colour="rgb(13,247,61)" +block=$(printf '█%.0s' {1..24}) +printf '\e[38;2;13;247;61m%s\n%s\n%s\e[0m\n' "$block" "$block" "$block" >"$collection/02-colour.txt" +jq -n --arg source "$collection" '{screensaver: {source: $source}}' >"$home/.config/omarchy/shell.json" + +launch_screensaver() { + local renderer=(env HOME="$home" TMPDIR="$playback" OMARCHY_PATH="$OMARCHY_PATH" PATH="$OMARCHY_PATH/bin:$PATH" + "$OMARCHY_PATH/bin/omarchy-screensaver") + local command line + + case $(xdg-terminal-exec --print-id) in + *Alacritty*) command=(alacritty --class="$SCREENSAVER_CLASS" --config-file "$OMARCHY_PATH/default/alacritty/screensaver.toml" -e "${renderer[@]}") ;; + *ghostty*) command=(ghostty --class="$SCREENSAVER_CLASS" --config-file="$OMARCHY_PATH/default/ghostty/screensaver" --font-size=18 -e "${renderer[@]}") ;; + *foot*) command=(foot --app-id="$SCREENSAVER_CLASS" --config="$OMARCHY_PATH/default/foot/screensaver.ini" -e "${renderer[@]}") ;; + *kitty*) command=(kitty --class="$SCREENSAVER_CLASS" --override font_size=18 --override window_padding_width=0 -e "${renderer[@]}") ;; + *) fail "default terminal is one the screensaver supports" "$(xdg-terminal-exec --print-id)" ;; + esac + + printf -v line '%q ' "${command[@]}" + hyprctl dispatch "hl.dsp.exec_cmd([[$line]])" >/dev/null 2>&1 || hyprctl dispatch exec -- bash -lc "$line" >/dev/null +} + +launch_screensaver +wait_until "screensaver window opens" 15 screensaver_present +wait_until "screensaver window takes focus" 10 screensaver_focused +wait_until "screensaver window is fullscreen" 10 bash -c 'hyprctl -j activewindow | jq -e ".fullscreen != 0 and .fullscreen != false"' +wait_until "screensaver plays plain artwork with the effect's own colours" 15 effect_args_contain "--existing-color-handling ignore" +screenshot "success-screensaver-plain" +wait_until "screensaver advances to colour artwork that keeps its colours" 120 effect_args_contain "--existing-color-handling dynamic" +# The settled colour shows only between effects, so poll without sleeping. +deadline=$((SECONDS + 120)) +until colour_on_screen; do + ((SECONDS < deadline)) || fail "colour artwork appears on screen in its own colour" "timed out after 120s" +done +pass "colour artwork appears on screen in its own colour" +screenshot "success-screensaver-colour" + +# Hyprland reports {} as the active window on an empty workspace. +focus_workspace empty +wait_until "focus on an empty workspace dismisses the screensaver" 10 screensaver_absent +wait_until "dismissal stops the effect" 10 effect_stopped +focus_workspace "$start_workspace" + +launch_screensaver +wait_until "screensaver reopens" 15 screensaver_present +wait_until "reopened screensaver takes focus" 10 screensaver_focused +wait_until "reopened screensaver starts an effect" 15 effect_running +# Send the key only once the screensaver, not another window, has focus. +screensaver_focused >/dev/null || fail "screensaver still has focus before the key press" +wtype x +wait_until "a key press dismisses the screensaver" 10 screensaver_absent +wait_until "key dismissal stops the effect" 10 effect_stopped +wait_until "dismissal removes the playback copy" 10 bash -c '[[ -z $(ls -A -- "$1") ]]' _ "$playback" diff --git a/test/shell.d/screensaver-branding-test.sh b/test/shell.d/screensaver-branding-test.sh new file mode 100755 index 000000000000..35dbaa859663 --- /dev/null +++ b/test/shell.d/screensaver-branding-test.sh @@ -0,0 +1,150 @@ +#!/bin/bash +set -euo pipefail +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" +require_command python3 +python3 - "$ROOT" <<'PY' +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +root = Path(sys.argv[1]) +with tempfile.TemporaryDirectory() as temporary: + home = Path(temporary) + stubs = home / 'bin' + stubs.mkdir() + branding = home / '.config/omarchy/branding' + branding.mkdir(parents=True) + target = home / 'dotfiles/shell.json' + target.parent.mkdir() + config = branding.parent / 'shell.json' + config.symlink_to(target) + original = {'idle': {'lock': 300}, 'custom': {'keep': True}, 'screensaver': {'source': '/old', 'other': 1}} + target.write_text(json.dumps(original)) + target.chmod(0o640) + (branding / 'screensaver.txt').write_text('ORIGINAL\n') + source = home / 'images' + source.mkdir() + for name in ('10-last.png', '2-second.jpg', '1-$(touch EXECUTED).png'): + (source / name).write_bytes(b'\x89PNG\r\n\x1a\nTEST') + (source / '0-link.png').symlink_to(source / '2-second.jpg') + (source / 'folder.jpg').mkdir() + os.mkfifo(source / 'pipe.png') + (source / '.hidden.png').write_bytes(b'fake') + texts = home / 'texts' + texts.mkdir() + (texts / 'one.txt').write_text('TEXT\n') + + def stub(name, body): + path = stubs / name + path.write_text('#!/bin/bash\n' + body) + path.chmod(0o755) + + stub('omarchy-transcode-ascii', 'printf "%s\\n" "$*" >> "$HOME/converts"\n' + '[[ ${FAIL_CONVERT:-0} == 1 ]] && exit 1\n' + '[[ ${SLOW_CONVERT:-0} == 1 ]] && exec sleep 60\n' + 'if [[ -n ${REPLACE:-} ]]; then rm -f -- "$REPLACE"\n' + ' case ${REPLACE_KIND:-} in link) ln -s -- missing "$REPLACE" ;; fifo) mkfifo -- "$REPLACE" ;; dir) mkdir -- "$REPLACE" ;; esac\n' + 'fi\n' + 'printf "CONVERTED\\n" > "$2"\n') + stub('omarchy-launch-screensaver', 'echo launch >> "$HOME/launches"\n') + stub('omarchy-shell', 'echo reload >> "$HOME/reloads"\n') + stub('omarchy-notification-send', 'printf "%s\\n" "$*" >> "$HOME/notifications"\n') + stub('omarchy-launch-editor', 'exit "${FAIL_EDITOR:-0}"\n') + stub('omarchy-file-select', '[[ ${CANCEL:-0} == 1 ]] && exit 1\nprintf "%s\\n" "$PICKED"\n') + env = dict(os.environ, HOME=str(home), OMARCHY_PATH=str(root), + PATH=str(stubs) + ':' + str(root / 'bin') + ':' + os.environ['PATH'], PICKED=str(source)) + + def run(*args, success=True, **extra): + result = subprocess.run([root / 'bin/omarchy-branding-screensaver', *args], + env=dict(env, **extra), capture_output=True, timeout=10, cwd=home) + assert (result.returncode == 0) == success, result.stderr.decode() + assert config.is_symlink() + assert target.stat().st_mode & 0o777 == 0o640 + current = json.loads(target.read_text()) + assert current['idle'] == original['idle'] and current['custom'] == original['custom'] + assert current['screensaver']['other'] == 1 + return current + + current = run('images', str(source)) + imported = Path(current['screensaver']['source']) + assert len(list(imported.glob('*.txt'))) == 3 + manifest = json.loads((imported / 'manifest.json').read_text()) + assert [r['source'].split('-')[0] for r in manifest['images']] == ['1', '2', '10'] + assert not (home / 'EXECUTED').exists() + assert all(line.endswith(' --mode color') for line in (home / 'converts').read_text().splitlines()) + print('ok - image folder uses native converter in colour mode, numeric order, and skips links/special files') + before = target.read_bytes() + run('images', success=False, CANCEL='1') + run('images', str(source), success=False, FAIL_CONVERT='1') + assert target.read_bytes() == before + assert "could not convert '1-$(touch EXECUTED).png'" in (home / 'notifications').read_text().splitlines()[-1] + (source / '0-bold&.png').write_bytes(b'\x89PNG\r\n\x1a\nTEST') + run('images', str(source), success=False, FAIL_CONVERT='1') + assert "'0-<b>bold&.png'" in (home / 'notifications').read_text().splitlines()[-1] + (source / '0-bold&.png').unlink() + # An image that vanishes or becomes a link after the scan fails the import + # instead of selecting a partial collection. + replaced = source / '10-last.png' + for kind in ('gone', 'link', 'fifo', 'dir'): + run('images', str(source), success=False, REPLACE=str(replaced), REPLACE_KIND=kind) + assert target.read_bytes() == before + assert list(imported.parent.iterdir()) == [imported] + assert "'10-last.png' changed during import" in (home / 'notifications').read_text().splitlines()[-1], kind + replaced.rmdir() if replaced.is_dir() and not replaced.is_symlink() else replaced.unlink(missing_ok=True) + replaced.write_bytes(b'\x89PNG\r\n\x1a\nTEST') + # An unreadable image fails with its own reason rather than being skipped. + if os.geteuid() != 0: + replaced.chmod(0) + run('images', str(source), success=False) + assert "cannot read '10-last.png' (Permission denied)" in (home / 'notifications').read_text().splitlines()[-1] + assert target.read_bytes() == before and list(imported.parent.iterdir()) == [imported] + replaced.chmod(0o644) + # A conversion timeout names the image, not the temporary snapshot. + result = subprocess.run([root / 'bin/omarchy-screensaver-import', str(source)], env=dict(env, SLOW_CONVERT='1'), + capture_output=True, timeout=40) + assert result.returncode != 0 and "took too long to convert" in result.stderr.decode() + assert 'input.' not in result.stderr.decode() and list(imported.parent.iterdir()) == [imported] + assert list(imported.parent.iterdir()) == [imported] + (source / 'bad.png').write_text('push graphic-context\nimage over 0,0 1,1 https://example.invalid/\n') + run('images', str(source), success=False) + assert target.read_bytes() == before + assert list(imported.parent.iterdir()) == [imported] + print('ok - cancellation, decoder failure, timeouts, files changed mid-import and disguised non-raster input preserve selection and clean incomplete imports') + current = run('folder', str(texts)) + assert current['screensaver']['source'] == str(texts) + print('ok - text folder selects a validated directory directly') + for action in ('image', 'text', 'reset'): + target.write_text(json.dumps(original)) + current = run(action) + assert 'source' not in current['screensaver'] + print('ok - image, text and reset clear collection selection while preserving other settings and symlinks') + target.write_text(json.dumps(original)) + before = target.read_bytes() + run('image', FAIL_CONVERT='1') + run('text', success=False, FAIL_EDITOR='1') + assert target.read_bytes() == before + target.write_text('{invalid json') + result = subprocess.run([root / 'bin/omarchy-branding-screensaver', 'folder', str(texts)], + env=env, capture_output=True, timeout=10) + assert result.returncode != 0 and target.read_text() == '{invalid json' + assert not list(target.parent.glob('.shell-config.*')) + print('ok - failed actions and malformed configuration do not silently replace selection or config') + + # Saving single-file artwork leaves shell.json alone when nothing is selected, + # including a config the shell tolerates but jq cannot parse. + for contents in ('{ "version": 1, }', '{"screensaver": "off"}', json.dumps({'idle': {'lock': 300}})): + target.write_text(contents) + (home / 'reloads').write_text('') + (home / 'launches').write_text('') + for action in ('image', 'text', 'reset'): + result = subprocess.run([root / 'bin/omarchy-branding-screensaver', action], + env=env, capture_output=True, timeout=10, cwd=home) + assert result.returncode == 0, result.stderr.decode() + assert target.read_text() == contents and not (home / 'reloads').read_text() + assert (home / 'launches').read_text().splitlines() == ['launch'] * 3 + assert (branding / 'screensaver.txt').read_text() == (root / 'logo.txt').read_text() + print('ok - image, text and reset save artwork without touching shell.json when no collection is selected') +PY diff --git a/test/shell.d/screensaver-collection-test.sh b/test/shell.d/screensaver-collection-test.sh new file mode 100644 index 000000000000..5e565d555b84 --- /dev/null +++ b/test/shell.d/screensaver-collection-test.sh @@ -0,0 +1,324 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command python3 +require_command magick + +python3 - "$ROOT" <<'PY' +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +root = Path(sys.argv[1]) +prepare = root / "bin/omarchy-screensaver-prepare" + + +def check(value, label): + if not value: + raise AssertionError(label) + print("ok - " + label, flush=True) + + +with tempfile.TemporaryDirectory() as temporary: + temp = Path(temporary) + source = temp / "art collection" + source.mkdir() + (source / "01.txt").write_text("FIRST\n") + (source / "02.txt").write_text("⣿⣿⣿\nSECOND\n") + + def run(path=source, success=True): + output = Path(tempfile.mkdtemp(dir=temp)) + result = subprocess.run([prepare, str(path), str(output)], cwd=temp, capture_output=True, timeout=5) + check((result.returncode == 0) == success, "source preparation " + ("succeeds" if success else "refuses unusable input")) + return [p.read_text() for p in sorted(output.glob("*.txt"))] + + check(run() == ["FIRST\n", "⣿⣿⣿\nSECOND\n"], "collection preserves text in filename order") + check(run(source / "02.txt") == ["⣿⣿⣿\nSECOND\n"], "single-file source preserves braille") + selected_link = temp / "selected-link" + selected_link.symlink_to(source, target_is_directory=True) + check(run(selected_link) == run(), "an explicitly selected directory symlink works") + + (source / "escape.txt").symlink_to(source / "01.txt") + (source / "loop.txt").symlink_to(source / "loop.txt") + (source / "folder.txt").mkdir() + (source / "folder.txt" / "nested.txt").write_text("NESTED") + os.mkfifo(source / "pipe.txt") + (source / ".hidden.txt").write_text("HIDDEN") + (source / "image.png").write_text("IMAGE") + (source / "binary.txt").write_bytes(b"\xff\x00") + (source / "empty.txt").write_text(" \n\t") + (source / "escape-sequence.txt").write_text("\x1b]52;c;SEVMTE8=\x07") + (source / "c1.txt").write_text("\u009b31m") + (source / "oversize.txt").write_text("X" * 1048577) + (source / "wide.txt").write_text("X" * 513) + (source / "tall.txt").write_text("X\n" * 129) + (source / "long-sgr.txt").write_text("\x1b[" + "1;" * 30 + "m" + "X") + (source / "sgr-then-osc.txt").write_text("\x1b[31mX\x1b]0;title\x07") + (source / "sgr-cursor.txt").write_text("\x1b[31mX\x1b[2J") + (source / "sgr-overflow.txt").write_text("\x1b[99999999999999999999mX") + (source / "sgr-big-value.txt").write_text("\x1b[38;5;300mX") + (source / "sgr-bad-arity.txt").write_text("\x1b[38;7;1mX") + (source / "sgr-dangling.txt").write_text("\x1b[38mX") + check(run() == ["FIRST\n", "⣿⣿⣿\nSECOND\n"], "links, special files, non-text files, controls and excessive artwork are skipped") + run(source / "pipe.txt", success=False) + colour = "\x1b[38;2;255;0;0;48;2;0;0;255m▀▄\x1b[0m\n" + (source / "00-colour.txt").write_text(colour) + check(run()[0] == colour, "SGR colour sequences pass through unchanged") + (source / "00-colour.txt").write_text(("\x1b[38;2;1;2;3;48;2;4;5;6m" + "█" * 500 + "\x1b[0m\n") * 120) + check(len(run()[0].encode()) > 65536, "a colour picture larger than the old 64 KiB limit is accepted") + (source / "00-colour.txt").write_text("\x1b[38;2;1;2;3m" + "X" * 513 + "\x1b[0m\n") + check(run()[0] == "FIRST\n", "the line limit applies to visible text, not to colour sequences") + (source / "00-colour.txt").write_text("\x1b[38;2;1;2;3m \x1b[0m\n") + check(run()[0] == "FIRST\n", "colour around blank text is still empty artwork") + (source / "00-colour.txt").write_text("\x1b[0;1;38;5;196;48;2;0;0;0mX\x1b[m\n") + check(run()[0].startswith("\x1b[0;1;38;5;196"), "attribute, 256-colour and empty SGR parameters are accepted") + (source / "00-colour.txt").write_text("X" * 513 + "\n" + "\x1b[m" * 300000 + "\n") + import time + started = time.monotonic() + check(run()[0] == "FIRST\n" and time.monotonic() - started < 2, "a large over-wide file is rejected quickly") + for name in ("00-colour.txt", "long-sgr.txt", "sgr-then-osc.txt", "sgr-cursor.txt", "sgr-overflow.txt", + "sgr-big-value.txt", "sgr-bad-arity.txt", "sgr-dangling.txt"): + (source / name).unlink() + + import re + image = temp / "photo.png" + subprocess.run(["magick", "-size", "120x80", "gradient:red-blue", str(image)], check=True, timeout=30) + converted = temp / "photo.txt" + subprocess.run([root / "bin/omarchy-transcode-ascii", str(image), str(converted), "--mode", "color", + "--width", "40", "--height", "20"], check=True, capture_output=True, timeout=60) + visible = re.sub(r"\x1b\[[0-9;]*m", "", converted.read_text()) + check(0 < len(visible.splitlines()) <= 20 and all(0 < len(line) <= 40 for line in visible.splitlines()) + and set(visible.replace("\n", "")) <= set("▘▝▀▖▌▞▛▗▚▐▜▄▙▟█"), + "colour conversion fits the cell box using block glyphs only") + check("\x1b[38;2;" in converted.read_text() and run(converted) == [converted.read_text()], + "colour conversion carries truecolour and passes playback validation") + + # Bounding large images must leave a small logo on a large canvas for trim. + subprocess.run(["magick", "-size", "8000x6000", "xc:white", "-fill", "none", "-stroke", "black", + "-strokewidth", "4", "-draw", "circle 4000,3000 4150,3000", str(image)], check=True, timeout=60) + for mode in ("braille", "block", "color"): + result = subprocess.run([root / "bin/omarchy-transcode-ascii", str(image), str(converted), "--mode", mode], + capture_output=True, timeout=60) + visible = re.sub(r"\x1b\[[0-9;]*m", "", converted.read_text()) if result.returncode == 0 else "" + check(len(visible.splitlines()) >= 20, "a thin logo on a large canvas still fills the frame: " + mode) + + # Sub-cell raster dimensions must still yield visible, preparable artwork. + for dimensions in ("1000x1", "1x1000", "3x5"): + subprocess.run(["magick", "-size", dimensions, "gradient:red-blue", str(image)], + check=True, capture_output=True, timeout=30) + subprocess.run([root / "bin/omarchy-transcode-ascii", str(image), str(converted), + "--mode", "color", "--no-trim"], check=True, capture_output=True, timeout=30) + check(run(converted) == [converted.read_text()], + "thin and odd-sized colour rasters produce playable cells: " + dimensions) + + # Exercise the runtime's actual deadline on a full, valid colour collection, + # not just cheap rejection of an oversized line. Vary every cell's colour. + large = temp / "large-colour-collection" + large.mkdir() + large_text = "".join( + "".join(f"\x1b[38;2;{x};{y};100;48;2;100;128;255m█" for x in range(200)) + + "\x1b[0m\n" for y in range(128)) + check(len(large_text.encode()) <= 1048576, "deadline fixture fits the per-artwork byte limit") + for index in range(128): + (large / f"{index:03d}.txt").write_text(large_text) + check(run(large) == [large_text] * 128, + "128 large valid colour artworks prepare within the five-second runtime deadline") + + marker = temp / "EXECUTED" + hostile = source / "03-$(touch EXECUTED) `touch EXECUTED`\n--help.txt" + hostile.write_text("LITERAL NAME\n") + check(run()[-1] == "LITERAL NAME\n" and not marker.exists(), "shell syntax, newlines and options in filenames remain data") + with tempfile.TemporaryDirectory(dir=temp) as snapshot: + subprocess.run([prepare, str(source), snapshot], check=True) + (source / "01.txt").write_text("CHANGED\n") + check((Path(snapshot) / "000.txt").read_text() == "FIRST\n", "playback copy is unaffected by source replacement") + check((Path(snapshot) / "000.txt").stat().st_mode & 0o777 == 0o600, "playback files are private") + + empty = temp / "empty" + empty.mkdir() + run(empty, success=False) + run(temp / "missing", success=False) + run("relative/path", success=False) + + many = temp / "many" + many.mkdir() + for index in range(129): + (many / f"{index:03d}.txt").write_text(str(index)) + check(len(run(many)) == 128, "artwork count is bounded") + for index in range(4096 - 129 + 1): + (many / f"extra-{index}").touch() + run(many, success=False) + + # Exercise the real runtime with a fake desktop and renderer. Nothing reaches + # the running compositor, the user's branding, or their processes. + home = temp / "home" + branding = home / ".config/omarchy/branding" + branding.mkdir(parents=True) + (branding / "screensaver.txt").write_text("DEFAULT\n") + config = branding.parent / "shell.json" + stubs = temp / "bin" + stubs.mkdir() + log = temp / "frames" + calls = temp / "calls" + scratch = temp / "scratch" + scratch.mkdir() + + def stub(name, content): + file = stubs / name + file.write_text("#!/bin/bash\n" + content) + file.chmod(0o755) + + stub("hyprctl", '''if [[ $1 == activewindow ]]; then + if (( $(wc -l < "$FRAME_LOG") >= 4 )); then + printf '%s\\n' '{"class":"other"}' + else + printf '%s\\n' '{"class":"org.omarchy.screensaver"}' + fi +fi +''') + stub("ttfx", 'printf "%s\\n" "$2" >> "$CALL_LOG"\nhead -n 1 -- "$2" >> "$FRAME_LOG"\n') + stub("pgrep", 'sleep 0.1\n(( $(wc -l < "$FRAME_LOG") >= 4 ))\n') + stub("pkill", 'exit 0\n') + stub("stty", 'echo "60 160"\n') + stub("tty", 'echo /dev/pts/99\n') + environment = dict(os.environ, HOME=str(home), OMARCHY_PATH=str(root), TMPDIR=str(scratch), + PATH=str(stubs) + ":" + str(root / "bin") + ":" + os.environ["PATH"], + FRAME_LOG=str(log), CALL_LOG=str(calls)) + + def play(settings): + config.write_text(json.dumps(settings)) + log.write_text("") + calls.write_text("") + result = subprocess.run([root / "bin/omarchy-screensaver"], env=environment, + stdin=subprocess.DEVNULL, capture_output=True, timeout=10) + check(result.returncode == 0, "screensaver exits on dismissal") + check(not list(scratch.iterdir()), "dismissal removes playback copies") + return log.read_text().splitlines() + + check(play({}) == ["DEFAULT"] * 4, "absent setting preserves default single-file playback") + check(play({"screensaver": {"source": str(source / '01.txt')}}) == ["CHANGED"] * 4, "configured file plays through the runtime") + check(play({"screensaver": {"source": str(source)}}) == ["CHANGED", "⣿⣿⣿", "LITERAL NAME", "CHANGED"], "runtime advances and wraps a collection") + check(play({"screensaver": {"source": str(empty)}}) == ["DEFAULT"] * 4, "empty collection keeps the screensaver alive with its fallback") + check(play({"screensaver": {"source": str(temp / 'missing')}}) == ["DEFAULT"] * 4, "missing source falls back instead of exiting") + check(play({"screensaver": {"source": 42}}) == ["DEFAULT"] * 4, "invalid config type retains the default") + stub("ttfx", 'printf "%s\\n" "$*" >> "$CALL_LOG"\nhead -n 1 -- "$2" >> "$FRAME_LOG"\n') + (source / "00-colour.txt").write_text("\x1b[38;2;255;0;0m▀\x1b[0m\n") + play({"screensaver": {"source": str(source)}}) + handling = [line.split("--existing-color-handling ")[1].split()[0] for line in calls.read_text().splitlines()] + check(handling[:2] == ["dynamic", "ignore"], "colour artwork settles on its own colours, plain artwork does not") + (source / "00-colour.txt").unlink() + stub("ttfx", 'printf "%s\\n" "$2" >> "$CALL_LOG"\nhead -n 1 -- "$2" >> "$FRAME_LOG"\n') + stub("mktemp", 'exit 1\n') + check(play({"screensaver": {"source": str(source)}}) == ["DEFAULT"] * 4, "temporary-directory failure retains playback") + (stubs / "mktemp").unlink() + stub("timeout", 'exit 124\n') + check(play({"screensaver": {"source": str(source)}}) == ["DEFAULT"] * 4, "preparation timeout retains playback and cleans its directory") + (stubs / "timeout").unlink() + (branding / "screensaver.txt").unlink() + play({"screensaver": {"source": str(empty)}}) + check(set(calls.read_text().splitlines()) == {str(root / 'logo.txt')}, "missing user fallback uses the bundled logo") + # Cleanup must not match unrelated process command lines or ttfx instances. + import shutil + import time + sleeper = temp / 'org.omarchy.screensaver-unrelated' / 'ttfx' + sleeper.parent.mkdir() + shutil.copy2('/usr/bin/sleep', sleeper) + unrelated = subprocess.Popen([str(sleeper), '30']) + owned_pid = temp / 'owned-pid' + dispatches = temp / 'dispatches' + broad_kills = temp / 'broad-kills' + environment.update(OWNED_PID=str(owned_pid), DISPATCHES=str(dispatches), BROAD_KILLS=str(broad_kills)) + stub('ttfx', 'echo $$ > "$OWNED_PID"\nexec sleep 30\n') + stub('pkill', 'echo unsafe >> "$BROAD_KILLS"\n') + stub('hyprctl', '''case "$1" in +activewindow) echo '{"class":"org.omarchy.screensaver"}';; +clients) echo '[{"class":"org.omarchy.screensaver","address":"0x123"},{"class":"other","address":"0x456"},{"class":"org.omarchy.screensaver","address":"bad;command"}]';; +dispatch) printf "%s\\n" "$2" >> "$DISPATCHES";; +esac +''') + process = subprocess.Popen([root / 'bin/omarchy-screensaver'], env=environment, + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + deadline = time.monotonic() + 5 + while not owned_pid.exists() and time.monotonic() < deadline: + time.sleep(.02) + check(owned_pid.exists(), 'runtime starts an owned animation child') + child_pid = int(owned_pid.read_text()) + process.communicate(b'x', timeout=5) + check(process.returncode == 0 and unrelated.poll() is None and not broad_kills.exists(), + 'dismissal leaves unrelated ttfx and matching command lines alone') + check(not Path(f'/proc/{child_pid}').exists(), 'dismissal reaps its owned animation child') + check('address:0x123' in dispatches.read_text() and '0x456' not in dispatches.read_text() + and 'bad;command' not in dispatches.read_text(), 'cleanup closes only validated screensaver window addresses') + finally: + if process.poll() is None: + process.kill() + process.wait() + unrelated.terminate() + unrelated.wait() + stub('ttfx', 'exit 1\n') + stub('hyprctl', 'exit 1\n') + process = subprocess.Popen([root / 'bin/omarchy-screensaver'], env=environment, + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + time.sleep(1.2) + check(process.poll() is None, 'renderer failure and unavailable compositor do not dismiss the idle window') + finally: + process.terminate() + process.communicate(timeout=5) + + # Hyprland answers {} when focus moves to no window, such as an empty + # workspace. That is a dismissal. A reply that is not JSON is not. + stub('ttfx', 'exec sleep 30\n') + for reply, dismissed in (("{}", True), ("ok", False)): + stub('hyprctl', f"[[ $1 == activewindow ]] && echo '{reply}'\nexit 0\n") + process = subprocess.Popen([root / 'bin/omarchy-screensaver'], env=environment, + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + try: + process.wait(timeout=4) + except subprocess.TimeoutExpired: + pass + check((process.poll() == 0) if dismissed else process.poll() is None, + "focus on no window dismisses" if dismissed else "an unreadable focus reply does not dismiss") + finally: + if process.poll() is None: + process.terminate() + process.communicate(timeout=5) + + # Image-folder import through the real converter and its resource policy. + def import_folder(folder): + return subprocess.run([root / 'bin/omarchy-screensaver-import', str(folder)], capture_output=True, timeout=130, + env=dict(os.environ, HOME=str(home), OMARCHY_PATH=str(root), + PATH=str(root / 'bin') + ':' + os.environ['PATH'])) + + animated = temp / 'animated' + animated.mkdir() + frames = [arg for n in range(128) for arg in ('-size', '48x48', f'xc:rgb({n * 2},128,128)')] + subprocess.run(['magick', '-delay', '10', *frames, str(animated / 'animated.webp')], check=True, timeout=30) + check(import_folder(animated).returncode == 0, 'an animated WebP with 128 frames imports') + photo = temp / 'photo' + photo.mkdir() + subprocess.run(['magick', '-size', '8064x6048', 'gradient:red-blue', '-quality', '85', str(photo / 'photo.jpg')], + check=True, timeout=60) + check(import_folder(photo).returncode == 0, 'a 48-megapixel JPEG imports') + links = temp / 'links' + links.mkdir() + subprocess.run(['magick', '-size', '64x64', 'gradient:red-blue', str(links / 'real.png')], check=True, timeout=30) + for index in range(128): + (links / f'link-{index}.png').symlink_to('real.png') + (links / f'folder-{index}.png').mkdir() + result = import_folder(links) + check(result.returncode == 0 and len(json.loads((Path(result.stdout.decode().strip()) / 'manifest.json').read_text())['images']) == 1, + 'skipped links and folders do not count against the 128-image cap') + (photo / 'broken.png').write_bytes(b'\x89PNG\r\n\x1a\nBROKEN') + result = import_folder(photo) + check(result.returncode != 0 and "could not convert 'broken.png'" in result.stderr.decode(), + 'a failed import names the image') +PY