Search by

sugarcraft / candy-image

detain

Terminal image viewer CLI — the chafa-independent front end of sugarcraft/sugar-image: file in, best-protocol image out, zero new render logic.

Package info

github.com/sugarcraft/candy-image

Homepage

Documentation

Type:project

pkg:composer/sugarcraft/candy-image

Statistics

Installs: 0

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

dev-master 2026-11-19 21:50 UTC

This package is auto-updated.

Last update: 2026-11-20 01:03:59 UTC


README

candy-image

CandyImage

CI codecov Packagist Version License PHP

VHS recording: candy-image rendering a synthetic sample as a quarter-block grid, followed by a --dump-detect report

Terminal image viewer for PHP 8.3+ — the chafa-independent front end built on sugarcraft/sugar-image. Point it at an image file and it detects your terminal, picks the best protocol, and writes the rendered bytes to stdout. This is the candy-image surface: the usable core of chafa's flag spellings, distilled to the ones the SugarCraft core can actually honor — and no shell-out to chafa, ever.

composer require "sugarcraft/candy-image:@dev"   # no stable release yet — see Install
./vendor/bin/candy-image photo.png                    # auto-detect + render
./vendor/bin/candy-image --dump-detect                # why is my image blank?
./vendor/bin/candy-image --format=half --size=80x24 logo.png
./vendor/bin/candy-image --format=symbols --symbols=ascii logo.png   # ASCII-art tier
./vendor/bin/candy-image --format=symbols --canvas=ansi256 --work=7 logo.png

To run it as a bare candy-image, add vendor/bin (or the global equivalent) to your PATH; the ./vendor/bin/... spelling above needs no PATH change. Inside a checkout the entry point is php bin/candy-image … — the spelling the demo tape runs — and a rolling latest phar is published too (see Install).

Long options only. Apart from -h, every flag is ---prefixed; chafa's single-dash muscle memory (-f, -s 80x24, -w 7) is not parsed as options — the first such token quietly becomes the image filename, so -f photo.png exits 1 with an "unexpected argument" complaint about the value, and a bare -v exits 2 with File not found: -v.

Input formats. PNG, JPEG and GIF are accepted, recognized by magic bytes. Anything else — including WebP and BMP — is refused with exit 2 and the MIME it detected (Unsupported MIME type: image/webp), even when the build's GD could decode it. That is a deliberate allow-list in the sugar-image library's ImageSource::fromFile, and widening it is a sugar-image decision, not this app's. The library's wider magic-byte roster and its animated-WebP structural refusal (the VP8X/ANMF sniff, host-independent) apply to the embedded fromString route. --animate plays animated GIF only: the sugar-animation decoder rejects non-GIF bytes outright.

Platform support

  • Linux — the primary target: winsize via the TIOCGWINSZ ioctl through sugar-core, live terminal queries on a tty, sixel/kitty/iTerm2 protocols exercised on every push in CI.
  • macOS — works through the same POSIX path with the environment fallback rungs behind it, but candy-image itself has never joined the macOS CI pool (the phar pipeline above runs Linux-only), so treat it as supported-untested rather than proven.
  • Windows — graceful but unproven. A render never hard-crashes on geometry any more: the console size falls back to COLUMNS/LINES, then to the fixed 60×24 viewport, and a still render arms the console output codepage to UTF-8 before writing the text tiers. Interactive paths (--animate, live capability queries) need ext-ffi — without it they degrade to the same fallback viewport, not a signal-255 death — and sixel under Windows Terminal is untested. In one line: still renders should work, animations are a gamble, and none of it is CI-pinned for this app.

Environment

Detection reads the environment before it queries the terminal: sugar-image's TermDb matches the roster in TermDb::ENV_KEYS (TERM, TERM_PROGRAM and TERM_PROGRAM_VERSION, TMUX, LC_TERMINAL, the kitty/XTERM/Konsole/ VTE/MLterm/Ghostty/WezTerm/Windows-Terminal markers, ComSpec) innermost first, and Detect::probe() layers live queries and the tmux passthrough decision on top. --dump-detect prints exactly which of those inputs were present, so the dump — not a guess at your wrapper — says what the chain saw.

