DesktopChomik/README.md
2026-10-28 09:56:33 +01:00

12 KiB

Desktop Chomik

A hamster that lives on top of your screen and reacts to typing, screenshots, music and being dragged around with the mouse. It runs on Linux (X11 and Wayland) and Windows; macOS, the tray and packaging are still on the list (docs/PLAN.md).

Source frames live in frames/ (18 animation folders, 1812 JPEG frames on black). The converter turns them into a transparent, lossless WebP set in assets/animations/ — 30 clips, 1811 frames, 24.7 MB — plus the manifest.json the app reads at startup.

Running it

cargo run -p convert_frames -- --in frames --out assets/animations   # regenerate assets
cargo test --workspace                                               # unit + asset tests

cargo run --release                                                  # the pet, on your screen
cargo run --release -- --backend x11                                 # force a backend (auto follows the session)
cargo run --release -- --headless --seconds 20                       # tick loop without a window
cargo run --release -- --replay scripts/demo.txt --seed 4            # scripted event sequence
./build.sh                                                           # release binaries in dist/

Flags: --assets, --config, --seed, --fps-scale, --backend, --no-sensors, --no-dialog, --seconds, --trace, --headless, --replay. A replay script is <milliseconds> <command> with key, drag_start, drag_stop, screenshot, music_on and music_off; --replay and --trace print every clip hand-off with its timestamp, which is how the rules below are verified.

Building

build.sh builds release binaries into dist/. With no argument it builds everything this machine can produce; targets can also be named, several at once:

./build.sh                 # everything available here
./build.sh all             # the same, explicit
./build.sh win64amd        # only the Windows x86_64 .exe
./build.sh linux64amd linux64arm

The aliases are linux64amd, linux64arm, mac64amd, mac64arm, win64amd and win64arm. Missing Rust targets or linkers are reported with the command that enables them, and each file is named after its target (e.g. dist/hamster-pet-x86_64-unknown-linux-gnu). Windows x86_64 cross-builds from Linux with mingw; arm64 Windows uses MSVC on Windows and LLVM-MinGW elsewhere. On Windows run the script from Git Bash in a Visual Studio developer shell (rustc needs link.exe). macOS builds on a Mac only, and its window backend is still planned (M5), so that binary exits with an unsupported-platform message.

The window

A transparent, always-on-top window the size of the canvas plus its padding (252x223), drawn by three backends: X11 (a dock-type window with a 32-bit ARGB visual), Wayland (a wlr-layer-shell top surface bound to one output, as KWin, sway and Hyprland provide) and Windows (a WS_EX_LAYERED popup whose frames go through UpdateLayeredWindow). On a display scaled above 100% the canvas is rendered at that scale. Without layer-shell the pet becomes an ordinary toplevel that the compositor places, so it cannot be dragged there; on X11 without a compositor it falls back to a shape mask — hard edged, but still animated and click-through outside the silhouette.

Pixels the hamster does not cover are cut out of the input region, so clicks reach whatever is behind: the shape extension on X11, an input region on Wayland, the alpha hit test of a layered window on Windows. Drag with the left button — the pet follows the cursor exactly and keeps playing its drag animation; right click quits. It wakes up in the bottom right corner and remembers where you left it, in global screen coordinates. Dragging is not clamped, so it can hang over an edge or sit on any monitor; only a saved position that is off every monitor is pulled back on screen.

Sensors

Sensor How it works
Typing /dev/input on Linux (needs the input group), a WH_KEYBOARD_LL hook on Windows; starts only on a burst of typing_start_keys presses inside typing_start_window_ms, so one shortcut key does not make it type
Screenshots the PrintScreen key from that same reader, so a shot that is never saved still counts, plus a folder watch on sensors.screenshot_dirs (the pictures folder by default) for shots taken with another shortcut. A file saved within 8 s of the press is that same shot. sensors.screenshot: auto (both), key (no disk), files (disk only), off
Music MPRIS over the session D-Bus on Linux, the media session manager (SMTC) on Windows: any player that reports Playing

No privileges beyond read access: run the pet as your own user (root has no session bus). If typing is reported as off, sudo usermod -aG input $USER and log back in; the startup dialog says the same. Anything the pet cannot use (no /dev/input, no session bus, no screenshot folder) is shown once in a startup dialog with its fix, using whatever the desktop ships (kdialog, zenity, yad) or the native message box on Windows; startup_dialog: false or --no-dialog turns that off.

Config

config.json is read from the working directory, next to assets/, so it lives in the project and nothing of the pet ends up in your home directory. It lists every option, so the knobs are easy to find and edit; without the file the pet runs on the defaults below and writes nothing. --config <file> uses another file instead, and creates it with all defaults when it does not exist yet. Only the window position is written back, into whichever file was read; command line overrides never are. A partial file keeps the defaults, out-of-range values are clamped, and a broken or unknown field falls back to the defaults with a warning — never a pet that refuses to start.

