All 42 libraries

SugarInput

Terminal escape sequence decoder

native PHP — semantics follow bubbletea input input foundation-package

SugarInput code coverage

The missing input layer for PHP TUI. EscapeDecoder consumes raw TTY bytes and emits typed Event objects — plain and legacy keys (including modified xterm forms), Kitty keyboard protocol, SGR 1006/1016 + urxvt 1015 + X10 mouse, focus events, bracketed paste, and a typed drain for terminal replies (DA, DSR/CPR, mode reports, Kitty flags). Reentrant, chunk-invariant, and fuzz-friendly, with counters that make dropped or discarded input observable.

Install

composer require sugarcraft/sugar-input

Quickstart

use SugarCraft\Input\Driver\StreamInputDriver;
use SugarCraft\Input\Event\FocusEvent;
use SugarCraft\Input\Event\KeyEvent;
use SugarCraft\Input\Event\MouseEvent;
use SugarCraft\Input\Event\PasteEvent;
use SugarCraft\Input\Event\TerminalReplyEvent;

$driver = new StreamInputDriver(STDIN);

while (!$driver->isEof()) {
    $event = $driver->read();
    if ($event === null) {
        if (!$driver->hasPending()) {
            usleep(2_000); // nothing buffered — back off before polling again
        }
        continue;
    }

    match (true) {
        $event instanceof KeyEvent        => handleKey($event),
        $event instanceof MouseEvent      => handleMouse($event),
        $event instanceof PasteEvent      => handlePaste($event),
        $event instanceof FocusEvent      => handleFocus($event),
        $event instanceof TerminalReplyEvent => handleReply($event),
        default                           => handleOther($event),
    };
}

One termination caveat: isEof() means "ended and drained", not "ended". A stream that stops mid-sequence leaves the decoder holding a partial, so isEof() stays false and read() answers null forever — call escapeDecoder()->reset() (or bound the loop with a grace period) when shutdown must win over an unfinished frame.

EscapeDecoder

__construct(?EscapeDecoderOptions $options = null)Protocol toggles at construction; null uses the defaults.
decode(string $bytes): list<Event>Decode a byte buffer — emits 0+ Events; buffers partial sequences.
remainder(): stringGet unconsumed bytes that couldn't yet form a complete sequence.
flushDeferredEscape(): list<Event>Settle a lone trailing ESC on an input-idle timer (with deferTrailingEscape).
drainedReplyCount() / droppedUnknownCount() / discardedPasteBytes(): intCounters for terminal replies drained, frames refused, and bytes discarded after a paste overflow.
reset(): voidClear every buffer — partials, paste state, string state. The recovery lever after an unterminated forged paste.

EscapeDecoderOptions

Five readonly booleans — enableMouse, enableKitty, enableFocus, enablePaste (all true by default) and deferTrailingEscape (false by default) — decide which protocol families the decoder interprets. A disabled family's frames are counted drops, never mis-decoded keys.

InputDriver

read(): ?EventReturn the next Event, or null when the non-blocking stream is idle or at EOF.

StreamInputDriver additionally answers isEof() and hasPending() — the null alone does not distinguish idle from ended — and both the stream and React drivers expose their owned decoder via escapeDecoder() for reset(), the flush helper, and the counters.

Event types

KeyEventkey, modifiers, raw, isRelease(), isRepeat — plain keys, F1-F24 legacy and up to F35 via Kitty, arrows, Home/End/PageUp/PageDown, Insert, Delete, Backspace, Tab, Enter, Escape, Ctrl+letter; Kitty releases arrive as ReleaseA (isRelease()), repeats as isRepeat
MouseEventx, y, button, action, modifiers — SGR 1006/1016, urxvt 1015 and X10: press, release, drag, scroll (buttons 96/97 up/down, 98/99 horizontal wheel); the constructor refuses any other action
FocusEventgained, raw — terminal window focus gained/lost (DECSET 1004)
PasteEventcontent, truncated, truncationNotice(): ?string — bracketed paste (CSI 200~ … CSI 201~); above the 1 MiB cap the announcement fires once and the overflow is discarded until the real terminator, never re-decoded as keys
TerminalReplyEventfamily, params, raw, body, truncated, is() — typed drain for device attributes, cursor position, DSR status, window reports, Kitty flags, mode reports, private CSI and string replies
ResizeEventcols, rows — produced by SignalResizeDriver after SIGWINCH (arm() opt-in)

KeyModifier

Modifiers arrive on events and are read with includes() / value(). The constants SHIFT, ALT, CTRL, META, SUPER, HYPER, CAPS_LOCK, NUM_LOCK document the wire bit layout the decoder maps from — Kitty lock-state bits arrive on the explicit-event-type form — and the constructor is private, so masks are not built by hand.

Use it for

  • Real-TTY input — decode raw bytes instead of symbolic key names, on plain streams or ReactPHP loops.
  • Interactive TUI programs — keyboard and mouse input without depending on a specific runtime.
  • Kitty keyboard protocol — event frames CSI code;mods u, including key release events (released a arrives as ReleaseA); the flags query/reply uses the CSI ?…u shape and drains as a reply.
  • Safe paste handling — bracketed paste with a 1 MiB cap whose overflow is discarded, not replayed, so hostile input cannot forge keystrokes.
  • Foundation for any input-consuming lib — pure byte decoding with no event-loop requirement; drivers add stream/ReactPHP/pcntl plumbing.