Three operator knobs sit under the stack (owned by sugar-pty): SUGARCRAFT_LIBC pins which C library the FFI bindings load (the musl/Alpine escape hatch — note it feeds FFI::cdef directly, so treat it as trusted input, not user input), SUGARCRAFT_PTY_BACKEND selects the pty backend (auto/posix-ffi/conpty), and SUGARCRAFT_TERMIOS=stty chooses the stty(1) termios path over the FFI one. When a default behaves oddly under an unusual wrapper, unsetting these is the first move — the dump's mux=/ tmux= fields show what changed once you do.

Install

Requirements. PHP 8.3+ and ext-gd are enforced on every channel: composer consumers get both from this package's require (a host without gd fails the install), and a downloaded phar embeds the vendor tree, whose vendor/composer/platform_check.php hard-fails any PHP older than 8.3 the moment the bundled autoloader loads. The phar carries no extension check though — run it on a PHP built with ext-gd, or the first decode fails. ext-ffi is not required to install, but interactive runs want it: without FFI the winsize ioctl cannot answer and the size falls back to COLUMNS/LINES, then to the fixed 60×24 viewport; Windows raw-terminal input needs it outright (it is sugar-pty's termios backend). Two external binaries are consulted opportunistically: stty(1) answers the terminal-size rescue rungs, and being inside tmux is what makes the default --passthrough=auto wrap frames in its envelope.

No released version yet. Packagist serves dev-master only — there is no tag and no branch-alias — so in a project with the default minimum-stability: stable, a bare composer require sugarcraft/candy-image cannot resolve. Ask for the dev package explicitly (the Packagist version badge above renders nothing until the first tag, for the same reason):

composer require "sugarcraft/candy-image:@dev"

Phar channel. CI rebuilds and republishes a rolling prerelease on every push to master that touches it or its dependency closure:

curl -LO https://github.com/detain/sugarcraft/releases/download/candy-image/latest/candy-image.phar
curl -LO https://github.com/detain/sugarcraft/releases/download/candy-image/latest/candy-image.phar.sha256
sha256sum -c candy-image.phar.sha256
php candy-image.phar photo.png

The rolling CI phar's --version prints the dev-<shortsha> stamp of the commit it was built from. A local tools/build-phar.php run stamps the newest candy-image/v* tag, or dev-build when no tag is reachable. The full sidecar set sits beside every rolling asset: .phar.sha256 (integrity — sha256sum -c checks it, as above), .phar.commit (the full build SHA) and .phar.pins.json (the sibling pin map); when the CI run holds the signing key, the .phar.sha256.sig, .phar.minisig and .phar.minisig.sha256 signatures ride along too. Integrity is verifiable as shipped; authenticity of the signatures needs the sugarcraft public key, which candy-image pins none — candy-code and candy-top are the only apps that carry it, to verify their own self-updates.

Options