Key Default Meaning
position bottom right Last anchor position on the desktop
backend auto auto, wayland or x11
output largest Wayland output the surface is bound to, e.g. HDMI-A-1
typing_start_keys 3 Presses needed before the hamster starts typing
typing_start_window_ms 1500 Window those presses are counted in
typing_stop_delay_ms 700 How long it keeps typing after the last key
idle_delay_ms [2000, 7000] Pause between idle activities
activity_loop_ms [2500, 5000] How long the looping middle of an idle activity runs
fps_scale 1.0 Playback speed multiplier for every clip, or --fps-scale <f> for one run
clip_fps {} Frame rate of single clips, e.g. {"idle_blink": 15}; names are the keys of assets/animations/manifest.json
min_loops {} Minimum full plays of a loop, e.g. {"idle_activity_sleep_loop": 3}; only the idle activity loops run for a set time, so only they can be stretched
disabled_activities ["dig"] Idle activities that must never play
screenshot_request_ttl_ms 3000 How long a queued screenshot reaction may wait before it is dropped
sensors all on typing (auto/evdev/off), music, screenshot (auto/key/files/off), screenshot_dirs (empty means the pictures folder)
startup_dialog true Dialog at startup for anything the pet cannot use

The wording of that dialog lives in texts.json, next to the config: title, intro, outro, the problem template and one entry per situation. {reason} and {folders} are filled in at runtime, an unknown placeholder stays visible (so a typo is easy to spot), a message without fix drops the arrow line, and anything left out or unreadable keeps its built-in wording.

Playback rules

  1. Frame rate belongs to the clip, not to the display. Every clip plays at its own fps from the manifest (30 fps today) against a monotonic clock, so a 60 Hz, 144 Hz or throttled compositor all show the same speed. One render tick never advances more than 100 ms of animation, so a stall slows playback instead of fast-forwarding it.
  2. A running animation finishes before it is overridden. When a higher priority state takes over, the current chain plays its finish clip first, and the new clip starts when that ends. A start clip that is already playing always plays out. Chains without a finish clip (the screenshot reaction, one-shot idle gags) are cut, as the source engine did.
  3. Dragging is the exception: it takes the hamster instantly, without waiting for a finish clip.
  4. Priorities: drag > screenshot > typing > music > idle activity > main idle. A condition that is still valid keeps its chain running — a screenshot arriving mid-drag waits instead of ending it.
  5. Idle life: the resting animation picks a weighted random activity (blink dominates, props like the newspaper are rare) after a random pause, then returns to the main idle. The digging idle is disabled by default, matching the source data. The looping middle runs for activity_loop_ms, measured from the loop clip itself, and at least min_loops full cycles when it has an entry there.

Development rules

  1. All code, comments, docs and commit messages in English. Keep the README short and factual.
  2. Comments only where they earn their place. One or two lines on why, never a narration of what the code already says. No commented-out code.
  3. No over-engineering. No abstraction, configuration knob or dependency for a single use case.
  4. Shared logic gets a named helper in one small module, never copy-pasted.
  5. Platform code stays behind interfaces. The core (animation, state machine, config) is platform-free and unit-testable; no cfg blocks in business logic.
  6. Edge cases are part of the feature. Every external input — files, config, sensors, monitors, clock — is untrusted: validate, clamp, debounce, degrade gracefully, never crash, never fail silently.
  7. Test the logic that can break quietly: state machine transitions, chain timing, scheduler weights, config clamping, manifest validation and asset matting, with a fake clock. The generated assets are checked against everything the manifest promises.
  8. The frame loop does no unbounded work. Frames are decoded on demand into a bounded LRU cache; nothing waits on a process or a display-server round trip per frame.
  9. Targets: idle CPU < 1%, RAM < 60 MB. Measure before claiming a speedup.
  10. Keep the tree small and obvious. frames/ is a read-only local input; generated assets are reproducible from it and never edited by hand.

Repository layout

frames/                 raw source frames (read-only input, not committed)
assets/animations/      generated lossless WebP clips + manifest.json (built by tools/)
config.json             behaviour, edited before a build
texts.json              wording of the startup dialog
tools/convert_frames/   JPG -> transparent WebP converter and clip table
src/core/               manifest, frame cache, clip/chain player, engine, config, texts, replay
src/platform/           the pet window: shared frame loop, compositor, X11, Wayland and Windows
                        backends, startup dialog
src/sensors/            keyboard (evdev or a Windows hook: typing + PrintScreen), music (MPRIS/SMTC),
                        screenshot folder watch
src/main.rs             CLI: window, headless tick loop and --replay mode
tests/assets.rs         checks the generated asset set against the manifest
build.sh                release builds into dist/ (named targets, or all)
scripts/                replay scripts used to verify the animation rules
docs/PLAN.md            implementation plan, asset format, per-OS support matrix

Asset pipeline

The converter (cargo run -p convert_frames, see above) is deterministic — the same input gives byte-identical output — and verifies its own output: the first and last frame of every clip are decoded back and compared byte for byte, a missing source frame or a size mismatch stops the run, and unused source frames are reported (the stray neutral frame in pacidle0 is expected).

Matting clears only the background reachable from the image border: enclosed dark details (eyes, belly) stay fully opaque, and a one pixel alpha ramp keeps a whisker a hair instead of a thick dark spike. The baked drop shadow is kept by default, because removing it needs a threshold high enough to eat whiskers and dark props; --shadow drop does it anyway.

frames/ is not committed: assets/animations/ is the set that ships, and the source frames are only needed to regenerate it.