Skip to content
65 changes: 59 additions & 6 deletions bin/omarchy-branding-screensaver
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,79 @@
# omarchy:summary=Edit, set, or reset screensaver branding
# omarchy:group=branding
# omarchy:name=screensaver
# omarchy:args=<image|text|reset>
# omarchy:examples=omarchy branding screensaver image | omarchy branding screensaver text | omarchy branding screensaver reset
# omarchy:args=<image|images|folder|text|reset> [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//'&'/'&amp;'}
reason=${reason//'<'/'&lt;'}
reason=${reason//'>'/'&gt;'}
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 <image|text|reset>" >&2
echo "Usage: omarchy-branding-screensaver <image|images|folder|text|reset> [path]" >&2
exit 1
;;
esac
71 changes: 64 additions & 7 deletions bin/omarchy-screensaver
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -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
Expand All @@ -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
161 changes: 161 additions & 0 deletions bin/omarchy-screensaver-import
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
#!/bin/bash

# omarchy:summary=Convert a local raster image folder into a screensaver text collection
# omarchy:hidden=true
# omarchy:args=<image-directory> [--mode <color|braille|block>]

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('''<policymap>
<policy domain="delegate" rights="none" pattern="*"/>
<policy domain="filter" rights="none" pattern="*"/>
<policy domain="coder" rights="none" pattern="*"/>
<policy domain="coder" rights="read|write" pattern="{PNG,JPEG,WEBP,PBM,PGM,PPM,PNM,INFO}"/>
<policy domain="path" rights="none" pattern="@*"/>
<policy domain="resource" name="memory" value="128MiB"/>
<policy domain="resource" name="map" value="256MiB"/>
<policy domain="resource" name="disk" value="1GiB"/>
<policy domain="resource" name="width" value="16384"/>
<policy domain="resource" name="height" value="16384"/>
<policy domain="resource" name="list-length" value="129"/>
<policy domain="resource" name="thread" value="1"/>
</policymap>''')
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
Loading