SugarImage
Image-to-cell renderer
Image-to-cell renderer for the terminal. It decodes PNG, JPEG, GIF (still and animated), APNG, WebP and BMP, then renders through the best available tier: Sixel, Kitty graphics, iTerm2 inline images, the chafa CLI, or a Unicode text tier (half-block, quarter-block, an ASCII character ramp, or the symbol-map engine). It mirrors charmbracelet/x/mosaic (Go), and the symbol engine is a port of chafa's coverage-class symbol matching.
Install
composer require sugarcraft/sugar-image
Requires PHP ^8.3, ext-gd, ext-mbstring and react/promise, all declared in composer.json. Without GD every pure-PHP tier refuses with a readable message instead of an undefined-function error. The chafa CLI is never required: the chafa tier is opt-in and is the only external binary the library runs to produce image output.
Quickstart
use SugarCraft\Image\Mosaic;
use SugarCraft\Image\ImageSource;
$mosaic = Mosaic::halfBlock();
$image = ImageSource::fromFile('examples/fixture-gradient.png');
$ansi = $mosaic->render($image, width: 40, height: 20);
echo $ansi;
The output is an ANSI byte string your program owns. Write it to stdout, to a socket, into a text frame, or into a file. Nothing is printed on your behalf.
Concepts
Every tier is one of two kinds. Graphic tiers (Sixel, Kitty, iTerm2) send the terminal's own image escape sequences, so the picture is pixels. Text tiers (half-block, quarter-block, ASCII ramp, symbol map) send glyphs with 24-bit or 256-color SGR, so they work in any Unicode terminal and survive a plain pipe. Use a graphic tier when the terminal supports it, and a text tier as the floor when it does not.
Mosaic::probe() picks the tier from the environment and a DA1 capability query, and Mosaic::auto() runs the same ladder. Both are fail-soft: the result is always a usable tier. Force a tier when you know the terminal, or when a probe answer is not what you see on screen.
Tasks
Pick a tier explicitly
use SugarCraft\Image\Mosaic;
$mosaic = Mosaic::probe(); // best tier for this terminal
$mosaic = Mosaic::fromModeString('quarterblock'); // a named tier, or null if unknown
Choose a color depth for a text tier
use SugarCraft\Image\Renderer\AsciiColorMode;
use SugarCraft\Image\Symbol\CanvasMode;
$sixteen = Mosaic::ascii(AsciiColorMode::Ansi16); // 16-color character ramp
$mono = Mosaic::ascii(); // monochrome ramp (the default)
$symbols = Mosaic::symbols(CanvasMode::Ansi256); // symbol map on a 256-color canvas
Text tiers emit 24-bit or 256-color SGR with no palette negotiation. On a limited-color terminal, pick the canvas explicitly. NO_COLOR changes which graphic protocol is detected, but no renderer reads it to reduce the colors it emits.
Place an image by id on Kitty
use SugarCraft\Image\KittyOptions;
// Store the image once, then reference it at many offsets.
$store = KittyOptions::transmit(7)->withUseVirtual(true);
$place = KittyOptions::place(7, x: 4, y: 2);
The storing transmit carries the payload once, and each place() is a control-only frame that never resends it. Use withCompression(1) to zlib-compress the PNG payload before base64 encoding, which helps large images on slow links.
Render from a remote URL safely
ImageSource::fromUrl() and fromUrlAsync() refuse any scheme outside the allowlist, re-check the scheme on every redirect hop, and refuse any host that resolves to a private, loopback, link-local or reserved address, including cloud metadata addresses. The security note in the README lists the residuals: the host check runs at guard time, not connect time.
API reference
Mosaic
use SugarCraft\Image\ImageSource;
use SugarCraft\Image\Mosaic;
use SugarCraft\Image\Renderer\AsciiColorMode;
use SugarCraft\Image\Renderer\QuarterBlockRenderer;
$image = ImageSource::fromFile('examples/fixture-gradient.png');
// Probe terminal once, pick best protocol
$mosaic = Mosaic::probe();
// Force a specific backend
$mosaic = Mosaic::sixel();
$mosaic = Mosaic::kitty();
$mosaic = Mosaic::iterm2();
$mosaic = Mosaic::halfBlock();
$mosaic = Mosaic::quarterBlock();
$mosaic = Mosaic::ascii(); // character ramp, monochrome
$mosaic = Mosaic::ascii(AsciiColorMode::Ansi256); // ...or Ansi16 / TrueColor chars
$mosaic = Mosaic::symbols(); // chafa symbol engine, default 676-glyph corpus
$mosaic = Mosaic::chafa('--colors=256'); // external chafa CLI (opt-in)
// Render — returns ANSI bytes
$ansi = $mosaic->render($image, width: 40, height: 20);
// Builder for fine-grained control; withResize() sets the default cell box
// render() uses when called without a width
$mosaic = Mosaic::builder()
->withRenderer(new QuarterBlockRenderer())
->withResize(width: 40, height: 20)
->build();
$ansi = $mosaic->render($image); // 40×20 cells
$ansi = $mosaic->render($image, 60); // explicit width wins; height from aspect
Key classes
| Class | Method | Description |
|---|---|---|
| Mosaic | probe() | Auto-detect best terminal protocol |
| Mosaic | sixel(), kitty(), iterm2(), halfBlock(), quarterBlock(), ascii(), symbols(), chafa() | Force specific renderer |
| Mosaic | protocol(), modeDetail() | Resolved backend name + per-mode detail (compose DiskCache keys from both) |
| Mosaic | render(image, ?width = null, ?height = null) | Render image to ANSI string; a null width uses the builder's withResize() box |
| Mosaic | builder() | Create builder for fine-grained control |
| Renderer | delete(imageId) | Remove a previously rendered image (Kitty=APC delete; iTerm2=OSC 1337 Pop; others=empty) |
| KittyRenderer | renderWithOptions(image, width, height, KittyOptions) | Render with Kitty protocol options (virtual-image store a=T,U=1 + control-only a=p; zlib o=z; raw-byte chunking) |
| KittyOptions | transmit(id), place(id, x, y) | Factory: transmit (with or without storage) or place a previously stored image; place() emits a one-shot control-only a=p frame and never carries payload |
| KittyOptions | withZIndex(z), withCompression(f), withUseVirtual(bool), withPlacementU(u) | Builder: z-index stacking, zlib compression (o=z), storing transmit (a=T,U=1 + trailing a=p), under/over-text placement (U=1 default, U=0 over text) |
| QuarterBlockRenderer | new | 2×2 sub-pixel renderer via Mosaic::builder()->withRenderer(new QuarterBlockRenderer()) |
| HalfBlockRenderer | new, supportsAlpha() | Unicode ▀ renderer with transparent-pixel handling (null alpha skips SGR codes, letting terminal default show through). supportsAlpha() returns false: transparency is rendered by omitting SGR, not blending. |
| SixelRenderer | new(dither, maxColors, cellWidth, cellHeight, intensity), maxColors(), dither() | DEC sixel renderer with median-cut quantizer (up to 256 colors). Constructor accepts maxColors (1–256, default 256) to limit palette size for limited-truecolor terminals. The constructor also takes intensity (0.0–1.0 Ordered/Noise bias; null keeps the chafa config default 1.0). Dither enum: FloydSteinberg, Stucki, Atkinson, Ordered, Noise, None. |
| ChafaRenderer | __construct(...), available(), renderAsync() | Shells out to the chafa CLI with bounded output; the child is reaped on a TERM→KILL ladder. available() reports whether a binary resolved. Opt-in only. |
| SymbolMapRenderer | withCanvasMode(), withWorkFactor(), withSymbolSelectors() | Symbol-map tier: picks glyph cells by Hamming-distance candidate search. Mosaic::symbols() builds one with its defaults. |
| SymbolMap | coverageToBitmap() and the candidate search | The coverage-class engine behind the symbols tier: the glyph corpus and the search over it. The 676-glyph default corpus is byte-frozen. |
| SymbolSetLatin | (glyph table) | The chafa Latin narrow set: 365 glyphs from U+00A1 to U+03F6, transcribed as 8×8 bitmaps. |
| SymbolSetTables | (glyph tables) | The chafa narrow tables the symbol engine carries: ASCII, the Latin and Greek set, misc-narrow, and the legacy-computing block entries. |
| Ditherer | indexRows(image, palette, offset, yOrigin), noiseMagnitude(intensity) | The shared dithering stage: error diffusion and bias texture. indexRows() walks RGB rows and yields palette indices, and the Sixel renderer uses it. |
| ImageSource | fromFile(path), fromString(bytes), fromGd(image, format), fromRgb(bytes, w, h) | Load an image from a file, bytes, a GD resource or raw RGB(A) pixels. Decode budgets apply to every route. |
| ImageSource | fromAnimatedFile(path) | Animated GIF or APNG frames as an Animation (frames + per-frame delays). Animated WebP is refused by name. |
| ImageSource | fromUrl(url, headers) / fromUrlAsync(url) | Remote images with the scheme and private-address SSRF floor (synchronous, or ReactPHP) |
| ImageSource | isPng(), aspectRatio(), crop(), resize() | Signature check, geometry, and pixel transforms on the decoded image |
| DiskCache | get/put/getOrCompute, key() | On-disk render cache; atomic writes, hashed keys, bounded entries |
| ImageLayer | place(bytes, w, h), placeTracked() | Reserve marker blocks carrying image bytes in a text frame (dedup by content hash) |
| Animation | fixed(frames, delayMs), withFrame(index, frame, delayMs), frameCount(), totalDurationMs() | Immutable frame sequence: uniform-delay factory, one replaced frame, count, and total duration in ms |
| AnimationDriver | new(animation, renderer, cellWidth, cellHeight?, index?, paused?, imageId?) | Model that drives an Animation onto a Renderer via tick-based frame timing; withIndex(), withPaused() and withImageId() return new instances |
| KittyRenderer | renderFrame(image, width, height, imageId) | Render a single frame with a stable id for targeted delete and redraw on Kitty terminals |
| Detect | cached(), fromEnv(), probe(), setAutoPassthrough(bool) | Capability detection: cached() memoizes the probe per process; setAutoPassthrough(false) opts out of tmux passthrough management |
What's in the box
TERM alone.auto() floor of the fallback ladder is the symbol-map tier.auto() rung).ImageSource::fromString() also accepts anything imagecreatefromstring() decodes (WebP, BMP and others) with its real MIME in format; the Kitty and iTerm2 renderers re-encode any payload that is not PNG by signature. Pixel allocations are bounded before GD is asked for them.Mosaic::probe() checks environment variables and the DA1 capability query on every call; Detect::cached() memoizes the answer per process.KittyOptions::transmit(id)->withUseVirtual(true), then reference it at many offsets with KittyOptions::place(id, x:, y:).KittyOptions::withCompression(1), emitted as f=100,o=z. Useful for large images on slow links.maxColors (1–256) to the SixelRenderer constructor to limit palette size on terminals with limited truecolor support. It rides the builder: Mosaic::builder()->withRenderer(new SixelRenderer(maxColors: 64))->build().symbols: when needed. Mosaic::symbols(canvas:, workFactor:, symbols:) selects the color canvas, candidate budget and chafa's --symbols= tag grammar.Mosaic::ascii() maps one luminance sample per cell onto a character ramp. AsciiColorMode::Ansi16 | Ansi256 | TrueColor carries pixel colors on the characters themselves.ChafaRenderer shells out to the chafa command with option passthrough. Output is bounded and the child is reaped on a TERM→KILL ladder. Binary discovery is gated (see Configuration). Opt-in only; the pure-PHP tiers never shell out for pixel data.ImageSource::fromUrl() and fromUrlAsync() (ReactPHP) with a security floor: scheme allowlist re-checked every redirect hop, and any host resolving to a private, loopback, link-local or reserved address (including cloud metadata) is refused.DiskCache stores finished bytes keyed by URL, size and protocol (plus the mode detail) for cross-process redraws. AdaptiveImage is the in-session LRU. ImageLayer reserves marker blocks so images ride inside a text frame without wrecking layout.allow-passthrough is on. TmuxPassthrough turns it on for the pane during the render and restores it (or unsets it) on retire. It is fail-soft and never throws.Animation (immutable frame sequence) and AnimationDriver (a Model with tick-based frame timing). Use KittyRenderer::renderFrame() for stable per-frame ids that support targeted redraws.Only methods declared in sugar-image/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Image
AdaptiveImage final class
Memoizing image renderer.
| Method | Summary |
|---|---|
__construct(private readonly ImageSource $image, private readonly Mosaic $mosaic, int $maxCache = 4, private readonly ?AsyncRenderer $asyncRenderer = null) | |
withAsync(?AsyncRenderer $renderer = null): self | Return an async-rendering twin of this AdaptiveImage. |
render(int $cellWidth, int $cellHeight): string | Render at the given cell dimensions, using the cache if available. |
renderAsync(int $cellWidth, int $cellHeight): PromiseInterface | Async render — resolves with ANSI bytes, using the cache. |
precompute(int $cellWidth, int $cellHeight): PrecomputedImage | Render once and return a PrecomputedImage that holds the result. |
clearCache(): void | Invalidate all cached entries. |
cacheSize(): int | Number of currently cached entries. |
Animation final class
An ordered sequence of frames with per-frame delays.
| Method | Summary |
|---|---|
__construct(public readonly array $frames, public readonly array $delaysMs) | |
static fixed(array $frames, int $delayMs): self | Convenience factory: same delay for every frame. |
frameCount(): int | Number of frames in the animation. |
totalDurationMs(): int | Sum of all per-frame delays in milliseconds. |
withFrame(int $index, ImageSource $frame, int $delayMs): self | Replace a single frame at the given index. |
AnimationDriver final class
Drives an Animation onto a Renderer using the Model contract so it can be embedded in a Program or composed into a parent Model via \SugarCraft\Core\Composite.
| Method | Summary |
|---|---|
__construct(public readonly Animation $animation, public readonly Renderer $renderer, public readonly int $cellWidth, public readonly ?int $cellHeight = null, public readonly int $index = 0, public readonly bool $paused = false, public readonly int $imageId = 1) | |
init(): ?\Closure | Return a tick Cmd for the first frame when not paused. |
update(Msg $msg): array | Handle tick messages: advance the frame index and schedule the next tick. |
view(): string | Emit the current frame, committing it before any retire byte. |
subscriptions(): ?\SugarCraft\Core\Subscriptions | No active subscriptions — this Model is purely tick-driven. |
withIndex(int $index): self | Advance to a specific frame index without changing pause state. |
withPaused(bool $paused): self | Pause or unpause animation playback. |
withImageId(int $imageId): self | Change the base of the driver's stable image-id pair. |
AsyncRenderer interface
Strategy interface for asynchronous rendering.
| Method | Summary |
|---|---|
renderAsync(ImageSource $image, int $width, int $height): PromiseInterface | Render the image asynchronously and resolve with ANSI bytes. |
Capability final class
Snapshot of the detected terminal's image-rendering capabilities. Immutable value object returned by Detect::probe().
| Method | Summary |
|---|---|
static universal(?CellSize $cellSize = null, bool $inTmux = false): self | Build a full-capability instance (all protocols available). Used for Mosaic::halfBlock() which is always available. |
static kitty(?CellSize $cellSize = null, bool $inTmux = false): self | Kitty-only capability built from an environment claim: the env hypothesis, not a confirmed result. Detect::probe() keeps it only when the terminal answers the APC a=q query, and Detect::fromEnv() reports the claim unconfirmed. A caller that builds it directly asserts Kitty on the environment alone, so it must not treat the result as a confirmed Kitty terminal. |
static iterm2(?CellSize $cellSize = null, bool $inTmux = false): self | iTerm2-only capability. |
static sixel(?CellSize $cellSize = null, bool $inTmux = false): self | Sixel-only capability. |
static unknown(?CellSize $cellSize = null, bool $inTmux = false): self | Empty capability set — used when no probe data is available. |
withCellSize(?CellSize $cellSize): self | Return a copy of this capability with the given cell size attached. Used by Detect::probeFontSize() to attach font-size data to whatever protocol was detected via env vars or DA1. A null $cellSize means "size unknown" — the probe never measured one — which is also the never-set state: renderers fall back to their own cell assumptions for it, so no sentinel distinction exists. |
withDefaultColors(?string $defaultFg, ?string $defaultBg): self | Return a copy of this capability with the terminal's reported default colours attached (lowercase 'rrggbb', null keeps unknown), shaped exactly like withCellSize() — the OSC 10/11 answers ride onto whichever protocol rung the ladder answered on. |
withTerminalFacts(?int $quirks, string $passthroughMode): self | Return a copy carrying the terminal-database facts — the quirks bitmask (null = chain never consulted, the byte-frozen shape) and the passthrough envelope mode. Built by Detect::probeEnv() on the resolved TermInfo, mirroring how chafa consults chafa_term_info_get_quirks() at the output epilogue (chafa.c:445-451) and dispatches on the chained passthrough mode (chafa-passthrough-encoder.c:145-165). |
detectSummary(): string | Return a human-readable summary of which protocols were detected. Mirrors Charmbracelet's image.(Kitty|Sixel|Iterm2|HalfBlock)Protocol.Name(). |
CellGeometry final class
Terminal-cell geometry — the arithmetic of turning a pixel aspect into cells.
| Method | Summary |
|---|---|
static cellAspect(?CellSize $cellSize): float | The height:width ratio of one cell, from probed font metrics when the terminal reported them and DEFAULT_CELL_ASPECT when it did not. |
static heightCells(int $widthCells, float $sourceAspect, float $cellAspect = self::DEFAULT_CELL_ASPECT): int | Cell rows that display a source of $sourceAspect at $widthCells without distortion — the inverse of the box the renderer actually paints. |
static widthCells(int $heightCells, float $sourceAspect, float $cellAspect = self::DEFAULT_CELL_ASPECT): int | Cell columns that display a source of $sourceAspect at $heightCells without distortion — the same law read from the other side, for callers that budget by rows. |
CellSize final class
Terminal cell pixel dimensions (width × height in pixels).
| Method | Summary |
|---|---|
__construct(public readonly int $cellWidth, public readonly int $cellHeight) |
Deadline final class
Monotonic deadline tracker for I/O timeout management.
| Method | Summary |
|---|---|
static in(int $ms): self | |
remainingMs(): int | Remaining whole milliseconds, floored, clamped at 0. |
isExpired(): bool | Whether the budget has run out, judged on the raw ns clock. |
remaining(): int |
DecodedImageCache final class
Process-wide LRU of decoded GD handles, keyed on the content of an ImageSource (rank 72), so a sheet that is cropped once per tile (rank 71) is decoded once instead of once per call.
| Method | Summary |
|---|---|
static gd(ImageSource $source): \GdImage | The decoded, truecolour handle for $source. A hit refreshes the entry's recency; a miss decodes once and evicts least recently used entries until both bounds hold again. |
static misses(): int | Number of decodes performed since the last reset(); a hit adds nothing. |
static size(): int | Entries currently held (never more than CAPACITY, nor more than BYTE_BUDGET bytes). |
static reset(): void | Drop every entry, zero the decode counter and clear the test budget seam (test isolation). |
Detect final class
Terminal image-protocol capability detection.
| Method | Summary |
|---|---|
static cached(): Capability | Probe once and cache the result for the lifetime of this process. |
static fromEnv(?array $env = null): Capability | Classify the terminal from environment variables alone: no tty, no query bytes, no timeout, no tmux process. Pure, so it can run in a test, in a pipeline, or before the program has a tty at all. |
static probe(): Capability | Probe the terminal: env vars first, then optional DA1 query. |
static reset(): void | Clear the cached capability, the last DA1 reply and the memoised Mosaic::auto() answer (for testing). |
static lastDa1Reply(): ?string | Return the raw bytes of the last DA1 reply, or null if no query was made or it timed out. |
static takeStrayInputBytes(): string | Take the keystrokes the probe readers swallowed alongside their replies, clearing the store so a second take cannot double-replay. Empty string when every read was reply-pure. |
static setProbeStdin($fd): void | Override the stdin source used during DA1 probing. Use this in tests to inject canned responses. |
static setProbeStdout($stream): void | Override the stdout sink used for writing the queries. Use this in tests to capture the query bytes the probe sends instead of spraying them onto the process's real STDOUT (finding 031); production code leaves this null. Pass null to restore the real STDOUT. Like setProbeStdin(), a test seam, not a knob. |
static setAutoPassthrough(bool $enabled): void | Opt the automatic tmux allow-passthrough transaction on or off . Default on; TmuxPassthrough::ensure() consults this on every call. Takes effect immediately for future probes — an already-open transaction is NOT rolled back here; retire it via TmuxPassthrough::retire(). |
static autoPassthrough(): bool | Whether setAutoPassthrough() currently permits the auto-toggle transaction. |
static supportsRepeat(): bool | Capability gate: does the current terminal interpret ESC[count b (REP — repeat the preceding graphic character)? |
static setSupportsRepeatOverride(?bool $supported): void | Force the REP answer for tests (null restores the env table). Same shape as the other Detect tri-states: while overridden, the table below is never consulted. |
static clearSupportsRepeatOverride(): void | Remove the override; supportsRepeat() goes back to the env table. |
static setTmuxTermFeaturesOverride(?bool $state): void | Force the tmux termfeatures answer for tests: true = outer terminal has sixel, false = definite no (veto), null = AUTO (the fail-soft verdict — while overridden, NO tmux process is ever spawned). |
static clearTmuxTermFeaturesOverride(): void | Remove the override; probeTmuxTermFeatures() goes back to asking tmux. |
static setTerminfoSixelOverride(bool $present): void | Test seam: pin the terminfo sixl answer without touching a real terminal database. true = short-circuit the ladder to sixel; false = "terminfo says nothing", fall through to the DA1 arm. While overridden no infocmp process is ever spawned. |
static clearTerminfoSixelOverride(): void | Remove the override; probeTerminfoSixel() consults the live probe again. |
static setTerminfoProbe(?TerminalProbe $probe): void | Seam: substitute the TerminalProbe the live arm runs (null restores default construction). The capability table itself stays in sugar-colorprofile — this is wiring, not a second lookup. |
DiskCache final class
Persistent, disk-backed cache for rendered terminal images.
| Method | Summary |
|---|---|
__construct(private readonly string $dir, private readonly int $maxEntries = 512, private readonly int $maxBytes = self::DEFAULT_MAX_BYTES) | |
static overrideClock(?callable $clock): void | Test seam for the LRU touch clock (same override-*-style pattern as ImageSource::overrideHostResolver()): lets a test age entries by virtual seconds instead of wall-waiting sixty of them. |
static key(string $url, int $width, int $height, string $protocol): string | Canonical cache key for a rendered image. |
has(string $key): bool | Whether an entry exists for the key (does not affect LRU order). |
get(string $key): ?string | Return the cached value, or null on a miss. |
put(string $key, string $value): void | Store a value for the key, then evict the oldest entries if over cap. |
getOrCompute(string $key, callable $compute): string | Return the cached value for the key, computing and storing it on a miss. |
delete(string $key): void | Remove a single entry (no-op if absent). |
clear(): void | Remove every entry in the cache directory, including any stray temp files. |
count(): int | Number of stored entries. |
Dither enum
Dithering algorithm selection for Sixel rendering.
Cases: None · FloydSteinberg · Stucki · Atkinson · Ordered · Noise
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
label(): string | Return the human-readable name for display. |
FrameTickMsg final class
Internal message indicating a frame-advance tick.
GraphicsFrameSession final class
Presents a sequence of frames on one terminal without leaking images.
| Method | Summary |
|---|---|
static new(Renderer $renderer): self | Start a session on $renderer using image ids 1 and 2. |
withImageId(int $imageId): self | A fresh session at frame zero whose two slots are $imageId and $imageId + 1. |
present(ImageSource $frame, int $width, ?int $height = null): string | Draw $frame and retire the previous one. Advances the session. |
frameCount(): int | Frames presented on this session so far. |
ImageLayer final class
A per-frame registry that turns pixel-graphics blobs into tiling-safe cell blocks and collects them for a \SugarCraft\Core\View's image layer.
| Method | Summary |
|---|---|
__construct(private readonly ?Renderer $renderer = null) | |
renderer(): ?Renderer | The renderer delete sequences are drawn from, or null when the layer was constructed without one (release()/releaseAllExcept() then still un-register placements but report empty sequences). |
static digestFor(string $bytes, int $width, int $height): string | Window key for a placement: content hash over bytes + cell footprint. |
place(string $bytes, int $width, int $height): string | Register $bytes and return a $width × $height marker block to drop in the frame (or a blank block of the same size once the id space is full). Deduplicates by content, so repeated bytes reuse their id. |
placeTracked(string $bytes, int $width, int $height): PlacedImage | place(), but also reporting the overlay id the bytes were assigned. |
placements(): array | The accumulated image layer (id → ImagePlacement) to hand to a \SugarCraft\Core\View. The runtime paints only the markers a given frame actually contains, so over-registering (e.g. images scrolled out of view) is harmless. |
removeById(int $imageId): void | Remove a placement by its image id. |
trackedDigests(): array | Every window digest currently tracked (one per distinct bytes+size combination that has been placed), in first-seen order. |
imageIdForDigest(string $digest): ?int | The image id a window digest is currently placed under, or null when it has never been placed, was since removed/released, or the id was re-placed at a different footprint (last-footprint-wins, see placeTracked()). Lets a viewport check its scratch digest against the layer before deciding to re-fetch/re-render — a null here after a size change is the layer telling you to re-place. |
release(int $imageId): string | Free one image: drop its placement (and its window-digest tracking) and return the escape sequence that deletes its terminal-side allocation. The bytes forfeit their id claim too — this door, not removeById, is where the id space is reclaimed (lowestFreeId()). Unknown id → no-op, empty string. |
releaseAllExcept(array $keepIds): array | Viewport windowing: free every placement whose id is NOT in $keepIds and return the delete sequences to emit, keyed by released image id. |
isEmpty(): bool |
ImageSource final class
A decoded image ready for rendering. Stores raw bytes, detected format, and pixel dimensions. Immutable.
| Method | Summary |
|---|---|
__construct(public readonly string $bytes, public readonly string $format, public readonly int $width, public readonly int $height, public readonly int $maxPixels = self::MAX_PIXELS) | |
withMaxPixels(int $maxPixels): self | Return a copy with a different decompression-bomb pixel ceiling. |
static fromFile(string $path, int $maxPixels = self::MAX_PIXELS): self | Load from a file on disk. |
static fromString(string $bytes, int $maxPixels = self::MAX_PIXELS): self | Load from raw bytes in memory. |
static sniffMime(string $bytes): ?string | The media type of image bytes, by magic number, or null when none of the four vision wires' formats matches: PNG, JPEG, GIF and WebP. |
static isFetchableUrl(string $url, ?array $allowedSchemes = ['http', 'https']): bool | Whether a URL names something fromUrl() may fetch: a non-empty host, and a scheme on the allow-list (compared case-insensitively, since RFC 3986 §3.1 makes schemes case-insensitive). |
isPng(): bool | True when self::$bytes carry the PNG signature. |
static fromGd(\GdImage $resource, string $format, int $maxPixels = self::MAX_PIXELS): self | Load from an existing GD image resource. |
static fromRgb(string $bytes, int $width, int $height, bool $hasAlpha = false, int $maxPixels = self::MAX_PIXELS): self | Ingest a raw RGB24/RGBA scanline buffer with no container format. |
static fromAnimatedFile(string $path, int $maxPixels = self::MAX_PIXELS): Animation | Decode an animated file into an Animation of frames + per-frame delays. |
static fromUrl(string $url, ?array $headers = null, ?array $allowedSchemes = ['http', 'https'], int $maxPixels = self::MAX_PIXELS, ?array $allowedHosts = null): self | Load from a remote URL synchronously. |
static fromUrlAsync(string $url, ?array $headers = null, ?Browser $browser = null, ?array $allowedSchemes = ['http', 'https'], int $maxPixels = self::MAX_PIXELS, ?array $allowedHosts = null): PromiseInterface | Load from a remote URL asynchronously on the ReactPHP event loop. |
aspectRatio(): float | Aspect ratio as a float (width / height). |
crop(int $x, int $y, int $w, int $h): self | Return a new ImageSource cropped to the given pixel region. The crop region must be fully within the source image bounds. |
resize(int $w, int $h): self | Return a new ImageSource resized to the given pixel dimensions using bicubic (high-quality) resampling. |
KittyOptions final class
Options for the Kitty graphics protocol renderer.
| Method | Summary |
|---|---|
static transmit(int $imageId = 0): self | Default options: transmit image inline. |
static place(int $imageId, int $x = 0, int $y = 0): self | Place a previously transmitted virtual image. |
withZIndex(int $z): self | Set z-index (stacking order, higher renders on top). |
withCompression(int $compress): self | Request zlib compression for the PNG payload. |
withUseVirtual(bool $useVirtual = true): self | Enable virtual placement — store with a=T,U=1, then place via a trailing control-only a=p,U=<placement> frame. The trailing frame's U follows self::withPlacementU(); the store frame's U=1 is fixed because it is the background-compositor flag, not a stacking choice (chafa emits U=1 on every transmit it may later place). |
withPlacementU(int $u): self | Choose the U value emitted on placement frames — both an explicit self::place() and the trailing frame of a virtual transmit pair. |
withCellDimensions(int $width, int $height): self | Set the transmitted image's display extent on the wire's s=/v= keys. |
withSourceDimensions(int $width, int $height): self | Set the transmitted image's display extent in pixels — the same s=/v= pair as self::withCellDimensions(), under the name that matches what the wire carries. |
withChunkBytes(?int $chunkBytes): self | Override the raw payload bytes carried per data-chunk frame. |
Lang final class
Per-library translation facade for sugar-image.
Mosaic final class
Public facade — the "Picker" from ratatui-image.
| Method | Summary |
|---|---|
__construct(private readonly Renderer $renderer, private readonly Capability $capability, private readonly ?int $forcedWidth, private readonly ?int $forcedHeight, private readonly ?Scale $scale, private readonly int $optimizations = 0) | |
static probe(): self | Probe the terminal and pick the best available protocol. |
static fromEnv(?array $env = null): self | Pick the best renderer from environment variables alone. |
static auto(): self | Auto-detect the best renderer. |
static resetAutoMemo(): void | Forget the memoised auto() result, so the next call probes the terminal again. For tests and for an application that changed terminal (a reattached multiplexer, say); the probe itself is the expensive part. |
static diagnose(): ProbeReport | Run the terminal capability probe and return a structured report. |
static kitty(): self | Force the Kitty graphics-protocol renderer. |
static iterm2(): self | Force the iTerm2 / WezTerm inline-image renderer. |
static halfBlock(): self | Force the half-block Unicode renderer (always available). |
static quarterBlock(): self | Force the quarter-block Unicode renderer (higher density than half-block). |
static ascii(AsciiColorMode $color = AsciiColorMode::Mono): self | Force the ASCII / ANSI character-ramp renderer (one pixel per cell). |
static sixel(Dither $dither = Dither::FloydSteinberg, ?float $intensity = null): self | Force the Sixel renderer with an optional dither algorithm. |
static chafa(string ...$options): self | Force the Chafa renderer with optional CLI options. |
static symbols(CanvasMode $canvas = CanvasMode::TrueColor, float $workFactor = SymbolMapRenderer::DEFAULT_WORK_FACTOR, ?string $symbols = null): self | Force the coverage-class symbol-map renderer. |
withCanvasMode(CanvasMode $canvasMode): self | Switch the colour canvas when the active backend is a text-tier renderer that speaks CanvasModeConfigurable (SymbolMapRenderer, QuarterBlockRenderer — also through a passthrough envelope); returns the same instance otherwise. |
withSymbolSelectors(string $selectors): self | Select the symbol corpus with chafa's --symbols= tag grammar when the active backend is the symbol-map renderer (also through a passthrough envelope); same instance otherwise. An invalid expression throws — never a silently empty corpus. |
withWorkFactor(float $workFactor): self | Forward chafa's --work dial when the active backend speaks WorkFactorConfigurable; same instance otherwise. |
withDither(Dither $dither): self | Return a new Mosaic with a different dither algorithm. Only meaningful when the current renderer is a SixelRenderer (also through a passthrough envelope); returns the same instance otherwise. |
acceptsDither(): bool | Whether the live backend hears the dither dial at all (withDither() and the builder's dither/sixel dials take effect). Answered through a passthrough envelope. |
acceptsCanvasMode(): bool | Whether the live backend speaks CanvasModeConfigurable — i.e. withCanvasMode() has an ear. |
acceptsWorkFactor(): bool | Whether the live backend speaks WorkFactorConfigurable — i.e. withWorkFactor() has an ear. |
acceptsSymbolSelectors(): bool | Whether the live backend is the symbol-map renderer whose chafa --symbols= corpus withSymbolSelectors() selects. |
ignoredDials(): array | The dial categories the live backend cannot hear, in the fixed order dither, canvasMode, workFactor, symbolSelectors. The tuning doors are silent no-ops on backends without an ear (the silence-law of this facade); this is their consultation surface — a doctor panel or the candy-code route asks which knobs would be ignored BEFORE offering them, instead of letting a user tune a dead dial. An empty list means every dial is live. |
withOptimization(Optimization ...$levels): self | Return a new Mosaic configured with optimization levels (chafa CHAFA_OPTIMIZATIONS ladder parity). |
optimizations(): int | The currently configured Optimization mask (0 = None). |
capability(): Capability | Expose the detected capability snapshot. |
protocol(): string | Stable backend name: 'sixel' | 'kitty' | 'iterm2' | 'halfblock' | 'quarterblock' | 'ascii' | 'chafa' | 'symbols'. This slot names the PROTOCOL only. The three AsciiRenderer colour arms all report 'ascii' here — pair with modeDetail() wherever the encoded bytes must be told apart. |
modeDetail(): ?string | Extra discriminator for when protocol() alone does not identify the encoded bytes. AsciiRenderer has four colour arms behind one protocol name, so an Ansi16/Ansi256/TrueColor ascii mosaic reports its AsciiColorMode value ('ansi16'/'ansi256'/'truecolor') here; every other renderer — and the Mono ascii arm, whose protocol name already is its mode value — reports null. A passthrough-decorated mosaic answers for its inner renderer, the same way the decorator's 'tmux(<inner>)'/'screen(<inner>)' name does. |
renderer(): Renderer | The renderer this mosaic encodes through (tmux decorator included when the terminal runs under tmux). |
static supportedProtocols(): array | All protocols supported by this library, in preferred order. |
isInline(): bool | True if render() produces inline cell text that can be placed directly in a text frame (half/quarter-block, ASCII); false for a pixel-graphics blob (Sixel/Kitty/iTerm2) that must be painted as an out-of-band overlay. See Renderer::isInline(). |
fontSize(): ?array | Best-effort font-size derived from capability detection. Returns null if font-size probing hasn't been implemented yet. |
scale(): ?Scale | The configured scale mode, or null for the default (Fit). |
render(ImageSource $image, ?int $width = null, ?int $height = null): string | Render the image to ANSI bytes at the given cell dimensions. |
renderRows(ImageSource $image, int $width, ?int $height = null): \Generator | Row-lazy twin of render(): the SAME scale pipeline runs up front (including its throws), then the encoded bytes arrive as append-order chunks whose concatenation is exactly what render() would have returned. |
static builder(): MosaicBuilder | Builder for fine-grained configuration. |
withScale(Scale $scale): self | Set the scale mode for rendering. |
adaptive(ImageSource $image): AdaptiveImage | Create a memoizing AdaptiveImage for the given source. |
precompute(ImageSource $image, int $width, ?int $height = null): PrecomputedImage | Render and cache one specific size as a PrecomputedImage. |
static fromModeString(string $mode, bool $probe = true): ?self | Build a Mosaic from a render-mode string. |
poster(string $url, int $cellW, ?int $cellH = null, ?DiskCache $cache = null, ?array $allowedHosts = null): string | Fetch a poster image from $url and render it at cell size in one call, consulting and populating an optional on-disk render cache. |
posterAsync(string $url, int $cellW, ?int $cellH = null, ?DiskCache $cache = null, ?array $allowedHosts = null): PromiseInterface | Async variant of poster() — resolves with the rendered bytes. |
posterFile(string $path, int $cellW, ?int $cellH = null, ?DiskCache $cache = null): string | Render a poster that already lives on local disk, with the same Fill-by-default scaling and optional DiskCache windowing as poster(). The cache key is derived from $path in place of a URL — and, unlike the URL legs, from the file's CURRENT identity (mtime at nanosecond resolution + size, finding 034): a remote URL is an immutable-enough handle for a TTL-free memo, but a path is a promise that the bytes under it never change, and they do. An edited or replaced poster therefore self-invalidates on the next call instead of serving the old encode forever under a stable key. Entries for since-deleted generations age out through the normal eviction cap; a stat failure (file vanished mid-call) falls back to the bare path — fromFile() is about to throw anyway. |
MosaicBuilder final class
Builder for Mosaic with optional renderer swap and dimension defaults.
| Method | Summary |
|---|---|
__construct(private readonly ?Renderer $renderer = null, private readonly ?int $width = null, private readonly ?int $height = null, private readonly ?Dither $dither = null, private readonly ?Scale $scale = null, private readonly ?float $sixelIntensity = null, private readonly ?int $sixelMaxColors = null) | |
withRenderer(Renderer $renderer): self | |
withResize(int $width, ?int $height = null): self | Resize target for the built Mosaic: width in cells, and height in cells with null meaning "no explicit height" — the same terminal meaning as Renderer::render()'s null leg (the renderer maps the image at its cell aspect), never a hidden per-builder default. |
withDither(Dither $dither): self | Set the dither algorithm for the Sixel renderer. Only takes effect when the built renderer is a SixelRenderer; consult the result with Mosaic::acceptsDither() / Mosaic::ignoredDials() instead of guessing the backend. |
withScale(Scale $scale): self | Set the scale mode for rendering. |
withSixelIntensity(?float $intensity): self | Tune the Ordered/Noise dither bias (0.0..1.0) of the built Sixel renderer; null (the unset default) leaves whatever bias the resolved backend carries. Values above 1.0 clamp to full bias at the setter — this is the same ladder SixelRenderer::__construct() speaks — and NaN or negatives are refused there and then, not at build(). Only takes effect when the built renderer is a SixelRenderer. |
withSixelMaxColors(?int $maxColors): self | Cap the palette budget (1..256 colors) of the built Sixel renderer; null (the unset default) leaves whatever budget the resolved backend carries — an explicitly constructed new SixelRenderer(maxColors: 16) keeps its tuning through an untuned build. Out-of-range budgets are refused at the setter with the renderer's own grammar. Only takes effect when the built renderer is a SixelRenderer. |
sixel(Dither $dither = Dither::FloydSteinberg): self | Configure the builder to use Sixel rendering with an optional dither. |
build(): Mosaic | Build the configured Mosaic. |
Optimization enum
Output-optimization levels for the character-mosaic renderers.
Cases: None · ReuseAttributes · RepeatCells
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
static bits(self ...$levels): int | Fold a set of levels into the int mask the emitters consume. |
static has(int $mask, self $level): bool | Whether $mask carries every bit of $level (None answers false: zero has no flag). |
static all(): int | The full upstream ladder minus the reserved gap: ReuseAttributes|RepeatCells. |
PacedAsyncRenderer final class
Async renderer that pumps an IncrementalRenderer against a slice budget.
| Method | Summary |
|---|---|
__construct(private readonly IncrementalRenderer $renderer, private readonly int $sliceMs = self::DEFAULT_SLICE_MS, private readonly int $rowsPerSlice = PHP_INT_MAX) | |
renderAsync(ImageSource $image, int $width, ?int $height = null): PromiseInterface | Render asynchronously in paced slices, resolving with the full bytes. |
session(ImageSource $image, int $width, ?int $height = null): PacedRenderSession | Open a step-driven pump for the same encode — the test/integration surface: call PacedRenderSession::advanceSlice() at your own cadence (no loop, no wall-clock assumption) and observe progress. |
renderer(): IncrementalRenderer | The wrapped row source. |
sliceMs(): int | Per-slice millisecond budget. |
rowsPerSlice(): int | Per-slice row cap (PHP_INT_MAX = unbounded, clock decides). |
PacedRenderSession final class
One paced, resumable pump over an incremental encode.
| Method | Summary |
|---|---|
__construct(private readonly \Generator $rows, private readonly int $sliceMs, private readonly int $rowsPerSlice) | |
advanceSlice(): string | Run one slice: pull rows while budget remains, appending their bytes. |
advanceUntil(Deadline $pause): bool | Run rows of the open slice until it closes or $pause expires. |
output(): string | All bytes accumulated so far — the full stream once isDone(). |
isDone(): bool | Whether every row has been consumed (idempotent past the last slice). |
sliceCount(): int | Slices run so far — the deterministic progress counter. |
rowsConsumed(): int | Rows pulled from the generator so far. |
PixelGrid final class
Internal: decode a GD image into a 2-D grid of RGB triples at a given cell resolution. Consumers never construct this directly — use a Renderer subclass's own downsampling logic or call fromGd() directly for testing.
| Method | Summary |
|---|---|
static fromGd(\GdImage $img, int $cellW, int $cellH, int $alphaThreshold = 127): self | Resize the source GD image to the target cell grid dimensions and read back the pixel values. |
static fromString(string $bytes, int $cellW, int $cellH, int $alphaThreshold = 127): self | Build a grid from raw GD image bytes (imagecreatefromstring path). Used for testing with fixed PNG fixtures. The $alphaThreshold is alpha hole cut-off, passed straight through to fromGd(). |
static fromGdQuarter(\GdImage $img, int $cellW, int $cellH, int $alphaThreshold = 127): self | Resize the source GD image to cellW*2 × cellH*2 pixels and read back four quadrant values per cell (ul, ur, ll, lr). Used by QuarterBlockRenderer for 2×2 sub-pixel rendering. |
PlacedImage final readonly class
The outcome of an ImageLayer::placeTracked() call: the marker block to compose into the frame, plus the overlay id the layer assigned to the bytes.
| Method | Summary |
|---|---|
__construct(public string $marker, public ?int $imageId) |
PngMetadata final class
PNG container codec for the A1111 infotext round-trip — no SD server, no library, pure byte work over the chunk framing of ISO/IEC 15948.
| Method | Summary |
|---|---|
static isPng(string $bytes): bool | Magic sniff: eight fixed signature bytes, nothing more. |
static readText(string $pngBytes, string $keyword = self::KEYWORD_PARAMETERS): ?string | Extract the text stored under $keyword, or null for ANY unfavourable shape: not a PNG, oversized, truncated tail, CRC-mismatched chunk, malformed text chunk, compressed iTXt that will not inflate (including one that would inflate past MAX_TEXT_BYTES), a text payload over that ceiling, or simply absent keyword. Never throws (reader resilience law). |
static writeText(string $pngBytes, string $keyword, string $text, ?string &$strategy = null): string | Return the PNG with $keyword carrying $text: an existing tEXt/iTXt chunk with that keyword is REPLACED in place — never appended as a duplicate — and every other chunk keeps its bytes and ordering untouched, including trailing bytes after IEND. No matching chunk → a new one is inserted immediately before IEND. |
static setInfotext(string $pngBytes, string $text): string | Stamp the full infotext block: $text becomes the parameters chunk (in place, per the replacement law) and an already-present prompt chunk is re-synced to the first line of the text — the A1111 pair law ("parameters" tEXt carries everything, "prompt" iTXt carries the bare prompt). A file without a prompt chunk is not given one: the minimal-diff / preservation law outranks minting upstream's newer companion chunk on our stamps. |
static stamp(string $pngBytes, string $text): string | Stamp an infotext block into a PNG (pure byte transform): $text becomes the parameters chunk and an existing prompt chunk is re-synced to the text's first line. Alias of setInfotext(). |
static extract(string $pngBytes): array | Read both A1111 keywords at once. A missing keyword, or any damaged / non-PNG input, yields null for that entry; never throws. |
static strategyFor(string $text): string | Strategy law in one place (W1.7 step 2): ASCII rides tEXt; non-ASCII that is legal UTF-8 rides compressed iTXt; raw 8-bit bytes that are not valid UTF-8 (a legacy latin-1 dump) ride tEXt verbatim — exactly "A1111 writes tEXt with the raw str", since iTXt text must be UTF-8. |
PngPixels final class
Pure-PHP PNG pixel decoder for still images, with no GD quantisation.
| Method | Summary |
|---|---|
static decode(string $bytes, int $maxPixels = self::MAX_PIXELS): ?RawRgba | Decode the base image of a PNG stream to straight-alpha RGBA8. |
PrecomputedImage final class
A precomputed rendered image — holds the encoded ANSI bytes and the target cell dimensions so the caller knows the layout.
| Method | Summary |
|---|---|
__construct(private readonly string $bytes, private readonly int $cellWidth, private readonly int $cellHeight) | |
bytes(): string | |
cellWidth(): int | |
cellHeight(): int |
Quantizer final class
Pairwise Nearest Neighbour (PNN) palette quantizer.
| Method | Summary |
|---|---|
static bitsForQuality(int $quality): int | The histogram resolution chafa's -w rung selects. |
static build(array $samples, int $nCols = 255, int $bitsPerCh = 4): array | Build a palette from raw RGB samples. |
Scale enum
Image scaling / cropping modes used when rendering into a fixed cell grid.
Cases: Fit · ShrinkToFit · Fill · Stretch · None · Crop
PHP also provides cases().
| Method | Summary |
|---|---|
static fromName(string $name): ?self | Parses a --scale spelling into its mode. This is the single name table for the scale vocabulary: every frontend (candy-image's --scale flag, and any other caller) resolves names here rather than keeping its own map, so the spellings cannot drift apart. |
computeDimensions(int $srcW, int $srcH, int $dstW, int $dstH): array | Compute source crop rect and destination dimensions for this scale mode. |
SpriteSheet final class
A grid of equally sized tiles packed into one image (a trickplay or storyboard sheet), read tile by tile in row-major order.
| Method | Summary |
|---|---|
static fromSource(ImageSource $sheet, int $cols, int $rows): self | |
count(): int | Number of tiles in the grid. |
tile(int $index): ImageSource | Tile $index, row-major from the top-left: 0 is the first cell of the first row, $cols - 1 the last cell of that row. |
SyncAsyncRenderer final class
Synchronous async renderer — DEFERS the encode to the next event-loop tick, but does not YIELD it back.
| Method | Summary |
|---|---|
__construct(private readonly Mosaic $mosaic) | |
renderAsync(ImageSource $image, int $width, int $height): PromiseInterface |
TermDb final class
The declarative terminal database — chafa's built-in term table ported to SugarCraft.
| Method | Summary |
|---|---|
static snapshotEnv(): array | Read the environment variables the table consults, as a key=>value map with unset keys absent. The only getenv site in the table. |
static matchChain(array $env): TermInfo | Resolve an environment snapshot to the chained terminal info. |
static parseVersion(string $version): int | Digits-only version folding — chicle's parse_version (:907-954): "1.2.3" → 123, "XTerm(388)" → 388, "next-3.6" → 36. Versions with more digits compare above versions with fewer, so 3.10 (310) > 3.4 (34) > 3.3 (33) without any per-field math. |
TermInfo final class
One resolved terminal identity from the TermDb table.
| Method | Summary |
|---|---|
__construct(public readonly string $chain, public readonly array $claims, public readonly array $passthrough, public readonly ?string $mux, public readonly int $safeSymbols = self::ALL_SYMBOLS, public readonly int $quirks = self::QUIRK_NONE) | |
static unknown(): self | No row matched at all — the environment says nothing about pixels. |
supports(string $protocol): bool | |
symbolIsSafe(int $classes): bool | Whether every symbol class in $classes is safe to draw on this chain. Pass one SYMBOL_* constant, or a union to require all of them. ASCII is always safe on any SugarCraft output path (7-bit bytes reach every seat the table knows about); the bit exists so the restricted presets can be spelled exactly like chicle's (LINUX_CONSOLE_SYMS). |
needsPassthrough(string $protocol): bool | Whether $protocol only reaches the screen wrapped in the mux passthrough sequence (\e Ptmux;…\e \\ or \e P…\e \\). False = the chain renders it natively — chicle's pixel_passthrough_needed table (chafa-term-db.c :474-490: tmux 3.4+ flips the SIXELS entry to FALSE because tmux decodes sixels itself). |
hasPixelProtocol(): bool | |
hasQuirk(int $quirk): bool | Whether one QUIRK_* bit is armed on this chain. |
passthroughMode(): string | Which passthrough envelope the matched MUX row demands — tmux rows pass CHAFA_PASSTHROUGH_TMUX (chafa-term-db.c:810/:818), the screen row passes CHAFA_PASSTHROUGH_SCREEN (:786-789); with no mux link there is nothing to envelope. The mux label from TermDb::rowLabel() ("tmux", "tmux 3.4", "screen") decides by prefix, so a versioned row keeps its parent's protocol. |
Timeline final class
Maps a playback position to the sprite tile that covers it: a clip of $durationSeconds split into $tiles equal slices, tile i covering [i * step, (i + 1) * step) where step = duration / tiles.
| Method | Summary |
|---|---|
static new(int $tiles, float $durationSeconds): self | |
tileAt(float $sec): int | The tile index covering playback position $sec. |
TmuxPassthrough final class
Transactional tmux allow-passthrough management.
| Method | Summary |
|---|---|
static ensure(): bool | Flip allow-passthrough on for this pane if it is not already passing through, remembering the prior state for retire(). |
static retire(): bool | Restore what ensure() changed. Safe to call any number of times; a retire with nothing to restore succeeds without touching a process. |
static isApplied(): bool | Whether the transaction is currently open (ensure() landed, retire() has not). Introspection for callers that bracket rendering themselves. |
TmuxPassthroughDecorator final class
Renderer decorator that wraps output in tmux's passthrough protocol.
| Method | Summary |
|---|---|
__construct(private readonly Renderer $inner) | |
inner(): Renderer | The wrapped renderer — lets callers reach protocol-specific behaviour (dither, palette size) through the passthrough envelope. |
decorate(Renderer $inner): Renderer | |
render(ImageSource $image, int $width, ?int $height = null): string | |
encodeBandStream(ImageSource $image, int $width, callable $write, ?int $height = null): void | Stream a Sixel render through the tmux passthrough envelope. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool | |
name(): string | |
supportsAlpha(): bool | |
isInline(): bool | |
delete(string $imageId): string | |
wrap(string $ansi): string | Wrap raw ANSI bytes in the tmux passthrough envelope. |
UnsupportedFormatException final class
Thrown when a container is recognised by magic bytes but carries a feature (or codec) this library does not decode.
SugarCraft\Image\Codec
RawRgba final class
Kitty graphics protocol f=32 raw RGBA encoder — GD-free by design.
| Method | Summary |
|---|---|
static new(int $width, int $height, string $rgba): self | Wrap a w×h RGBA8 buffer, validated by validate(). |
static fromPixels(array $pixels): string | Serialise a pixel list (each R | G<<8 | B<<16 | A<<24) to wire bytes. |
static fromGdImage(\GdImage $img): string | Read a truecolor GD image into wire-order RGBA bytes. |
static validate(string $rgba, int $width, int $height): string | Fail fast when a raw payload does not describe exactly w×h quads. |
TiffUncompressed final class
Minimal uncompressed-TIFF encoder — the GD-free iTerm2 payload.
| Method | Summary |
|---|---|
static encode(string $rgba, int $width, int $height): string | Wrap an RGBA byte buffer (w×h×4, row-major, unassociated alpha) in a single-strip uncompressed TIFF. |
SugarCraft\Image\Concerns
ForceTrueColor final class
The one truecolor gate for every GD image this lib reads pixels from.
| Method | Summary |
|---|---|
static convert(\GdImage $image): void | Convert a palette image to truecolor in place, or refuse loudly. |
ImageSourceRgbFallback trait
Default \SugarCraft\Image\Renderer\Renderer raw-pixel and frame-present methods for backends whose output has no id-addressable frame.
| Method | Summary |
|---|---|
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool |
OptimizationCarrierTrait trait
Carrier for the Optimization bit mask on the cell-mosaic renderers (house immutable style: with*() clones, the field is only ever written on a fresh instance).
| Method | Summary |
|---|---|
withOptimizations(int $mask): static | |
optimizations(): int |
RenderValidationTrait trait
Shared validation and height-computation for renderers.
ResolvesRawPixelsTrait trait
Shared "obtain a raw RGBA buffer for an ImageSource" step for the GD-free transmission paths.
SugarCraft\Image\Dither
Ditherer final class
The shared dithering stage — error diffusion and bias texture lifted out of \SugarCraft\Image\Renderer\SixelRenderer::indexRows() so the block/character renderers can consume the same math chafa runs in its common prepare_pixels pass (chafa-pixops.c), not sixel-only.
| Method | Summary |
|---|---|
__construct(private readonly Dither $dither = Dither::FloydSteinberg, private readonly ?OrderedTexture $texture = null, private readonly ?float $intensity = null, private readonly int $alphaThreshold = 127, private readonly ?Color $flattenBackground = null, private readonly bool $serpentine = false, private readonly int $grainWidth = 1, private readonly int $grainHeight = 1, private readonly bool $serpentineErrorFold = false) | |
grainWidth(): int | Grain dimensions in source pixels (1x1 = per-pixel walk). |
grainHeight(): int | |
serpentineErrorFold(): bool | True when the edge-grain tap fold is armed. It has no effect unless serpentine() is armed as well — the walk honours the pair, not the flag alone. |
serpentine(): bool | |
static noiseMagnitude(?float $intensity): float | Noise bias magnitude — chafa's chafa_dither_init() NOISE arm, chafa_gen_noise_matrix (dither->intensity * 0.1f), with the base intensity left at 1.0: chafa-canvas.c (:591-614) applies the depth ladder to ORDERED only, so Noise never sees a maxColors-derived factor. |
static flattenOnto(int $r, int $g, int $b, int $alpha, Color $bg): array | Src-over composite of one pixel's RGB toward the flatten background, on GD's inverted alpha scale (0 = opaque, 127 = fully transparent), so background weight is alpha / 127. |
indexRows(\GdImage $img, array $palette, int $offset, int $yOrigin = 0): \Generator | Yield the index grid one row at a time, keyed by absolute row index. |
static lumaIndexRows(array $lumaRows, callable $quantize, Dither $dither, float $intensity = 1.0, ?OrderedTexture $texture = null, bool $serpentine = false, bool $fold = false): \Generator | Per-luma error diffusion for scalar (one-channel) renderers — the ascii ramp threshold and, since the block-walk landed, per-cell block luma. Mirrors chafa's structure of dithering the value the picker will threshold (chafa dithers before the symbol/palette choice, never after), which is what the "FS before the LumaRamp threshold" requires. |
static diffuseError(array &$accum, int $w, int $h, int $x, int $y, float $eR, float $eG, float $eB, Dither $dither, int $dxSign = 1, bool $fold = false): void | Diffuse quantization error to future (unprocessed) neighbors. |
SugarCraft\Image\Levels
LevelsStretch final class
Chafa's prepare_pixels auto-levels pass — histogram-driven per-channel stretch plus a saturation lift, ported to GD in place.
| Method | Summary |
|---|---|
static stretch(\GdImage $img, int $maxColors, int $alphaThreshold = 127): void | Apply the full pass-1 → bounds → pass-2 sequence to $img in place. |
static boost(array $rgb): array | Saturation lift for one pixel — public because it is a usable colour primitive on its own (and the testable core of the stretch math). Faithful to boost_saturation_rgb with the corrected weights: P = sqrt(Σ w·c²), then ch = P + (ch − P)·2 truncated to int and clamped, exactly as the C assignment did. |
static intensity(int $r, int $g, int $b): int | rgb_to_intensity_fast — weighted sum to 8× so the bin index divides back by shifting. Sums to 2040 max, inside the bin count. |
static cropPct(int $maxColors): int | Crop percentage for the renderer rung — chafa's palette switch: FIXED_16 → 5 %, FIXED_8 → 10 %, everything else → 20 %. |
SugarCraft\Image\Passthrough
PassthroughDecorator interface
Common surface of the two passthrough envelopes.
| Method | Summary |
|---|---|
wrap(string $ansi): string | Rewrite a complete ANSI byte string so every control-sequence run it contains travels through the multiplexer intact. |
inner(): Renderer | The renderer being enveloped (unwrapping for configuration sites). |
decorate(Renderer $inner): Renderer | Wrap a reconfigured renderer in THIS envelope flavour — how Mosaic's with*() sites re-apply the decorator after swapping the inner one, polymorphically and without instanceof ladders over concrete classes. |
ScreenPassthrough final class
GNU Screen passthrough envelope for a nested renderer.
| Method | Summary |
|---|---|
__construct(private readonly Renderer $inner) | |
inner(): Renderer | |
decorate(Renderer $inner): Renderer | |
render(ImageSource $image, int $width, ?int $height = null): string | |
delete(string $imageId): string | |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool | |
name(): string | |
supportsAlpha(): bool | |
isInline(): bool | |
wrap(string $ansi): string | Frame a complete ANSI string into Screen passthrough packets. |
encodeBandStream(ImageSource $image, int $width, callable $write, ?int $height = null): void | Stream band chunks through the same packetizer state machine wrap() uses, so the concatenation of $write bytes is byte-for-byte equal to render()'s wrapped output no matter where the chunk boundaries fall (the SixelStreamTest twin law, inherited here). Only a nested SixelRenderer can stream; any other inner renderer under a streaming request is a programming error, same posture as the tmux decorator. |
SugarCraft\Image\Render
Bands final class
Unit-aligned band partition — splits a pixel/cell row range into [startRow, endRow) half-open band specs, the shape a later per-band worker pool or incremental pump consumes. Pure utility: it owns no render state and no renderer calls it yet, so landing it cannot move a single output byte (the DoD of this step).
| Method | Summary |
|---|---|
static partition(int $totalRows, int $unit = self::SIXEL_UNIT, int $maxBands = 1): array | Partition rows [0, $totalRows) into unit-aligned bands. |
SugarCraft\Image\Renderer
AcceptsOptimization interface
Optional contract for renderers whose OUTPUT BYTES are configured by the Optimization ladder rather than by constructor-time state.
| Method | Summary |
|---|---|
withOptimizations(int $mask): Renderer | Return a copy emitting under $mask (an Optimization::bits() fold). Immutable: the receiver is unchanged. |
optimizations(): int | The currently configured optimization mask. |
AsciiColorMode enum
Colour treatment for the AsciiRenderer: each pixel becomes a luminance character, optionally tinted.
Cases: Mono · Ansi256 · Ansi16 · TrueColor
PHP also provides cases(), from() and tryFrom().
AsciiRenderer final class
ASCII / ANSI renderer — maps each pixel to a luminance character, optionally tinted (see AsciiColorMode).
| Method | Summary |
|---|---|
__construct(private readonly AsciiColorMode $color = AsciiColorMode::TrueColor, private readonly string $ramp = self::RAMP, ?float $intensity = null, private readonly Dither $dither = Dither::None, private readonly bool $serpentine = false) | Opt-in luminance dithering — chafa dithers inside the common prepare_pixels pass, BEFORE the picker thresholds the value, and this renderer had no error control at all (without it, gradients band). Dither::None (default) keeps the byte-frozen cold-quantise walk; the ramp default is what every existing golden pins. |
dither(): Dither | The diffusion kernel in force (Dither::None = cold quantise). |
intensity(): ?float | The dither bias strength in force, or null for chafa's 1.0. |
serpentine(): bool | True when the diffusion walk snakes (odd cell rows reversed). |
render(ImageSource $image, int $width, ?int $height = null): string | |
name(): string | The protocol slot carries the protocol, not the colour ramp. All three AsciiColorMode arms encode through the same ASCII-symbol protocol, so name() is the constant 'ascii'; the colour depth a particular renderer instance encodes at is its own axis, exposed by colorMode() for cache-key discriminators and future callers. |
colorMode(): AsciiColorMode | The colour-ramp mode this renderer encodes with (Mono/Ansi16/Ansi256/TrueColor). Relocated this value out of name() so protocol() stops leaking 'ansi256'/'truecolor' into the PROTOCOL slot; anything that previously differentiated ascii variants by name() must key on this. |
supportsAlpha(): bool | |
isInline(): bool | |
delete(string $imageId): string | Plain-text SGR output — no stored image identity to delete. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool | |
withOptimizations(int $mask): static | |
optimizations(): int |
CanvasModeConfigurable interface
Optional capability: the renderer's colour canvas is a dial the host can flip after construction. PHP interfaces cannot carry default bodies, so instead of widening Renderer every backend that speaks canvas modes declares this interface and the single Mosaic call site checks for it — every other implementer keeps compiling untouched (house precedent: ConfigFingerprintProvider).
| Method | Summary |
|---|---|
withCanvasMode(CanvasMode $mode): Renderer | Immutable switch onto a fixed-palette canvas; returns a new instance. |
canvasMode(): CanvasMode | The canvas mode currently in force. |
ChafaBinary final class
Single source of truth for locating the chafa binary.
| Method | Summary |
|---|---|
static path(): ?string | Absolute path to chafa, or null when no gate-passing binary resolves. |
ChafaRenderer final class
Chafa graphics renderer — invokes the chafa command-line tool.
| Method | Summary |
|---|---|
__construct(private readonly array $options = [], private readonly ?string $format = null) | |
static available(): bool | Whether a gate-passing chafa binary resolves and answers --version. Resolution is the ChafaBinary roster/override choke — a bare PATH chafa is deliberately NOT executed. Probed once per process (the result is memoised) so a per-frame video render does not spawn a probe each frame. |
renderAsync(ImageSource $image, int $width, ?int $height = null, ?LoopInterface $loop = null): PromiseInterface | Off-loop twin of render() (rank 74): the chafa child runs through ChildRun::launch() on $loop, so the loop keeps serving its other watchers while the encode is in flight, instead of parking in a blocking drain and a usleep reap. |
render(ImageSource $image, int $width, ?int $height = null): string | |
name(): string | |
configFingerprint(): string | The CLI options and the output format both change chafa's encoded bytes for identical input, so both ride the fingerprint — Mosaic::chafa('--colors=16') must never serve a '--colors=256' cache entry (or a symbols-format one) back. |
static reset(): void | Reset the memoised availability check AND the memoised binary resolution, so a later call re-reads ChafaBinary::ENV_OVERRIDE and re-scans the roster. |
supportsAlpha(): bool | |
isInline(): bool | |
delete(string $imageId): string | Chafa invokes an external command — no persistent image identity to delete. Returns the empty string. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool |
ConfigFingerprintProvider interface
Optional capability interface for renderers whose construction-time config changes the encoded bytes beyond what Renderer::name() identifies.
| Method | Summary |
|---|---|
configFingerprint(): string | Stable, human-debuggable encoding of every construction config that changes the bytes this renderer emits for otherwise-identical input (key=value segments joined with '|'). Two instances with equal fingerprints must be byte-equivalent encoders; differing configs must yield differing fingerprints. |
HalfBlockRenderer final class
Text-tier fallback renderer for sighted readers, using Unicode half-block (▀) with 24-bit foreground + background SGR codes. Each terminal cell shows two vertically-stacked pixel rows: the upper pixel's colour as foreground, the lower pixel's colour as background, rendered as one ▀ glyph.
| Method | Summary |
|---|---|
render(ImageSource $image, int $width, ?int $height = null): string | |
renderRows(ImageSource $image, int $width, ?int $height = null): \Generator | Yield the frame one display row at a time. |
name(): string | |
supportsAlpha(): bool | |
isInline(): bool | |
delete(string $imageId): string | Half-block rendering uses plain text SGR codes — no stored image identity to delete. Returns the empty string. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool | |
withOptimizations(int $mask): static | |
optimizations(): int |
IncrementalRenderer interface
Optional capability interface for renderers that can emit their bytes one row (or frame) at a time instead of materialising the whole encode.
| Method | Summary |
|---|---|
renderRows(ImageSource $image, int $width, ?int $height = null): \Generator | Encode the image lazily, yielding byte chunks in append order. |
Iterm2Renderer final class
iTerm2 / WezTerm inline image renderer via OSC 1337.
| Method | Summary |
|---|---|
render(ImageSource $image, int $width, ?int $height = null): string | |
name(): string | |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | Raw RGBA straight to an uncompressed TIFF, with no PNG container. |
renderTiff(ImageSource $image, int $width, ?int $height = null, ?string $rgba = null): string | Transmit as an uncompressed TIFF (type=tiff) — the GD-free wire format. |
supportsAlpha(): bool | |
isInline(): bool | |
delete(string $imageId): string | Remove the most recently displayed iTerm2 / WezTerm image. |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool |
KittyRenderer final class
Kitty graphics protocol renderer via chunked APC sequences.
| Method | Summary |
|---|---|
render(ImageSource $image, int $width, ?int $height = null): string | Render an image as a Kitty graphics protocol sequence. |
renderRows(ImageSource $image, int $width, ?int $height = null): \Generator | Yield the transmission one protocol frame at a time. |
name(): string | |
renderWithOptions(ImageSource $image, int $width, ?int $height, KittyOptions $opts): string | Render with explicit Kitty protocol options. |
supportsAlpha(): bool | |
isInline(): bool | |
delete(string $imageId): string | Remove a previously rendered image by its numeric id. |
renderFrame(ImageSource $image, int $width, ?int $height, int $imageId): string | Render a single animation frame with a stable image id. |
renderUncompressed(ImageSource $image, int $width, ?int $height = null, ?string $rgba = null): string | Transmit as RAW RGBA (f=32) — the GD-free wire format. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | Transmit a raw RGBA8 buffer without building a PNG container. |
renderRgbFrame(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height, int $imageId): string | Transmit a raw RGBA8 buffer under a caller-owned image id. |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | Draw $imageId, then retire $prevId once the new frame is on screen. |
supportsIdDelete(): bool |
OrderedTexture final class
Ordered-dither bias texture — an additive PRE-QUANTIZATION offset consulted per pixel before the palette lookup, with no error feedback (this is chafa's bias model, not a matrix-threshold model).
| Method | Summary |
|---|---|
static bayer16(float $magnitude): self | Generate the 16×16 Bayer texture chafa uses for CHAFA_DITHER_MODE_ORDERED (TEXTURE_DIM_SHIFT 4 in chafa-dither.c; magnitude is the already-folded dither intensity). |
static blueNoise64(float $magnitude): self | The 64x64 three-channel blue-noise texture chafa uses for CHAFA_DITHER_MODE_NOISE. Mirrors chafa_gen_noise_matrix() (chafa-noise.c:225-238): matrix[i] = ((gfloat) blue_noise_src[i] - 128.0f) * magnitude + 0.5f -> gint, ported with the same symmetric-rounding deviation documented on the class. |
mod(int $x, int $y, int $channel): int | The texture offset for one pixel channel, tiling with a wrap mask — chafa_dither_pixels() phases rows by y >> grain_height_shift and columns by x >> grain_width_shift; the grain defaults to one pixel (calc_grain_shift(1) == 0), so both shifts are zero here and only the mask remains. |
QuarterBlockRenderer final class
Quarter-block Unicode renderer using 16 glyphs (▘▝▖▗▀▄▌▐▙▟▛▜▞▚█). Each terminal cell renders a 2×2 group of pixels; the glyph selection encodes which quadrants are bright via foreground colour and which are dim via background colour (both drawn from the same image pixel).
| Method | Summary |
|---|---|
canvasMode(): CanvasMode | |
configFingerprint(): string | Non-default canvas only: the default rung fingerprints as '' so existing poster-cache keys never churn. |
withCanvasMode(CanvasMode $mode): self | Fixed-palette canvas mode. TrueColor is the historical default and stays byte-identical; the limited palettes snap the candidate pens before error scoring — the same rule chafa applies to its canvas (CanvasMode) — and emit snapped SGR. |
render(ImageSource $image, int $width, ?int $height = null): string | |
name(): string | |
supportsAlpha(): bool | |
isInline(): bool | |
delete(string $imageId): string | Quarter-block rendering uses plain text SGR codes — no stored image identity to delete. Returns the empty string. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool | |
withOptimizations(int $mask): static | |
optimizations(): int |
Renderer interface
Contract for image-to-terminal renderers.
| Method | Summary |
|---|---|
render(ImageSource $image, int $width, ?int $height = null): string | Render $image into ANSI bytes at the given cell dimensions. |
name(): string | Stable backend identifier: 'sixel' | 'kitty' | 'iterm2' | 'chafa' | 'halfblock' | 'quarterblock' | 'ascii' | 'symbols'. |
supportsAlpha(): bool | True if this backend supports partial transparency (alpha channel). The graphics tiers (Sixel, Kitty, iTerm2, Chafa) do; the text tiers (half-block, quarter-block, ASCII, symbol map) do not. |
isInline(): bool | True if render() produces inline cell text — newline-separated rows, one terminal line per cell row — that can be placed directly in a text frame and stitched beside other content (half-block, quarter-block, ASCII, symbol map, and Chafa). |
delete(string $imageId): string | Emit the protocol-specific sequence to delete a previously rendered image identified by $imageId. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | Render a raw straight-alpha RGBA8 buffer (\SugarCraft\Image\Codec\RawRgba layout: $pixelWidth × $pixelHeight × 4 bytes, rows top to bottom). |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | Emit one frame of a sequence that may be re-displayed later. |
supportsIdDelete(): bool | True when delete() removes one specific frame by its id, so a replaced frame can be retired after the new one is on screen. Kitty only: iTerm2's delete pops the topmost image and Sixel has no delete at all. |
SixelRenderer final class
Sixel graphics renderer — DEC sixel to terminal.
| Method | Summary |
|---|---|
__construct(private readonly Dither $dither = Dither::FloydSteinberg, private readonly int $maxColors = 256, private readonly int $cellWidth = 10, private readonly int $cellHeight = 20, ?float $intensity = null, private readonly int $alphaThreshold = self::DEFAULT_ALPHA_THRESHOLD, private readonly ?Color $flattenBackground = null, private readonly bool $serpentine = false, private readonly bool $mltermEdgeRows = false, private readonly ?int $quality = null, private readonly bool $autoLevels = false, private readonly ?int $quirks = null) | |
render(ImageSource $image, int $width, ?int $height = null): string | |
encodeBandStream(ImageSource $image, int $width, callable $write, ?int $height = null): void | Stream the Sixel encoding one 6-pixel-tall band at a time. |
name(): string | |
supportsAlpha(): bool | Sixel supports transparent backgrounds via the #0;2;P background register: fully-transparent pixels are left unpainted and show the terminal's own background. See render(). |
isInline(): bool | |
delete(string $imageId): string | Sixel has no standard delete mechanism — DECSIXEL does not support removing individual images after emission. Returns the empty string. |
dither(): Dither | |
configFingerprint(): string | Every ctor config that changes the encoded bytes rides the fingerprint — dither arms the index grid differently, maxColors changes the palette, and the cell-pixel geometry resamples to a different pixel canvas, so two SixelRenderers named 'sixel' with any of these differing must never cross-serve a poster cache entry. |
withDither(Dither $dither): self | A copy of this renderer using $dither, keeping its colour budget, bias intensity and cell-pixel geometry — so re-tinting a configured Sixel (custom maxColors or real terminal cell sizes) never silently resets them. |
withIntensity(?float $intensity): self | A copy of this renderer using $intensity as its dither bias, keeping the dither algorithm, color budget and cell geometry. Refusals come from the constructor's own grammar (NaN and negatives rejected by name); values above 1.0 clamp to full bias, and null releases the tuning entirely — back to the chafa-config default ladder, the byte-frozen legacy shape. |
withMaxColors(int $maxColors): self | A copy of this renderer quantising its palette to at most $maxColors entries — same keep-everything-else contract as withDither(); out-of-range budgets are refused by the constructor ladder before any copy exists. |
alphaThreshold(): int | The GD-alpha hole cut-off in force (0..127; 127 = only fully transparent pixels are holes, the older behaviour). |
flattenBackground(): ?Color | The flatten background in force, or null when semi-transparent pixels keep their stored colour. |
withAlphaThreshold(int $threshold): self | Copy with a different alpha threshold: pixels whose GD alpha reaches $threshold become background holes, and the hole decision happens before the pixel ever enters the palette census or the diffusion stream (chafa quantize_pixel skip semantics, chafa/internal/chafa-indexed-image.c:117-125 — lowered thresholds also shed semi-transparent fringe colours from median-cut buckets, the counterpart of chafa's MAX(alpha_threshold,1) sampler guard). 127 is byte-identical to the historical === 127 hole test; the extreme 0 declares every pixel (opaque included) a hole — legal, but the encode paints nothing. |
withFlatten(?Color $background): self | Opt-in pre-sampling flatten — every semi-transparent pixel (0 < alpha < threshold) is composited toward $background inside the base read, BEFORE quantisation or diffusion touch it, so the encoder dithers the colour the terminal will actually show instead of the raw un-premultiplied fringe (which is typically near-black — the dark-halo defect). null (default) disables flattening entirely. |
serpentine(): bool | True when the diffusion walk snakes (odd rows reversed). |
withSerpentine(bool $serpentine = true): self | Copy with the serpentine scan armed. Only diffusion dithers are affected — Ordered is a position-taken bias and None has no walk to reverse, so both render byte-identically with or without it. |
mltermEdgeRows(): bool | True when the mlterm first/last-row quirk is armed. |
withMltermEdgeRows(bool $mltermEdgeRows = true): self | Copy with the mlterm edge-band quirk armed. The quirk only ever fires on a canvas that carries the transparent background register (offset 1) whose global first or last band encodes to nothing at all; those bands then draw a full-width zero-bit run on register 0 so the graphics position advances across the whole row. Off by default until the TermDb table can select it per terminal. |
withCellSize(int $cellWidth, int $cellHeight): self | Copy sized to a probed terminal cell rather than the constructor's conventional 10×20. |
withQuirks(?int $quirks): self | Copy armed from a terminal-database quirks bitmask (TermInfo::QUIRK_*). Two chicle consumers re-home here: QUIRK_MLTERM_EDGE_ROWS arms the full-width edge-band forcing (the flag's "auto-enabling belongs to the TermDb capability table" home promised in its docblock), and the ABSENCE of QUIRK_SIXEL_OVERSHOOT on a KNOWN terminal makes the encoder append the parking newline chafa writes at chafa.c:445-451 — a terminal with the quirk parks its own cursor a row below the final band and needs nothing extra. Passing QUIRK_NONE is a positive fact ("chain consulted, no quirks") and still earns the parking newline; only the never-polled null default keeps the legacy bytes frozen. |
quirks(): ?int | The armed quirks mask, null when the terminal was never consulted (the byte-frozen default). |
hasQuirk(int $quirk): bool | Whether one QUIRK_* bit is armed. Null quirks answers false for every bit — no facts, no quirk-driven bytes. |
parkingNewline(): string | The parking newline chafa.c:445-451 appends after sixel output when the terminal is KNOWN not to overshoot its cursor. Returns '' for the frozen null default and for overshooting terminals. |
quality(): ?int | The PNN quality rung in force (1-9), or null when the renderer quantises with median-cut — the byte-frozen default. |
autoLevels(): bool | Chafa's --preprocessing auto-levels in force — the fast-intensity histogram bounds, per-channel stretch, and Rec.709 saturation lift run before the palette census (see LevelsStretch()). Default OFF: every byte-frozen digest predates the pass. |
withAutoLevels(bool $autoLevels = true): self | A copy using (or not using) the auto-levels pass, keeping every other dial. |
withQuality(int $quality): self | Copy on a different rung of the chafa -w ladder (1-9). Arming it routes palette construction through Quantizer when the sample census outweighs the colour budget; every other setting rides along. The default path never calls this, so default bytes are untouched. |
maxColors(): int | The maximum number of colors in the quantized Sixel palette. |
intensity(): ?float | The Ordered/Noise dither bias in force (0.0..1.0), or null when the renderer runs the chafa-config default ladder untouched. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool |
SixelRows final class
Row-at-a-time view over a SixelRenderer.
| Method | Summary |
|---|---|
__construct(private readonly SixelRenderer $renderer) | |
renderRows(ImageSource $image, int $width, ?int $height = null): \Generator | |
renderer(): SixelRenderer | The wrapped one-shot renderer — parity reference for consumers. |
SymbolMapRenderer final class
Coverage-class symbol renderer — the 'symbols' tier.
| Method | Summary |
|---|---|
__construct(?SymbolMap $map = null, ?string $defaultFg = null, ?string $defaultBg = null) | |
withWorkFactor(float $workFactor): self | chafa's work-factor dial: 0..1, clamped. The config float maps to chafa's integer (int)(wf*10 + 0.5); values >= 8 run the exhaustive slow path (every corpus symbol, direct coverage only — chafa-symbol-renderer.c), smaller values narrow the search to the top-candidateLimit() Hamming candidates (with the inverse trial riding along). Default 0.5 keeps the pre-dial behaviour byte-identical. |
workFactor(): float | |
canvasMode(): CanvasMode | |
withSymbolSelectors(string $selectors): self | Select the glyph corpus with chafa's --symbols= tag grammar (SymbolMap::withSelectors()). The default corpus (the base 676 entries) stays byte-frozen; a selector widens the map to the full 1,260-glyph narrow array (1,251 under the BAD-vetoing all) or narrows it to one class family. An invalid expression throws at configuration time. |
symbolSelector(): ?string | |
configFingerprint(): string | Only non-default rungs fingerprint: the default (TrueColor, work 0.5) reports '' so existing poster-cache keys never churn. |
withCandidateObserver(?\Closure $observer): self | Deterministic op-counter seam: called once per scored cell as fn(bool $exhaustive, int $evaluated, string $winner, int $bestError). Timing-fragile pins are banned repo-wide, so the work-factor dial is measured through this observer instead of wall clock. |
static workFactorToInt(float $workFactor): int | The raw chafa integer step: (int)(wf*10+0.5) over the clamped dial. |
static isExhaustiveWorkFactor(float $workFactor): bool | True when the raw step reaches chafa's exhaustive slow-path flag. |
static candidateLimit(float $workFactor): int | Candidate window size: the raw step clamped into chafa's 1..8. |
withCanvasMode(CanvasMode $mode): self | Select the fixed-palette canvas mode. TrueColor (the default) reproduces the original byte output exactly; the limited palettes snap the scoring pens BEFORE the candidate error sum — a 16-colour terminal must pick the best glyph FOR THAT PALETTE — and emit the snapped pens (Fgbg emits none, riding terminal defaults). Chafa counterpart: chafa-canvas.c update_cell palette dispatch + use_quantized_error. |
render(ImageSource $image, int $width, ?int $height = null): string | |
name(): string | |
supportsAlpha(): bool | |
isInline(): bool | |
delete(string $imageId): string | Symbol-map rendering is plain SGR text — no stored image identity. |
renderRgb(string $rgba, int $pixelWidth, int $pixelHeight, int $width, ?int $height = null): string | |
present(ImageSource $image, int $width, ?int $height, string $imageId, ?string $prevId): string | |
supportsIdDelete(): bool | |
withOptimizations(int $mask): static | |
optimizations(): int |
WorkFactorConfigurable interface
Optional capability: the renderer exposes chafa's work-effort dial — 0.0 spends the least per cell (single best Hamming candidate), 1.0 scores the whole corpus. Same interface-cannot-have- bodies rationale as CanvasModeConfigurable: Mosaic delegates only when the active backend declares this.
| Method | Summary |
|---|---|
withWorkFactor(float $workFactor): Renderer | Immutable dial set (clamped into chafa's 0..1 config range). |
workFactor(): float | The dial currently in force. |
SugarCraft\Image\Support
GdAvailability final class
Single decision point for "is the GD extension usable right now".
| Method | Summary |
|---|---|
static available(): bool |
OutputOptimizer final class
Streaming SGR pen-delta optimizer for character-mosaic emitters.
| Method | Summary |
|---|---|
static trueColor(int $r, int $g, int $b): string | Normalized SGR parameters for a 24-bit colour. |
static indexed256(int $index): string | Normalized SGR parameters for a 256-palette index. |
__construct(private readonly ?string $entryForeground = null, private readonly ?string $entryBackground = null, private readonly bool $repeatCells = false) | |
cell(string $glyph, ?string $foreground = null, ?string $background = null): void | Append a coloured cell, emitting SGR only for channels that change. |
blank(): void | Append a blank cell: foreground copied from the previous cell (zero bytes), background dropped back to the entry style. |
attribute(string $channel, bool $on): void | Switch an attribute channel on (or back to the entry/off state with null). |
finishRow(): string | Close the current row: restore the entry pen (scoped resets, never an ESC[0m clobber) and return the row's bytes. Pen state is back at the entry style afterwards, so the next row (or the caller) starts clean. |
static rowByteCapacity(int $cells): int | Documented worst-case row size for a row of $cells cells. |
foreground(): ?string | Current tracked foreground parameters (null = terminal default). |
background(): ?string | Current tracked background parameters (null = terminal default). |
PushToPull final class
Turns a push (callback) producer into a lazy pull generator.
| Method | Summary |
|---|---|
static chunks(callable $produce): \Generator |
ResolvedBinary final class
Shared argv[0]-resolution doctrine for this library's external tools.
| Method | Summary |
|---|---|
static locate(?string $overrideEnv, array $candidates): ?string | Resolve one external tool to an absolute executable path. |
static lookupOnPath(string $name): ?string | PATH lookup for an explicitly-named bare override only. Relative PATH entries are skipped: they are exactly the shape a hijack rides in on. |
static usable(string $candidate): bool | The gate both doors share: an existing, executable file. |
SttyBinary final class
Single source of truth for locating the stty binary.
| Method | Summary |
|---|---|
static path(): ?string | Absolute path to stty, or null when no gate-passing binary resolves. |
static reset(): void | Clear the roster memo (test isolation). The override leg is never cached. |
TmuxBinary final class
Single source of truth for locating the tmux binary.
| Method | Summary |
|---|---|
static path(): ?string | Absolute path to tmux, or null when no gate-passing binary resolves. |
static reset(): void | Clear the roster memo (test isolation). The override leg is never cached. |
SugarCraft\Image\Symbol
CanvasMode enum
Terminal canvas colour modes — the fixed-palette quantisation ladder.
Cases: TrueColor · Ansi256 · Ansi16 · Fgbg
PHP also provides cases(), from() and tryFrom().
| Method | Summary |
|---|---|
quantizeRgb(array $rgb): array | Snap an RGB triple onto this mode's fixed palette. |
quantizes(): bool | Whether glyph-cell colour scoring must quantize its mean pens. |
fgSgr(?array $rgb): ?string | SGR parameter string for a foreground pen, or null to let the terminal default through (Fgbg). |
bgSgr(?array $rgb): ?string | SGR parameter string for a background pen, or null (Fgbg). |
SymbolDef final class
One candidate glyph of the coverage-class corpus: its character, the 8x8 coverage it paints packed row-major MSB-first into a 64-bit bitmap (pixel (x,y) = bit 63-(y*8+x)), the family tags, and the precomputed foreground weight (popcount) — chafa stores exactly this on every ChafaSymbol and the scoring path divides the foreground group by it without re-counting (chafa/internal/chafa-symbols.c calc_weights).
| Method | Summary |
|---|---|
static new(string $char, int $bits, int $tags): self | |
bgWeight(): int | Number of coverage-0 pixels the background pen paints (chafa bg_weight). |
SymbolMap final class
Coverage-class symbol engine — the glyph corpus and candidate search behind the 'symbols' render tier.
| Method | Summary |
|---|---|
static new(): self | |
withLatin(): self | Opt-in LATIN tier: chafa's 365 narrow chafa-symbols-latin.h glyphs (U+00A1-U+03F6, table SymbolSetLatin) appended after the current corpus. |
hasLatin(): bool | Whether the opt-in LATIN tier is appended (see withLatin()). |
withAsciiIbm(): self | Swap the ascii tier (U+0020–U+007E) to chafa's orphaned IBM face — the verbatim chafa-symbols-ascii-ibm.h transcription in SymbolSetTables::ASCII_IBM. |
hasAsciiIbm(): bool | Whether the ascii tier carries the IBM face (see withAsciiIbm()). |
withKana(): self | Opt-in KANA wide tier: chafa's 181 16x8 chafa-symbols-kana.h glyphs (U+3041-U+30FE, table SymbolSetKana) appended after the current wide selection as chafa's wide symbols2 pairs (WideSymbolDef) — never the narrow corpus. |
hasKana(): bool | Whether the opt-in KANA wide tier is appended (see withKana()). |
wideDefs(): array | The map's wide (two-cell) selection in build order — chafa's symbols2 array. Empty on every narrow-only map, so the wide render pass never activates for the default corpus or the latin/ascii-ibm tiers. |
wideCorpus(): array | The wide selection in chafa's symbols2 scan order — joint popcount ascending, ties by codepoint ascending (findWideCandidates() narrows inside the same order; the renderer's exhaustive path walks it directly, so ties resolve exactly like the C's init-sorted array). |
defs(): array | The corpus in build order (basic, braille, sextant, octant) — then the opt-in LATIN tier when withLatin() was used. |
hasSymbol(int $codepoint): bool | chafa_symbol_map_has_symbol (chafa-symbol-map.c:1137): whether the selection holds a codepoint. The solid-cell shortcut consults it for U+2588 (see \SugarCraft\Image\Renderer\SymbolMapRenderer's solid ladder). |
withSelectors(string $selectors): self | Apply chafa's --symbols= tag selector grammar over the FULL corpus — the narrow array (1,260 unique glyphs) and the wide symbols2 array (181 kana glyphs) — returning a new map holding each selection in its corpus build order. |
findCandidates(int $bitmap, bool $allowInverse, int $limit): array | chafa's find_candidates(): a flat popcount-Hamming walk of every corpus bitmap maintaining an insertion-sorted window of the eight best (symbol, inverted) trials. Equal distances keep scan order; an inverse trial (64 - hd) rides the same buffer. |
findWideCandidates(int $bitmapLeft, int $bitmapRight, bool $allowInverse, int $limit): array | Chafa's find_wide_candidates (chafa-symbol-map.c:1268) — the same 8-slot insertion buffer over the WIDE selection, but the distance is the joint hamming of the two 8x8 halves against the candidate's sym[0]/sym[1] pair, seeded at hd 129 with the inverse trial at 128 - hd. The scan order is chafa's own: compare_symbols2_popcount sorts symbols2 ascending by joint weight then codepoint (stable across equal keys), not build order — the wide array is sorted at init in the C, and this port keeps that law so ties resolve exactly like chafa's. |
static coverageToBitmap(array $coverage, ?int $threshold = null): int | chafa coverage_to_bitmap(): row-major MSB-first packing of the 8x8 coverage, pixel (x,y) landing on bit 63-(y*8+x). Two faces: the corpus generators (outline 255/0, braille/sextant/octant 1/0) use the truthy form exactly like chafa's internal one; the runtime conversion of a 0..255 pixel ramp passes $threshold = 127 (chafa/chafa-symbol-map.c:240) — the single place the 8-bit ramp becomes binary. |
static coverageOf(int $bitmap): array | chafa bitmap_to_bytes(): the binary coverage bytes painted by a bitmap, index = y*8+x (the same bit order as coverageToBitmap). |
SymbolSetKana final class
KANA: the wide 16x8 kana symbol tier — chafa's chafa-symbols-kana.h table.
SymbolSetLatin final class
The LATIN symbol set — chafa's chafa-symbols-latin.h table: 365 narrow 8x8 glyphs spanning U+00A1-U+03F6 (Latin-1 supplement, Latin Extended-A and -B, IPA extensions, spacing modifier letters, Greek), transcribed one row per glyph as 'row|row|...' ('X' = painted pixel, MSB-first like SymbolMap::coverageToBitmap()). The bitmaps are chafa's own, a close match to the Terminus ter-x14n font (chafa-symbols-latin.h header).
SymbolSetTables final class
The chafa narrow symbol tables this port had not yet carried: the ASCII glyph set (U+0020–U+007E), its orphaned alternate face ASCII_IBM, the Latin/Greek set (U+00A1–U+03F6), the misc-narrow set (U+2190–U+25FC) and the "Symbols for Legacy Computing" block entries of chafa's block table (U+1FB3C–U+1FBAE) that are neither the generated sextant range nor the eighth-block tier.
| Method | Summary |
|---|---|
static ascii(): array | |
static asciiIbm(): array | The alternate ASCII face of chafa's orphaned chafa-symbols-ascii-ibm.h (see the self::ASCII_IBM docblock for the chafa-wiring verdict). |
static latin(): array | |
static misc(): array | |
static legacyBlock(): array |
SymbolTags final class
Coverage-class symbol tags, bit-for-bit mirrors of chafa's ChafaSymbolTag enum. Tags classify a glyph's visual family; defs ride their table declarations and SymbolMap::withSelectors() filters on the effective tags exactly as chafa's char_is_selected() does — the old "selection never filters" v1 note predates the selector grammar), also serving callers that want to restrict a pick to, say, BRAILLE or STIPPLE families.
| Method | Summary |
|---|---|
static selectorMask(string $name): ?int | Tag mask for a --symbols= class name, or null when unknown. |
WideSymbolDef final class
One candidate WIDE glyph of the coverage-class corpus — chafa's ChafaSymbol2: a 16x8-pixel cell carried as TWO 8x8 bitmaps (sym[0] the left half, sym[1] the right half), each packed row-major MSB-first like SymbolDef::$bits, scored jointly as hd(left) + hd(right) against the two canvas cells it would replace (chafa/internal/chafa-symbols.c init_symbol_array_wide: left = def_to_symbol offset 0 rowstride 16, right = offset 8).
| Method | Summary |
|---|---|
static new(string $char, int $bitsLeft, int $bitsRight, int $tags): self | |
static fromOutline16x8(string $char, string $outline, int $tags): self | Decode one 16x8 outline row-string ('|'-joined rows of 16 'X'/space characters, SymbolSetKana::OUTLINES shape) into the packed half bitmaps — chafa's def_to_symbol with rowstride 16. |
bgWeight(): int | Number of coverage-0 pixels the background pen paints across both halves. |
Configuration
Environment variables
| Variable | Effect |
|---|---|
SUGAR_IMAGE_CHAFA | Operator override for the chafa binary. An absolute path must be an executable file, and a broken absolute override is refused rather than replaced. A bare name authorizes a PATH lookup for that one value only. |
SUGAR_IMAGE_TMUX | Binary override for the tmux consults. Same absolute-path gate as chafa. |
SUGAR_IMAGE_STTY | Binary override for the terminal-state round trip. Same absolute-path gate. |
SUGAR_IMAGE_TMUX_PASSTHROUGH_TTL | Seconds between re-checks of tmux allow-passthrough. Default 30. 0 re-verifies before every frame. A negative or unparsable value falls back to the default. |
Identity variables (TERM, TERM_PROGRAM, TERM_PROGRAM_VERSION, LC_TERMINAL, TERMINAL_NAME, TMUX, KITTY_WINDOW_ID, KITTY_PID, XTERM_VERSION, KONSOLE_VERSION, VTE_VERSION, MLTERM, GHOSTTY_BIN_DIR, WEZTERM_EXECUTABLE, ComSpec) | Probe inputs for Mosaic::probe(). The table-driven identity stage reads exactly these fifteen names. The live DA1 round trip on the TTY decides what the table cannot. |
NO_COLOR, CLICOLOR | Consulted only by the terminfo sixel-detection ladder. They can change which protocol is detected, never which colors are emitted. |
Decode budgets
| Budget | Value | What it stops |
|---|---|---|
ImageSource::MAX_BYTES | 64 MiB | The file, animated-file, URL and fromString() reads. Oversized payloads are refused before GD sees them. |
ImageSource::MAX_PIXELS | 50,000,000 px | The per-decode pixel budget. withMaxPixels() tunes it per source. |
DecodedImageCache::BYTE_BUDGET | 32 MiB, eight slots at most | The process-wide decode LRU. A handle larger than the budget is never kept. |
Animation::MAX_FRAMES | 10,000 frames | The frame-list length. new Animation(...) and withFrame() refuse a longer sequence. |
Chafa binary discovery
The chafa tier is the one place sugar-image executes an external program to produce image output. The binary is chosen through a strict gate, and a bare chafa argv[0] is never spawned, so a rogue chafa earlier on PATH never runs. The order is: the SUGAR_IMAGE_CHAFA override, then a fixed roster of absolute candidates (/usr/bin/chafa, /usr/local/bin/chafa, /opt/homebrew/bin/chafa), each checked for being a file and executable. When nothing resolves, ChafaRenderer::available() returns false and render() throws a chafa.not_found failure. The gate is POSIX-shaped, so the chafa tier does not run on Windows.
Styling and color depth
sugar-image does not ship a theme. Its styling choices are the color depth and the dither mode. The depth is set by the text-tier factory (AsciiColorMode for the ramp, CanvasMode for the symbol map). The dither mode is set on the Sixel renderer, and Mosaic::withDither() changes it on a built Mosaic.
use SugarCraft\Image\Dither;
use SugarCraft\Image\Mosaic;
$sixel = Mosaic::sixel(Dither::Ordered, intensity: 0.6);
$sixel = $sixel->withDither(Dither::FloydSteinberg);
Mosaic::sixel(dither, intensity) exposes the dither axis. intensity (0.0–1.0) biases the Ordered and Noise dithers, and null keeps the chafa default of 1.0.
Examples
examples/inline-image.php <image-file> [width-in-cells](default width 80) prints one image on the terminal's best tier. It is the shortest read of the detection path. Its exit codes are listed under Troubleshooting.examples/text-tiers.php [width-in-cells](default 24) renders the committed fixture through the half-block, quarter-block, ASCII (mono and ansi16) and symbol-map tiers, one labeled block each. It needs no graphics protocol and no chafa binary, so its output can be captured or piped.examples/fixture-gradient.pngis a committed image, so the quickstart and both scripts run against the checkout without a separate file.
php examples/text-tiers.php 16 | head -n 5
php examples/inline-image.php examples/fixture-gradient.png 40
Testing
cd sugar-image && composer install && vendor/bin/phpunit
The suite bootstraps from tests/bootstrap.php and covers the renderers, the decode budgets and the tmux passthrough. The main caps (MAX_BYTES, MAX_PIXELS and Animation::MAX_FRAMES) are pinned by boundary tests, so a change that loosens one fails the suite. The README Limits section lists the few caps that are not pinned.
Troubleshooting and FAQ
Exit codes from inline-image.php
| Exit | Meaning |
|---|---|
| 0 | The image rendered and its bytes were written to stdout. |
| 1 | Usage: no image path given, a width that is not a positive integer of cells, or no file at the given path. |
| 2 | ext-gd is not loaded. This check runs before argument parsing. |
| 3 | The path exists but is not a readable regular file, the bytes did not load as a supported image, or the render refused at the requested size (for example, the canvas ceiling guard). |
The image appears as escape-sequence noise
The probe chose a graphic tier, but the terminal does not render it. Force a text tier with Mosaic::halfBlock() or Mosaic::symbols(), and report the terminal to the probe tables if it should have been detected.
Graphics vanish inside tmux
tmux swallows graphics escapes unless allow-passthrough is on for the pane. Leave TmuxPassthrough in its default auto mode, which turns the option on during the render and restores it afterwards. If you manage tmux yourself, set SUGAR_IMAGE_TMUX_PASSTHROUGH_TTL=0 to re-check on every frame, or call Detect::setAutoPassthrough(false).
A render refuses with a message about GD
Without ext-gd, every pure-PHP tier refuses with a readable message. Install the extension and check it with php -m.
An animated WebP is refused
ImageSource::fromAnimatedFile() refuses animated WebP by name. Use chafa for it, or sugar-video's AnimatedWebpDecoder, which decodes animated WebP for playback.
The chafa tier does not run
The chafa binary is found only through the discovery gate. Set SUGAR_IMAGE_CHAFA to an absolute path of an executable file. A broken absolute override is refused on purpose, so the library never falls back silently to a different program. Check ChafaRenderer::available() to see whether a binary resolved.
Upstream mapping
| SugarCraft | Upstream | Notes |
|---|---|---|
Mosaic facade, Kitty, Sixel, iTerm2 and half-block tiers | charmbracelet/x/mosaic | Listed in docs/MATCHUPS.md. The Picker role matches the ratatui-image facade listed at line 55 of the same MATCHUPS file. |
Symbol namespace (symbol map, canvas modes, corpus) | chafa's coverage-class symbol engine | Ported for parity. The default 676-glyph corpus is frozen byte for byte. |
SugarCraft is developed as a native PHP project. The upstream is a reference, not a source to transliterate.
Architecture
SugarCraft\Image
├── Mosaic / MosaicBuilder # facade: probe, auto, builder, render
├── ImageSource # bytes, metadata and decode budgets
├── Animation / AnimationDriver# frame sequences and their Model
├── Detect / TermDb / Capability # capability detection and quirks tables
├── DiskCache / AdaptiveImage # render caches (on disk; in-session LRU)
├── ImageLayer # marker blocks that ride inside a text frame
├── Renderer/ # Sixel, Kitty, iTerm2, half-block, quarter-block,
│ # ASCII, symbol map, chafa
├── Symbol/ # symbol map, tables, canvas modes, corpus
├── Dither/ # Ditherer and the Dither enum
├── Passthrough/ # tmux passthrough packetizer and decorators
└── Support/ # binary gates (chafa, tmux, stty) and GD probe
The renderers share one interface, so a Mosaic is a renderer plus a sizing policy. Graphic renderers emit protocol bytes, and text renderers emit glyphs. Nothing writes to a terminal on your behalf. The caller owns the output stream, which is what makes the same render usable over ssh, inside tmux or down a CI pipe.
Changelog and versioning
The package has no CHANGELOG file yet, and no sugar-image release tags exist. Consumers install the dev-master branch until a tagged release is cut. The monorepo sugar-image/ commit history is the record of changes. The Packagist page shows the current version.
Source & demos
Demos.
VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.