Option Meaning
--format=F Force a protocol: auto sixel kitty iterm2 half (halfblock) quarter (quarterblock) ascii ansi16 ansi256 truecolor symbols (symbol/sym).
--symbols=CLASS[+CLASS...] Select the symbol tier's glyph corpus with chafa's tag classes — the live set is all none space solid stipple block border diagonal dot quad half hhalf vhalf inverted braille sextant octant wedge technical geometric ascii alpha digit narrow wide ambiguous ugly extra alnum bad legacy latin import imported (+ adds, - removes, a leading sign is relative to the default corpus; signs persist across comma-separated tokens, last match wins). Names are matched exactly (case-insensitively): chafa's prefix spellings such as brai are refused, and its [chars] literal-set and codepoint-range forms are not implemented. Which corpora the classes draw on — and what all counts — is stated once, in the compat map below.
--canvas=MODE Colour canvas for the text tiers: truecolor (default) ansi256 ansi16 fgbg. A no-op on backends without the dial.
--work=N Candidate-search effort: chafa's integer 1–9, config float (N−1)/8 — 1 is the cheapest render, 9 runs the exhaustive path.
--size=WxH Render box in terminal cells (chafa's WxH syntax — here a cells box).
--width=N / --height=N Individual box legs (one dimension each); cannot be mixed with --size. Defaults: the terminal viewport — columns × (rows − 1), with one status row held back when STDOUT is a live tty, the COLUMNS/LINES environment when both are set, and a fixed 60×24 cells otherwise (piped output, CI, examples — e.g. candy-image x.png > out.txt); size the box explicitly if you need anything else. The image aspect never picks the box height on this CLI. Each box leg is capped at 100,000 cells, and the box as a whole at 25,000,000 cells (width × height): render time scales with the product, so an oversized box is refused (exit 1) rather than left looking frozen.
--scale=S Fit policy: fit shrink fill stretch none crop (maps onto SugarCraft\Image\Scale).
--animate Animated-GIF pass-through into sugar-animation's Player (alternate screen). Pause, frame-stepping and the solid/density preset toggle ride this viewer's wired Player (Keys below); frame-rate, speed and watch-mode flags (--fps/--speed/--duration/--watch) live in candy-gifview. Combining it with the render dials --format/--scale/--symbols/--canvas/--work is refused (exit 1) — the animation path speaks none of them and would silently drop them; --width/--height/--size are honored. A run with both stdin and stdout redirected is refused too (exit 1): the player is interactive, and with no terminal to steer it the loop would spin forever.
--passthrough=V tmux allow-passthrough transaction: auto (default) or none. Under tmux with none, the --format argv check no longer runs the probe, so the auto() probe runs at render with passthrough off (behavior change; see the --passthrough row of the compat map).
--polite Accepted no-op for chafa muscle-memory — this viewer always renders inline and synchronously. The value slot accepts on/off (the bare flag and --polite= are accepted as the empty value); any other value is refused (exit 1).
--dump-detect Print the resolved terminal state. When set, the file path is optional — the dump prints the version banner and the full evidence table the detection chain consulted (every TermDb::ENV_KEYS roster entry — TERM, TERM_PROGRAM, TMUX, emulator-version variables, ComSpec — each (unset)/(empty)/value), then the detection report (TermDb chain/claims/passthrough/mux fields, Detect capabilities sixel/kitty/iterm2/halfblock/chafa/tmux and summary, cell pixel size, default fg/bg, DA1 reply ((none) also when the terminal only echoed the query silently), auto() selection, tmux transaction, palette report). The dump happens before the file argument is required, so a supplied path is ignored and the run exits 0.
--version / --help (-h) Print the version / usage and exit 0.

--format=auto confirms Kitty with an APC query, so it needs a tty on stdin and stdout. Redirected output (candy-image --format=auto photo.png > frame.txt) gets symbols text, not Kitty bytes, even inside a Kitty terminal. Use --format=kitty to write the Kitty bytes without a probe. See sugar-image's README (Kitty is confirmed, not assumed) for the 300 ms reply window and the remote-session cost.

Chafa flag-compat map (what this viewer honors and why)

chafa flag status here reason
--format ✅ subset The CLI allow-list is auto sixel kitty iterm2 half (halfblock) quarter (quarterblock) ascii ansi16 ansi256 truecolor symbols. Mosaic::fromModeString() knows two arms more than the CLI accepts: chafa (its own refusal message by design — the whole point is a viewer that never shells out) and ansi (halfBlock's legacy alias — refused as an unknown format). Both exit 1.
--size ✅ cells; --width/--height as explicit-leg aliases.
--dump-detect ✅ chafa's debugging gold, re-expressed over Detect + TermDb + the palette probe.
--passthrough ✅ auto/none The GNU Screen envelope has landed — sugar-image's Passthrough\ScreenPassthrough is applied automatically by detection. What refuses (exit 1, with a pointer mirroring lang/en.php) is forcing it: tmux and screen are not accepted values here; use auto or none. Behavior change (P1-13c-image): --format validation at argv time is probe-free (Mosaic::fromModeString($raw, probe: false)), so it no longer switches tmux allow-passthrough on before --passthrough is applied. The auto() probe now runs at render, after the passthrough choice. Under tmux with --passthrough=none, --format=auto therefore runs its probe with passthrough off, and the Kitty APC query and wrapped sixel may be dropped by tmux, so the image may fall back to symbols.
--polite ✅ no-op sugar-image has no async worker model; every render is already "polite".
--symbols ✅ tag classes The default corpus is the byte-frozen 676-entry prefix. The all class expands it to 1,251 effective glyphs drawn from the 1,260-entry narrow array — the tables chafa's C build reads: ASCII, Latin, block table, legacy, misc-narrow, braille, sextant and octant. Nine narrow glyphs tagged ambiguous in those C tables are vetoed even by all (chafa's all omits the bad class, which contains them); re-including bad explicitly — all,bad — admits all 1,260. The opt-in wide kana tier (181 double-width glyphs) rides the double-width wide-glyph engine.
--scale ✅ chicle has a scale option (chicle-options.c); this CLI honors all six arms — fit shrink fill stretch none crop — mapped straight onto sugar-image's Scale enum.
--work ✅ chicle's integer work factor 1–9, mapped onto the config float (N−1)/8, threaded onto whichever backend speaks it.
--probe=off ⏭ refuses sugar-image does expose a probe-free seam (Detect::fromEnv(), reached through Mosaic::fromModeString($mode, probe: false)), but mapping --probe=off onto it would change the protocol --format=auto picks: a Kitty claim stays unconfirmed and no DA1 sixel query runs. That is a behavior change this viewer's compat contract does not take on, so the spelling stays refused.
everything else ⏭ refuses out of scope for a thin composition-only viewer (façade law): the capability stays in the libs.

--canvas deliberately does not sit in this map: chafa's CLI has no --canvas flag (its canvas mode is an internal, detected setting), so the spelling here is sugar-image's CanvasMode dial name surfaced for the text tiers — see Options above.

Exit codes

Code Meaning
0 success (including --help / --version / --dump-detect)
1 usage error — unknown flag, bad value (including a size leg past the 100,000-cell ceiling, or a box reaching the 25,000,000-cell product ceiling), refused format (chafa/ansi), no image path given at all (usage is printed), a second file argument; separately, the bin exits 1 printing cannot find composer autoload.php when no autoloader resolves
2 input/decode error — an image path that is absent, unreadable, or undecodable (a missing file lands here, not on the usage path), undecodable image, empty animation, render failure

Architecture

bin/candy-image is a thin shim by design — an autoload probe with phar-identity resolution (a phar bundle outranks a working-tree vendor) and a one-line Cli::main() hand-off; all branches live in SugarCraft\CandyImage\Cli and are driven in-process by the tests (in-memory pipes, plus a ?\Closure $play seam for the animation loop). Detection, protocol selection, decode, and scaling are only ever sugar-image calls — no render logic may land in this package (façade law). The namespace is SugarCraft\CandyImage\ rather than the mechanical SugarCraft\Image\ because the latter is sugar-image's own — per the naming rule in PROJECT_NAMES.md.

Keys (while --animate plays)

Key Action
Space pause / resume (resuming re-anchors the frame clock)
← / → step one frame back / forward — works paused or playing, wrapping
d toggle the render preset: solid ↔ density
q / Esc quit
Ctrl+C quit — handled as a key by the player loop, and the SIGINT teardown path also stops playback

The player paints its own status footer with the same set, abbreviated: space pause ←/→ step d preset q quit.

Accessibility

Every format this viewer can pick produces pixels-or-glyphs, not semantics: nothing here describes image content, and no output leg is a screen-reader surface. What the flag surface can do is choose how the picture reaches you:

  • The graphics protocols (--format=sixel / kitty / iterm2) hand the terminal an encoded payload — they are literally invisible to screen readers and to copy/select, and they say nothing on a braille cell.
  • The text tiers are characters in the buffer: --format=ascii (a luminance ramp), --format=symbols (the symbol-engine corpus), the block tiers half/quarter, and the colored-character tiers ansi16/ansi256/ truecolor. They remain selectable and reachable by anything that reads terminal text, which the protocol payloads are not.
  • --canvas=fgbg confines a text-tier render to the terminal's own foreground/background pair, so the picture follows the user's contrast theme instead of embedding colors chosen from the image.
  • --work=1 is the cheapest candidate-search setting (the shortest path to a frame) when the exhaustive ladder is not wanted.
  • --dump-detect is the diagnostic leg: when a render looks blank or wrong, it prints what the stack actually detected instead of guessing.

Localized

The user-facing CLI strings — usage, flag/value/format refusals, notices — ship through the sugar-core i18n lookup from lang/en.php (the unique candy-image namespace — T::register() is first-wins, so this app must never bake the sibling sugar-image library's image). The bin activates the environment's locale at startup (T::setLocale(T::detect())), so an additional locale authored through the repo's add-locale flow is read on the very next run — no further wiring needed. Machine-facing output deliberately stays English: the --dump-detect report labels and the --version line are fixed-format diagnostics meant to be pasted verbatim into bug reports, not translatable prose.