Source & demos

Try the quickstart →

API

ClassMethodDescription
EscapeDecoder__construct(?EscapeDecoderOptions $options = null)Choose which protocol families decode
EscapeDecoderdecode(string $bytes): list<Event>Decode byte buffer, buffer partials
EscapeDecoderremainder(): stringGet unconsumed bytes
EscapeDecoderflushDeferredEscape(): list<Event>Settle a deferred lone ESC on input idle
EscapeDecoderdrainedReplyCount(): intTerminal replies drained as events
EscapeDecoderdroppedUnknownCount(): intFrames refused (unknown or disabled family)
EscapeDecoderdiscardedPasteBytes(): intBytes discarded after a paste overflow
EscapeDecoderreset(): voidClear partial, paste and string state
StreamInputDriverread(): ?EventNext event from stream, or null (idle/EOF)
StreamInputDriverisEof(): bool / hasPending(): boolDistinguish ended-and-drained from idle
StreamInputDriverescapeDecoder(): EscapeDecoderSeam to the owned decoder (reset/counters/flush)
ReactInputDriveron('data'): eventsEmits decoded Events as they complete (event emitter, not a pull driver)
ReactInputDriverisReadable() / pause() / resume() / close()ReadableStreamInterface surface; pause buffers, resume flushes
ReactInputDriverpipe(WritableStreamInterface): WritableStreamInterfaceForwards raw bytes of the wrapped stream
ReactInputDriverescapeDecoder(): EscapeDecoderSeam to the owned decoder
SignalResizeDriverarm(): boolInstall the SIGWINCH handler; false without ext-pcntl (constructor is side-effect free)
SignalResizeDriverdisarm(): boolHand the process disposition back (previous handler, or SIG_DFL)
SignalResizeDriverread(): Event|ResizeEvent|nullInputDriver surface: returns a fresh ResizeEvent when a SIGWINCH landed since the last read, else null
KeyEventkey: stringSymbolic key name (releases: Release + capitalised name)
KeyEventmodifiers: KeyModifierModifier bitmask
KeyEventraw: stringRaw bytes that produced this event
KeyEventisRelease(): boolTrue for Kitty key-release events
KeyEventisRepeat: boolTrue for Kitty autorepeat frames (decode as press)
MouseEventx, y: intColumn and row (1-based; cells under 1000/1006, pixels under 1016 — the decoder keeps each field's first integer verbatim, units belong to the reporting mode)
MouseEventbutton: intButton index (0=left, 1=middle, 2=right; scroll 96=up, 97=down, 98=wheel-left, 99=wheel-right; X10 releases report 3 — match releases on action, not the button index)
MouseEventaction: stringpress | release | drag | scroll (constructor refuses anything else)
FocusEventgained: boolTrue if focus gained, false if lost
FocusEventraw: ?stringEscape sequence that produced the event
PasteEventcontent: stringPasted content (max 1 MiB)
PasteEventtruncated: boolTrue when content was clipped to the cap
PasteEventtruncationNotice(): ?stringLocalized one-liner explaining the clip, or null
TerminalReplyEventfamily: stringOne of the eight reply families (see FAMILIES)
TerminalReplyEventparams / paramsDropped / raw / body / truncatedParsed reply parameters (first MAX_PARAMS = 32 ride the event; the count the wire carried beyond the cap rides paramsDropped) and the bytes that carried them
TerminalReplyEventis(string $family): boolFamily check
ResizeEventcols, rows: intNew terminal dimensions
KeyModifiernone() / shift() / alt() / ctrl() / altShift() / ctrlShift() / altCtrl() / all()Named factories (memoized)
KeyModifierfromKittyInt() / fromSgrMouse() / fromXtermParam()Wire decoders for each protocol's modifier encoding
KeyModifierincludes(int $flag): boolCheck if flag (e.g. KeyModifier::SHIFT) is set
KeyModifierequals(KeyModifier $other): boolBitmask equality
KeyModifiervalue(): intRaw bitmask value

Security: decoded content is untrusted

Everything the decoder emits is attacker-writable input — any process that can write the pts slave, an injected tmux send-keys session, or whatever the clipboard held feeds the stream. Treat key names, PasteEvent::content, TerminalReplyEvent::body/params, and every raw field as hostile bytes: never echo decoded content straight back to the terminal (a crafted paste or reply body can carry OSC-8 hyperlinks and other introducers that command your renderer — sugar-core's Sanitize is the fleet's shared tool for the sweep), and never interpolate it into shell commands, paths, or logs without your own quoting and redaction discipline.

Two structural laws to design against. Bracketed paste fences are forgeable: CSI 200~/CSI 201~ are just bytes — use framing for convenience (bulk text without keymap side effects), never as an authenticity boundary between typed and pasted. Caps never reinterpret: a sequence that overflows its cap is refused with one counted drop (droppedUnknownCount()); paste bytes past the cap are discarded and counted by discardedPasteBytes() — the paste-only counter. Neither is ever pushed back into the stream for a second parse. The fleet's private-use-area arena (zone sentinels U+E000/U+E001, image markers from U+E002) passes through decoding byte-identical — the consumer that renders owns the sweep, with Sanitize::untrustedForMarkedFrames(); sugar-core's InputReader is a consumer that strips. The decoder's own caps contain parser resource use; they do not make the content trustworthy. The fleet-wide contract lives in docs/TRUST-BOUNDARY.md.