SugarMouse
Mark/Scan/Get (tag the output, scan the frame, look up the id) mouse hit-testing primitives plus the bubblezone-style Zones manager layer, in one package
SugarMouse finds clickable regions in a rendered terminal frame and resolves mouse events to them. You wrap each region in private-use sentinel tags, scan the frame to record each region's bounding box, then hit-test mouse events against those boxes. The primitive Scanner owns its own state, so no global wiring is needed. The Zones\Manager layer adds prefixed managers for nested components, plus hover, drag and multi-click trackers. It ports the Mark, Scan and Get pattern of lrstanley/bubblezone, and ZoneClickTracker addresses bubblezone issue #10.
Install
composer require sugarcraft/sugar-mouse:@dev
The package has no tagged release yet, so it ships only dev-master, and the @dev constraint is required until the first version tag lands. The manifest requires PHP ^8.3. The only package dependency is sugarcraft/sugar-core, which supplies the mouse message types and the width oracle.
Quickstart
use SugarCraft\Mouse\Mark;
use SugarCraft\Mouse\Scan;
use SugarCraft\Mouse\Scanner;
use SugarCraft\Mouse\ZoneClickTracker;
use SugarCraft\Mouse\MouseEvent;
// 1. Wrap interactive content with private-use sentinel tags.
$rendered = Mark::zone('btn-ok', ' OK ')
. Mark::zone('btn-cancel', 'Cancel');
// 2. Scan after rendering to populate the zone registry.
$scanner = Scanner::new()->scan($rendered);
// Never echo marked bytes. Print the stripped frame instead.
echo Scan::strip($rendered);
// 3. Reverse-lookup on mouse events. ' OK ' spans columns 1 to 6 of row 1.
$zone = $scanner->hit(4, 1); // Zone 'btn-ok'
// 4. A click fires only when the release's fresh re-hit agrees with the
// press zone on id AND box. Resolve each event against the frame it
// arrived in.
$tracker = new ZoneClickTracker();
$tracker->track(MouseEvent::press(4, 1), $scanner->hit(4, 1));
$click = $tracker->track(MouseEvent::release(4, 1), $scanner->hit(4, 1));
if ($click !== null) {
echo "Clicked zone: " . $click->zone->id;
}
The Zones\Manager layer does the same job with a single object, and it is the form most applications use. Its scan() returns the display-ready frame, so the printed output and the measured output match:
use SugarCraft\Core\MouseButton;
use SugarCraft\Core\MouseAction;
use SugarCraft\Core\Msg\MouseMsg;
use SugarCraft\Mouse\Zones\Manager;
$z = Manager::newUnprefixed();
$frame = $z->mark('btn:ok', ' OK ') . ' ' . $z->mark('btn:cancel', 'Cancel');
// Scan once before printing. The manager records each marker's box and
// returns the frame with the markers removed.
echo $z->scan($frame);
// A click at column 5, row 1 lands inside the six-cell " OK " button.
$click = new MouseMsg(5, 1, MouseButton::Left, MouseAction::Press);
if ($z->get('btn:ok')?->inBounds($click)) {
// Handle the OK button.
}
Concepts
There are two layers, and both work on the same sentinel tags. The primitive layer is Mark, Scan and Scanner, plus the click and selection state machines. It tells you what geometry a frame holds, and it never touches the registry of a shared manager. The Zones layer wraps the primitives in a Manager that owns a registry, stamps prefixed ids, and routes MouseMsg values into a sugar-core Model.
A zone is a one-based rectangle of terminal cells, with columns counted from the left and rows from the top. A tag is two three-byte private-use codepoints, U+E000 to open and U+E001 to close. Its id is one of the characters A-Z a-z 0-9 . _ : -. Scanning reads the tags to compute each zone's box and never changes the string. Stripping the tags from the bytes you print is your job, and Scan::strip() or Manager::scan() does it for you.
A zone that paints no cell has no box, so it cannot take a click. Zones never overlap a neighbor's clicks unless their boxes do, and the smallest box wins when two overlap.
Tasks
Make a list of selectable rows
Mark each row with its own id, and scan the full frame once. Resolve each click through allInBounds() or anyInBounds(). examples/zones-list-default.php adds a keyboard path that drives the same cursor with Down and Enter.
use SugarCraft\Mouse\Zones\Manager;
$z = Manager::newUnprefixed();
$rows = '';
foreach (['alpha', 'beta', 'gamma'] as $i => $name) {
$rows .= $z->mark('row:' . $i, $name) . "\n";
}
echo $z->scan($rows);
Isolate nested components
Give each component its own prefixed manager, so identically named ids cannot shadow each other. Use newPrefix() for every sub-tree. Pass the full root frame to every manager's scan(), not each sub-tree's own output, because a nested zone's box depends on the outer layout. examples/zones-nested-components.php runs two panes side by side.
use SugarCraft\Mouse\Zones\Manager;
$left = Manager::newPrefix('left.');
$right = Manager::newPrefix('right.');
$frame = $left->mark('ok', 'OK') . ' ' . $right->mark('ok', 'OK');
echo $left->scan($frame); // records only left.* zones
$right->scan($frame); // records only right.* zones from the same frame
Track hover, drag and double clicks
Each tracker takes the manager it hit-tests against, and each one's update() returns the messages it produced. Enable the matching mouse reporting modes first, as the Configuration section explains.
use SugarCraft\Mouse\Zones\Manager;
use SugarCraft\Mouse\Zones\ZoneHoverTracker;
use SugarCraft\Mouse\Zones\DragTracker;
use SugarCraft\Mouse\Zones\MultiClickTracker;
$z = Manager::newUnprefixed();
$hover = ZoneHoverTracker::new($z);
$drag = DragTracker::new($z);
$clicks = MultiClickTracker::new($z, 500);
// Inside Model::update(), feed each MouseMsg to the trackers.
// $hover->update($msg) yields ZoneEnterMsg and ZoneExitMsg.
// $drag->update($msg) yields the three ZoneDrag*Msg values.
// $clicks->update($msg) yields DoubleClickMsg and TripleClickMsg.
Select text across a region
Selection is the press, drag and release state machine for text selection, bounded to a region. Call range() to read the normalized, inclusive range, and SelectionRange::extract() to read its text. The range is row first, and every cell is one-based.
use SugarCraft\Mouse\Selection;
$selection = Selection::new(1, 5, 1, 40); // rows 1-5, columns 1-40
$selection->begin(2, 4); // press on row 2, column 4
$selection->dragTo(3, 10); // drag to row 3, column 10
$range = $selection->range();
$lines = ['first line of text', 'second line of text', 'third line of text'];
$picked = $range?->extract($lines) ?? '';
API reference
The primitive and Zones tables below list the public surface. Deprecated aliases are marked as such. They keep working, and each one delegates to its replacement.
| Class | Method | Description |
|---|---|---|
| Mark | Mark::zone(string $id, string $content) | Wrap content in the sentinel tags. Equivalent to Mark::new()->wrap(). |
| Mark | Mark::new() / Mark::disabled() / withEnabled(bool) / wrap(string $id, string $content) | Instance form. A disabled mark returns the content unwrapped. The id is validated either way. |
| Mark | Mark::isValidId(string) | Whether an id is one that Mark encodes and Scan decodes. Ids are at most MAX_ID_BYTES (256) bytes. |
| Mark | Mark::untrusted(string) / Mark::escapeForMessage(string) | Sweep the sentinel bytes from untrusted text. Escape a hostile id into printable ASCII for an error message. |
| Scan | Scan::parse(string $rendered, ?int $width = null) | Decode the frame into a map of id to Zone. Throws on a duplicate id in one render. |
| Scan | Scan::strip(string $rendered) | Remove the well-formed tags and keep the text, byte for byte. |
| Scanner | Scanner::new() / scan(string $rendered, ?int $width = null) | Create an empty scanner, then parse a frame into its registry. Returns the scanner. |
| Scanner | get(string $id) / hit(int $col, int $row) / all() | Look up a zone by id, reverse-look up the zone at a cell, or read every zone. |
| Scanner | idsStartingWith(string $prefix) / clear() | The zones whose ids begin with a prefix, or an empty registry. prefixed() is a deprecated alias of idsStartingWith(). |
| Zone | Zone::new(string $id, int $startCol, int $startRow, int $endCol, int $endRow) | A zone with its one-based bounding box. |
| Zone | inBounds(MouseEvent) / pos(MouseEvent) / width() / height() / isZero() | Test a point, read its offset from the top-left, read the size, or check for a never-painted zone. |
| MouseEvent | press(int $x, int $y, int $button = 0) / release(...) / drag(...) / scroll(...) | Build an event from its action. The button defaults to the left button. |
| MouseAction | Press, Release, Drag, Scroll | The action enum. The button constants include BUTTON_WHEEL_UP and BUTTON_WHEEL_DOWN. |
| ZoneClickTracker | ZoneClickTracker::new() / track(MouseEvent, ?Zone $hitZone = null) | Feed an event. A completed click returns a ClickResult, and anything else returns null. |
| ZoneClickTracker | observeRelease(MouseEvent, ?Zone = null) / setPressZone(Zone, int $button) | Check a release without completing a click. setPressZone() is deprecated. It is the two-call form of track(), kept for callers that cannot pass the zone with the press. |
| ClickResult | ClickResult::new(Zone, int $button) / $zone / $button | A completed click. |
| Selection | Selection::new(int $rowFrom, int $rowTo, int $colFrom, int $colTo) | A text-selection state machine bounded to a region. |
| Selection | begin(int $row, int $col, bool $shiftExtend = false) / dragTo(int $row, int $col, bool $shiftExtend = false) | Press and drag, with rows first. Each returns whether the state changed. |
| Selection | beginEvent(MouseEvent) / dragToEvent(MouseEvent) | The same press and drag, taking a mouse event. |
| Selection | range() / clear() / active() / dragging() | The current SelectionRange, reset, and whether a selection or a drag is in progress. |
| SelectionRange | SelectionRange::new(int $rowA, int $colA, int $rowB, int $colB, ?int $edgeFrom = null, ?int $edgeTo = null) | A normalized, inclusive range. The constructor takes its arguments row first. |
| SelectionRange | spanOnRow(int $row) / cellContains(int $row, int $col) / cells() / extract(array $lines) | The columns a row covers, a point test, a generator over every cell, and the selected text. |
| Sentinel | Sentinel::OPEN / Sentinel::CLOSE | The two codepoints, which alias sugar-core's Sanitize constants. |
| Class | Method | Description |
|---|---|---|
| Manager | Manager::newUnprefixed() | A fresh manager with no id prefix, independent of every other instance. It is not the shared default, which is Zones::defaultManager(). newGlobal() is a deprecated alias. |
| Manager | Manager::newPrefix(string $prefix = '') / prefix() | A manager whose mark() stamps the prefix onto each id. It skips ids outside the prefix when it scans. |
| Manager | mark(string $id, string $content) | Wrap rendered output in a zone marker. |
| Manager | scan(string $rendered, ?int $width = null) | Record the zones into the registry, strip the markers, and return the frame. Ids re-recorded in a scan replace their earlier boxes, and absent ids persist. |
| Manager | get(string $name) / all() / zoneAt(int $col, int $row) | Look up a zone by name, read every zone, or hit-test a cell without a mouse message. |
| Manager | anyInBounds(MouseMsg) / allInBounds(MouseMsg) | The smallest-area zone under the event, or every covering zone, smallest first. |
| Manager | anyInBoundsAndUpdate(Model, MouseMsg) | Route a hit into a Model as MsgZoneInBounds. Otherwise, forward the raw event. |
| Manager | idsAbsentFromFrame(iterable $scannedIds) | The registered ids that a frame did not paint. Use it to prune stale zones. |
| Manager | clear(?string $id = null) / close() / setEnabled(bool) / isEnabled() | Drop one zone or all of them, switch the manager to pass-through, or toggle its enabled state. |
| Manager | motionTrackingAnsi(bool $on) | Return the paired CSI ?1003h ?1006h enable bytes, or the LIFO disable bytes. It emits nothing itself. setMotionTracking() is a deprecated alias. |
| Zones | defaultManager() / setDefaultManager(?Manager) | The shared manager that the static facade routes through. |
| Zones | mark / scan / get / clear / close / setEnabled / isEnabled / newPrefix / anyInBounds / anyInBoundsAndUpdate | Static forwarding to the default manager. |
| Zone | fromMouseZone(MouseZone) / inBounds(MouseMsg) / pos(MouseMsg) / width() / height() / isZero() / contains(Zone) | The hit-testable adapter over the primitive zone. pos() returns [col, row] from the top-left, zero-based. |
| ZoneHoverTracker | ZoneHoverTracker::new(Manager, ?string $currentZoneId, ?string $pendingEnterId) / update(MouseMsg) | Track the hovered zone. update() returns the enter and exit messages for a boundary crossing. |
| ZoneHoverTracker | currentZone() / currentZoneId() / pendingEnter() / withManager(Manager) / withCurrentZoneId(?string) | The hovered zone or its id, the enter owed after a crossing, a rebind, and a restore from a serialized id. |
| DragTracker | DragTracker::new(Manager, ?string $originZoneId, ?string $currentZoneId, ?MouseButton $dragButton) / update(MouseMsg) | Track one drag across zones. update() returns start, move and end messages. |
| DragTracker | originZone() / currentZone() / originZoneId() / currentZoneId() / dragButton() / withManager(Manager) / withZoneIds(?string, ?string) | The zones and ids of the open drag, the button it was pressed with, a rebind, and a restore from ids. |
| MultiClickTracker | MultiClickTracker::new(Manager, int $clickIntervalMs = 500, ?callable $now = null) / update(MouseMsg) | Track double and triple click streaks. The clock argument steps time in tests. ClickCounter is a class alias. |
| MultiClickTracker | clickCount() / withManager(Manager) | The current streak, where zero means no streak, and a rebind that carries the streak. |
| Messages | ZoneEnterMsg, ZoneExitMsg, ZoneDragStartMsg, ZoneDragMoveMsg, ZoneDragEndMsg, DoubleClickMsg, TripleClickMsg, MsgZoneInBounds | Enter, exit, double-click, triple-click and in-bounds messages carry the zone they concern as zone. Drag messages carry originZone and currentZone and have no zone property. A drag ends with the zone under the release cursor, or null outside every zone. |
Only methods declared in sugar-mouse/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\Mouse
ClickResult final readonly class
The result of a completed click: the zone that was clicked and the button that was used.
| Method | Summary |
|---|---|
static new(Zone $zone, int $button): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public Zone $zone, public int $button) |
Grapheme final class
Grapheme-cluster extraction for the zone scanner: one user-perceived character per call, never one code point.
| Method | Summary |
|---|---|
static next(string $s, int $i): string | The grapheme cluster starting at byte offset $i of $s ('' when $i is at or past the end). |
static nextWithoutIntl(string $s, int $i): string | The cluster at $i found without ext-intl: PCRE \X over a window of WINDOW whole code points, grown while the cluster fills it, up to MAX_WINDOW. Public so the fallback can be verified on hosts that do have ext-intl. |
Lang final class
Per-library translation facade for sugar-mouse.
LineWidthCache final class
Remembers the painted width of frame lines that carry no zone markup, so re-scanning a frame whose lines did not change skips the per-cluster walk for them.
| Method | Summary |
|---|---|
static new(): self | |
beginFrame(): void | Start a new frame: entries not looked up since the previous beginFrame() are dropped at the next one. |
lookup(string $line): ?int | The cached width of $line, or null when it is not cached. |
store(string $line, int $width): void | Record the width the walk measured for an inert $line. |
hits(): int | Lookups answered from the cache since construction. |
misses(): int | Lookups the cache could not answer since construction. |
size(): int | Lines held across both generations. |
clear(): void | Forget every cached line. |
Mark final class
Wrap $content with sentinel zone markers so Scanner can later extract bounding boxes without any external Manager wiring.
| Method | Summary |
|---|---|
static new(): self | House factory: returns a Mark instance with marking enabled. |
static disabled(): self | Factory — creates a Mark instance with marking disabled. |
withEnabled(bool $enabled): self | Return a new Mark with the given enabled state. |
wrap(string $id, string $content): string | Wrap $content with start / end sentinels for $id. |
static isValidId(string $id): bool | Whether $id is a zone id wrap() would accept: non-empty, within self::MAX_ID_BYTES, and every byte inside self::ID_PATTERN. |
static untrusted(string $content): string | Sweep zone sentinels out of an UNTRUSTED string before it is composed into a marked frame. |
static escapeForMessage(string $value): string | Quoted single-line repr of $value for exception messages. Printable ASCII passes through (with quote/backslash escapes and \n \r \t); every other byte becomes \xHH. var_export() and print_r() re-emit control and UTF-8 bytes raw into the message, so a hostile id could smuggle terminal traffic into every log or terminal that later prints the refusal. This function escapes everything that is not printable ASCII instead. |
static zone(string $id, string $content): string | Static convenience alias — creates a temporary instance and calls wrap(). Uses an enabled instance so sentinel output is always produced. |
MouseAction enum
Mouse action type — mirrors bubblezone's mouse-action enum.
Cases: Press · Release · Drag · Scroll
PHP also provides cases(), from() and tryFrom().
MouseEvent final readonly class
Immutable mouse event — x/y are 1-based terminal cell coordinates, matching the coordinate space used by Scanner::hit().
| Method | Summary |
|---|---|
static new(int $x, int $y, int $button, MouseAction $action): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public int $x, public int $y, public int $button, public MouseAction $action) | |
static press(int $x, int $y, int $button = 0): self | Convenience factory for a press event. |
static release(int $x, int $y, int $button = 0): self | Convenience factory for a release event. |
static drag(int $x, int $y, int $button = 0): self | Convenience factory for a drag event. |
static scroll(int $x, int $y, int $button = 0): self | Convenience factory for a scroll event. |
Scan final class
Parse zone sentinels from a rendered string and compute bounding boxes for each discovered zone.
| Method | Summary |
|---|---|
static parse(string $rendered, ?int $width = null, ?LineWidthCache $cache = null): array | Feed a rendered string through the scanner and return all discovered zones. |
static strip(string $rendered): string | Remove this package's PUA sentinel tags from a rendered frame, leaving the visible content byte-for-byte intact. |
Scanner final class
Stateful scan-then-get fluent API for mouse hit-testing.
| Method | Summary |
|---|---|
__construct() | |
static new(): self | Factory — creates an empty scanner ready for scan(). |
scan(string $rendered, ?int $width = null): self | Parse zone sentinels from $rendered, populate the zone registry, and return $this for chaining. |
get(string $id): ?Zone | Return the zone with the given id, or null if not found. |
all(): array | Return all scanned zones keyed by id. |
idsStartingWith(string $prefix): array | Return all zones whose id starts with $prefix. |
prefixed(string $prefix): array | |
hit(int $col, int $row): ?Zone | Reverse-lookup: the zone that owns cell (col, row), or null if no zone covers it. |
hitAll(int $col, int $row): array | Every zone covering cell (col, row), innermost first (ascending area, equal areas in registration order) — the full stack hit() picks the head of. |
zone(ZoneId $id): ?Zone | The zone recorded under a typed id — the ZoneId spelling of get(). |
lineWidths(): LineWidthCache | The line-width cache scan() reads and fills. |
clear(): void | Clear all recorded zones. |
Selection final class
The press → drag → release state machine of a mouse text-selection gesture, clamped to a selectable region of the painted frame.
| Method | Summary |
|---|---|
static new(int $rowFrom, int $rowTo, int $colFrom, int $colTo): self | A selection machine over one selectable region. |
begin(int $row, int $col, bool $shiftExtend = false): bool | Anchor a gesture at a pressed cell. |
dragTo(int $row, int $col, bool $shiftExtend = false): bool | Move the head to the pointer, clamped into the region. |
beginEvent(MouseEvent $event, bool $shiftExtend = false): bool | begin() addressed by a mouse event. |
dragToEvent(MouseEvent $event, bool $shiftExtend = false): bool | dragTo() addressed by a mouse event — same (x, y) to (row, col) transpose as beginEvent(). |
clear(): void | Drop the gesture: no anchor, no head. The machine returns to idle and the next plain event starts fresh. |
range(): ?SelectionRange | The covered cells in reading order, or null when nothing is selected. |
active(): bool | True while a gesture holds an anchor — from the first accepted press (or plain drag) until clear(). |
dragging(): bool | True once the head has left the anchor — this is a drag, not a click. |
SelectionRange final class
A normalized, inclusive range of cells a mouse text selection covers over a painted frame — the frozen product of a Selection gesture.
| Method | Summary |
|---|---|
static new(int $rowA, int $colA, int $rowB, int $colB, ?int $edgeFrom = null, ?int $edgeTo = null): self | Normalize two cells into a reading-order range. |
spanOnRow(int $row): ?array | The inclusive [fromCol, toCol] this range covers on $row, or null when $row lies outside it. |
cellContains(int $row, int $col): bool | True when $row/$col is covered by the selection — by the STREAM shape, not merely by the bounding rectangle. A cell on the first row left of the start (or on the last row right of the end) sits inside the bbox yet was never swept, and copying or highlighting it would be a lie. |
cells(): \Generator | Every covered cell in reading order. |
extract(array $lines): string | The text this range covers, read from the frame's lines. |
highlight(array $lines, ?\Closure $paint = null): array | $lines with the covered cells repainted — reverse video unless $paint says otherwise. |
Sentinel final class
Shared sentinel constants for zone markup.
Zone final class
A rectangular mouse-interactive zone discovered by Scanner::scan(). Coordinates are 1-based terminal cells, matching the coordinate space of MouseEvent::$x / MouseEvent::$y.
| Method | Summary |
|---|---|
static new(string $id, int $startCol, int $startRow, int $endCol, int $endRow): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly string $id, public readonly int $startCol, public readonly int $startRow, public readonly int $endCol, public readonly int $endRow) | |
inBounds(MouseEvent $event): bool | Check whether a mouse event's coordinates fall inside this zone. |
pos(MouseEvent $event): array | Mouse position relative to the zone's top-left, 0-based. Returns negative values when the mouse is outside the zone. |
width(): int | |
height(): int | |
isZero(): bool | True when the zone has never had its bounds set — equivalent to a zero-valued struct from bubblezone's Get(). |
ZoneClickTracker final class
Deduplicate press/release pairs so callers receive one ClickResult per logical click — suppressing spurious extra Press events fired during a drag and discarding mismatched Press+Release pairs on different zones.
| Method | Summary |
|---|---|
static new(): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
track(MouseEvent $event, ?Zone $hitZone = null): ?ClickResult | Feed a mouse event and receive a ClickResult if the event completes a clean Press+Release pair on the same zone. |
observeRelease(MouseEvent $event, ?Zone $hitZone = null): bool | Read-only view of the release-agreement gate: would a track() call with THIS release event and re-hit zone complete the click? Answers without consuming the pending press. A caller can distinguish "I forgot to re-resolve" (false with null, true once passed the fresh hit) from "the zone genuinely moved" (false either way). The silent null from track() cannot tell those apart, and misclick-protection consumers want to know which one they hit. |
setPressZone(Zone $zone, int $button): void | Inject the zone that was hit at the time of the press event. Call this immediately after track(Press) when you have the zone. The Release call must still carry the fresh re-hit zone for the Release-agreement gate — setPressZone() only stores the press half. |
ZoneGrid final class
The bucket-grid spatial index and the package's ONE hit rule.
| Method | Summary |
|---|---|
static of(iterable $zones): self | Index a zone set. Iteration order is registration order — the equal-area tie-break. |
count(): int | Number of indexed zones. |
smallestAt(int $col, int $row): Zone|ZonesZone|null | The zone that owns cell ($col, $row), 1-based: the smallest covering area, ties to the first registered. Null when no zone covers it. |
allAt(int $col, int $row): array | Every zone covering cell ($col, $row), innermost first: ascending area, equal areas in registration order (PHP's sort is stable). |
ZoneId final class
A typed zone id: a namespace (what kind of thing the zone is — toolcall, tab, menuitem) plus a key (which one — 42, settings).
| Method | Summary |
|---|---|
static of(string $namespace, string|int $key = ''): self | Build a typed id. |
static parse(string $wire): ?self | Read a wire id back into its typed form, or null when it is not one a of() call could have produced (invalid id material, an empty namespace, or a trailing : with no key) — such a zone is simply not routable, never an error. |
wire(): string | The id Mark writes and Zone::$id reads back. |
intKey(): ?int | The key as an integer, or null when it is not a canonical decimal integer that fits in an int (7 and -3 are; 07, 7a, ` and an overflowing run are not). Replaces the (int) substr(...)` idiom, which turned every malformed suffix into row 0. |
inNamespace(string $namespace): bool | |
equals(self $other): bool | |
mark(string $content): string | Wrap $content in zone markup for this id (Mark::zone()). |
ZoneRouter final class
Dispatch a zone hit to a handler keyed by a typed ZoneId, instead of a chain of str_starts_with($id, 'prefix:') tests and substr parsing.
| Method | Summary |
|---|---|
static new(): self | |
on(ZoneId $id, \Closure $handler): self | Route the exact id $id to $handler, replacing any earlier route for it. |
onNamespace(string $namespace, \Closure $handler): self | Route every id in $namespace that has no exact route to $handler, replacing any earlier route for the namespace. |
handles(string|ZoneId $id): bool | True when route() would call a handler for $id. |
route(string|ZoneId $id, mixed ...$args): mixed | Call the handler routed for $id with ($zoneId, ...$args) and return its result, or null when no route matches. A handler may itself return null; ask handles() first when the two must be told apart. |
routeMouse(MouseMsg|MouseEvent $event, Scanner|Manager $zones): mixed | Hit-test $event against $zones (the shared smallest-area rule) and route the owning zone: the handler receives ($zoneId, $event, $zone). Null when no zone covers the cell or the hit zone has no route. |
SugarCraft\Mouse\Zones
DragTracker final class
Tracks press → move → release drag sequences within and across zones.
| Method | Summary |
|---|---|
static new(Manager $manager, ?string $originZoneId = null, ?string $currentZoneId = null, ?MouseButton $dragButton = null): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Manager $manager, ?string $originZoneId = null, ?string $currentZoneId = null, ?MouseButton $dragButton = null) | |
originZoneId(): ?string | Read-only accessor for the zone the drag started from. Returns null when no drag is in progress. |
currentZoneId(): ?string | Read-only accessor for the zone the mouse is currently in. Returns null when cursor is not inside any tracked zone. |
originZone(): ?Zone | Resolve the origin zone from the manager's registry. Returns null when not dragging or when the zone was removed. |
currentZone(): ?Zone | Resolve the current zone from the manager's registry. Returns null when cursor is not inside any tracked zone. |
update(MouseMsg $msg): array | Process a mouse event and detect drag state transitions. |
dragButton(): ?MouseButton | Read-only accessor for the button that started the current drag. Returns null when not dragging or when state came from an id-only self::withZoneIds() restore. |
withManager(Manager $manager): self | Return a new tracker with a different manager. |
withZoneIds(?string $origin, ?string $current): self | Return a new tracker with specific zone ids. Intended for state snapshot/restore. An id-only restore cannot carry button identity, so releases are accepted from any button until the next Press re-arms the tracker. |
Manager final class
Mouse-zone manager. Wraps content with sentinel-tagged zone markers identifying a logical "zone". scan() later finds those markers, records each zone's bounding box in terminal cells, and returns the cleaned-up frame.
| Method | Summary |
|---|---|
__construct() | Public for BC; newUnprefixed() is the house spelling. |
static newUnprefixed(): self | Build a fresh un-prefixed manager, independent of every other instance. The name says what it builds: a manager with NO id prefix. Distinct from the Zones facade's shared default manager (Zones::defaultManager()) — use that one only when the whole program agrees on a single zone namespace. |
static newGlobal(): self | |
static newPrefix(string $prefix = ''): self | Build a manager that namespaces every id with a unique prefix. |
static newWithIdPrefix(string $prefix): self | A manager stamping exactly $prefix onto every id, with no counter bookkeeping — the raw constructor ZoneRegistry::newPrefix() builds on. An empty prefix builds an un-prefixed manager. Prefer newPrefix() (or a registry's) unless the prefix is already known to be unique. |
setEnabled(bool $on): void | Toggle marker emission and scanning. When $enabled = false, mark() returns $content verbatim (no markers wrapped — but the id is STILL validated, so flipping the manager off must not become a way to smuggle an illegal id through the emit path) and scan() is a no-op pass-through. Useful for non-interactive output (CI logs, file dumps) where the markers add nothing. |
isEnabled(): bool | |
motionTrackingAnsi(bool $on): string | Build the all-motion tracking byte sequence — RETURNS bytes, emits nothing. The old setMotionTracking name taught setter reflexes and a discarded call was a silent zero-effect failure; this name states what the method is. |
setMotionTracking(bool $on): string | |
prefix(): string | Read-only accessor for the prefix this manager prepends to ids. |
mark(string $id, string $content): string | Wrap $content with start/end markers for prefix() . $id. |
scan(string $rendered, ?int $width = null): string | Strip markers from $rendered, recording each zone's bounding box, and return the cleaned frame ready for the terminal. |
get(string $id): ?Zone | Look up a recorded zone. |
all(): array | |
idsAbsentFromFrame(iterable $scannedIds): array | Generation-diff prune helper: the registered ids that did not appear among $scannedIds, in registry order (latest recording last). |
clear(?string $id = null): void | Forget zone state. With no argument, drops every recorded zone (the original clear() shape, kept for back-compat). Pass an $id to drop a single zone — equivalent to the upstream Manager::Clear(id string) overload. Like get(), the $id may be the short or the wire spelling. |
close(): void | Tear down the manager. Mirrors bubblezone's Manager::Close() — upstream stops the background zoneWorker goroutine here. Our port computes everything synchronously inside scan() so there is no worker to stop, but close() still drops every recorded zone and disables the manager so subsequent mark() / scan() calls become pass-throughs. Idempotent. |
anyInBounds(Msg $mouse): ?Zone | The innermost (smallest-area) recorded zone whose bounds contain $mouse; on equal area the zone the latest scan closed first wins (a re-scanned id takes this scan's close order, not the position of its first-ever recording). This is THE hit rule, shared with the primitive \SugarCraft\Mouse\Scanner::hit() through ZoneGrid, so both layers name the same owner for one painted frame when this Manager holds exactly that frame's zones (it scanned the frame and every id the frame did not paint was cleared via idsAbsentFromFrame()); zones kept from earlier frames can win a cell the frame's Scanner gives to another zone. This registry has no stacking concept — no priority, layer, or modal state — see the overlay contract in README's Zones section before scanning a full-screen modal over a live registry. Returns null if no zone matches (or if the Msg isn't a MouseMsg to begin with — handy when an update() loop routes every Msg here without filtering first). |
allInBounds(Msg $mouse): array | Every zone whose bounds contain $mouse, ordered innermost first (ascending area; equal areas in registry order — the latest scan's close order for the ids it recorded — matching anyInBounds()). Lets a consumer route a click to ALL owners of a cell — e.g. a container and the button inside it — instead of only the smallest. |
zoneAt(int $col, int $row): ?Zone | Pure-geometry lookup without a Msg: the innermost zone covering cell ($col, $row), 1-based — same area/tie rule as anyInBounds(). Lets consumers resolve what is under the wheel, the caret, or an arbitrary position without fabricating a MouseMsg. |
zone(\SugarCraft\Mouse\ZoneId $id): ?Zone | The zone recorded under a typed id — the \SugarCraft\Mouse\ZoneId spelling of get() (short or wire form, like get()). |
lineWidths(): LineWidthCache | The line-width cache scan() reads and fills. |
anyInBoundsAndUpdate(Model $model, Msg $mouse): array | Hit-test $mouse against every recorded zone. If a zone matches, dispatch a MsgZoneInBounds carrying the hit zone + the original Msg through $model->update() and return the resulting pair [Model, ?Cmd]. If nothing matches, dispatch the original Msg verbatim. |
MsgZoneInBounds final class
Mouse-event Msg paired with the zone the click landed inside.
| Method | Summary |
|---|---|
static new(Zone $zone, MouseMsg $mouse): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Zone $zone, public readonly MouseMsg $mouse) |
MultiClickTracker final class
Tracks rapid successive clicks (double / triple) within a zone.
| Method | Summary |
|---|---|
static new(Manager $manager, int $clickIntervalMs = 500, ?callable $now = null): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Manager $manager, public readonly int $clickIntervalMs = 500, ?callable $now = null) | |
clickCount(): int | Read-only accessor for the current click streak count. Returns 0 when no click streak is in progress. |
update(MouseMsg $msg): array | Process a mouse press event and detect double/triple click streaks. |
withManager(Manager $manager): self | Return a new counter with a different manager, carrying the click streak across (mirrors ZoneHoverTracker::withManager()): rebinding the manager re-points hit-testing, it does not erase the user's in-progress double-click. |
Zone final class
A rectangular zone discovered by Manager::scan(). Coordinates are 1-based terminal cells, matching MouseMsg::$x / MouseMsg::$y.
| Method | Summary |
|---|---|
static new(string $id, int $startCol, int $startRow, int $endCol, int $endRow): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly string $id, public readonly int $startCol, public readonly int $startRow, public readonly int $endCol, public readonly int $endRow) | |
static fromMouseZone(MouseZone $zone): self | Adapt a primitive \SugarCraft\Mouse\Zone (as parsed by \SugarCraft\Mouse\Scan) into a Zones-layer Zone, preserving id + bounds. Used by Manager::scan() to store the SSOT-parsed zones under this namespace's public type. |
inBounds(MouseMsg $msg): bool | |
pos(MouseMsg $msg): array | Mouse position relative to the zone's top-left, 0-based. Returns negative values when the mouse is outside the zone. |
width(): int | |
height(): int | |
isZero(): bool | True when the zone has no recorded position — bubblezone returns a zero-valued struct from Get() if the id has never been scanned. SugarMouse's Manager::get() returns null for the same case, but holders of a Zone that was never scanned (e.g. an end-marker arrived without a start) can use isZero() to spot the degenerate state without a special-case check at every site. |
contains(Zone $other): bool | True when $other is entirely contained within this zone. Uses closed interval semantics (boundaries are inclusive), matching inBounds(). |
static toMouseEvent(MouseMsg $msg): MouseEvent | Translate a Core wire message into the primitive MouseEvent vocabulary — the lib's ONE public bridge between the two action enums (Core Press|Release|Motion + the MouseWheelMsg subclass vs primitive Press|Release|Drag|Scroll). |
ZoneHoverTracker final class
Tracks which zone the cursor is in across mouse-move events and emits enter/exit messages on boundary crossings.
| Method | Summary |
|---|---|
static new(Manager $manager, ?string $currentZoneId = null, ?string $pendingEnterId = null): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Manager $manager, ?string $currentZoneId = null, ?string $pendingEnterId = null) | |
pendingEnter(): ?Zone | The zone the cursor is over when an Exit(A) was just emitted and the matching Enter(B) is still owed — the one-message-per-call contract strands it until a re-feed. Reports the pending Zone WITHOUT consuming it: re-feed update() (synthetic Motion at the same coordinates works, see README's hover re-dispatch recipe) to receive the real Enter. |
currentZoneId(): ?string | Read-only accessor for the currently hovered zone id. Returns null when the cursor is not inside any tracked zone. |
currentZone(): ?Zone | Resolve the currently hovered zone from the manager's registry. Returns null when the cursor is not inside any zone. |
update(MouseMsg $msg): array | Process a mouse event and detect zone boundary crossings. |
withManager(Manager $manager): self | Return a new tracker with a different manager (useful when composing multiple zone-aware components each with their own prefixed manager). |
withCurrentZoneId(?string $id): self | Return a new tracker with a specific current zone id. Intended for state snapshot/restore rather than direct use. Pass null to clear the hovered state; an owed Enter is dropped (a restored id replaces the enter flow, it does not continue it). |
ZoneRegistry final class
The per-application home of the state the Zones layer used to keep in statics: the default Manager and the counter behind auto-generated Manager::newPrefix() prefixes.
| Method | Summary |
|---|---|
static new(): self | A registry whose auto prefixes come from the one process-wide counter. |
static isolated(): self | A registry with its own auto prefix counter, starting at 1-. Its prefixes are unique within this registry only: a manager it hands out may share a prefix with one from any other registry. |
defaultManager(): Manager | This registry's shared default manager (un-prefixed), built lazily on first access and kept so zone state persists across mark() → scan() → get() cycles. |
setDefaultManager(?Manager $manager): void | Replace the default manager; null drops it so the next defaultManager() builds a fresh enabled one. |
newPrefix(string $prefix = ''): Manager | A manager that namespaces every id with a prefix unique within this registry's counter scope (the process for new(), the registry for isolated()). Same contract as Manager::newPrefix(): an empty $prefix auto-generates <n>-; an explicit numeric <n>- prefix is reserved, so a later auto prefix never merges into it. |
successor(): self | A new registry with no default manager whose auto prefixes continue after this one's. Zones::setRegistry() resets through it, so a manager built before the reset never shares a prefix with one built after it: Manager::scan() accepts any id that starts with its prefix, and two managers holding 1- would accept each other's zones. A new() registry's successor shares the process counter; an isolated() one's starts from a copy of its counter. |
newUnprefixed(): Manager | A fresh un-prefixed manager, independent of the default one. |
Zones final class
Package-level facade over a single shared Manager instance.
| Method | Summary |
|---|---|
static registry(): ZoneRegistry | The process registry the facade and the static Manager::newPrefix() route through, built lazily on first use. |
static setRegistry(?ZoneRegistry $registry): void | Replace the process registry; null resets it to an empty default manager while auto prefixes keep counting up, so no process-registry prefix is ever issued twice (ZoneRegistry::successor()). A ZoneRegistry::new() registry draws from the same process-wide counter, so injecting one keeps that guarantee; an injected ZoneRegistry::isolated() registry keeps its own counter, and its managers may share a prefix with another registry's and must not scan each other's frames. |
static defaultManager(): Manager | The shared default Manager of the process registry. Lazily constructed on first access; survives between calls so zone state persists across mark() → scan() → get() cycles. |
static setDefaultManager(?Manager $m): void | Replace the shared default manager. Mostly useful in tests (tearDown(): Zones::setDefaultManager(null) flushes state) or when you want every package-level call to route through a pre-configured prefixed manager. |
static mark(string $id, string $content): string | Mirrors bubblezone's package-level Mark. |
static scan(string $rendered, ?int $width = null): string | Mirrors bubblezone's Scan. $width clamps zone columns into [1, $width]. |
static get(string $id): ?Zone | Mirrors bubblezone's Get. |
static clear(?string $id = null): void | Mirrors bubblezone's Clear. Pass an id to drop a single zone; omit to wipe every zone tracked by the default manager. |
static close(): void | Mirrors bubblezone's Close. After calling this the default manager is disabled (mark / scan become pass-through) and its registry is dropped — Idempotent. WARNING: subsequent package-level calls (Zones::define / Zones::scan / Zones::get …) then pass through silently and hit-tests resolve nothing, i.e. a whole dead UI with no error. Re-arm with Zones::setDefaultManager(null), which lazily builds a fresh enabled default on the next access. |
static setEnabled(bool $on): void | Mirrors bubblezone's SetEnabled. |
static isEnabled(): bool | Mirrors bubblezone's Enabled. |
static newPrefix(string $prefix = ''): Manager | Mirrors bubblezone's NewPrefix — but unlike upstream (which returns a string prefix scoped to the default manager), this returns a **fresh prefixed Manager**. Compose multiple components by giving each its own prefixed manager rather than sharing the default. Draws from the process registry's counter, with the same ZoneRegistry::isolated() injection caveat as Manager::newPrefix(). |
static anyInBounds(Msg $mouse): ?Zone | Mirrors bubblezone's AnyInBounds. |
static anyInBoundsAndUpdate(Model $model, Msg $mouse): array | Mirrors bubblezone's AnyInBoundsAndUpdate. |
SugarCraft\Mouse\Zones\Msg
DoubleClickMsg final class
Emitted when a second press lands inside the same zone within the click interval (default 500 ms).
| Method | Summary |
|---|---|
static new(Zone $zone): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Zone $zone) |
TripleClickMsg final class
Emitted when a third press lands inside the same zone within the click interval (default 500 ms).
| Method | Summary |
|---|---|
static new(Zone $zone): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Zone $zone) |
ZoneDragEndMsg final class
Emitted when the drag button is released, ending a drag sequence.
| Method | Summary |
|---|---|
static new(Zone $originZone, ?Zone $currentZone): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Zone $originZone, public readonly ?Zone $currentZone) |
ZoneDragMoveMsg final class
Emitted when the cursor crosses into a different zone during a drag — motion inside the current zone emits nothing, and dragging off all zones clears the current zone silently (there is no zone to name).
| Method | Summary |
|---|---|
static new(Zone $originZone, Zone $currentZone): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Zone $originZone, public readonly Zone $currentZone) |
ZoneDragStartMsg final class
Emitted when a mouse button is pressed inside a zone, starting a drag sequence.
| Method | Summary |
|---|---|
static new(Zone $originZone, Zone $currentZone): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Zone $originZone, public readonly Zone $currentZone) |
ZoneEnterMsg final class
Emitted when the cursor enters a zone.
| Method | Summary |
|---|---|
static new(Zone $zone): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Zone $zone) |
ZoneExitMsg final class
Emitted when the cursor exits a zone.
| Method | Summary |
|---|---|
static new(Zone $zone): self | House ::new() factory - same signature as the public constructor, which stays public for BC (SM-S31, gate G12 house-convention half). |
__construct(public readonly Zone $zone) |
Configuration and options
There is no configuration file and no environment variable. The settings are constructor arguments, the manager's prefix and enabled state, and the terminal's mouse reporting mode, which the host must enable.
| Option | Where | Default | Effect |
|---|---|---|---|
| Id prefix | Manager::newPrefix($prefix) | '' | Namespaces every id the manager stamps. Use one per component. |
| Enabled | setEnabled(bool) | on | A disabled manager's mark() returns the content verbatim, and its scan() passes the frame through unchanged. The id is still validated, so turning the manager off cannot let an illegal id through. |
| Click interval | MultiClickTracker::new($manager, $clickIntervalMs) | 500 ms | The longest gap between presses that still counts as one streak. Widen it for users who need more time. |
| Id length | Mark::MAX_ID_BYTES | 256 | Longest id that Mark encodes and Scan decodes. |
| Content size | Mark::MAX_CONTENT_BYTES | 1048576 | Largest chunk that Mark wraps. |
| Width | scan($rendered, ?int $width) | none | Clips the scanned frame to a viewport, so a zone past the right edge is dropped. |
Mouse-tracking modes
This library never writes to the terminal. The host must enable the reporting modes before any tracker can see an event, and each tracker needs a different mode. Whoever enables a mode owns disabling it on every exit path.
| Mode | Reports | Needed by |
|---|---|---|
1000 | Press, release and wheel | ZoneClickTracker and MultiClickTracker, for clean clicks |
1002 | Press, release and drag, which also covers motion with a button held | DragTracker boundary crossings while a button is pressed |
1003 | All motion, with or without a button held | ZoneHoverTracker, for enter and exit with no press |
1006 | SGR extended coordinates, shaped CSI < b ; x ; y M or m | Any mode above column or row 223, where the legacy encoding saturates |
Manager::motionTrackingAnsi(true) returns \x1b[?1003h\x1b[?1006h, and the matching disable is the reverse order. The mode 1000 alone reports nothing this library can read. The reader expects the SGR form, so turn 1000 on with its 1006 companion. 1002 and 1003 are the xterm family. Konsole has no 1003, and tmux re-encodes reports, so design for a fallback when motion reports never arrive. Strip the modifier bits, which are 4 for shift, 8 for alt and 16 for ctrl, before you compare button numbers. Bit 32 marks a held-drag motion.
Keys and input
The library reads no keyboard input. Every mouse action in a zone-driven interface needs a keyboard route to the same command. Tab and Shift+Tab, or the arrow keys, move focus across the zones in reading order, and Enter fires the focused one. Feed the keyboard route into the same handler that a click calls. The Accessibility section lists the full parity rules.
Theming and styling
The library emits no SGR, so styling is the host's job. To highlight a selection, call Selection::range() and test each cell with SelectionRange::cellContains(), then apply your own style to those cells. Hover and focus highlights work the same way: keep the tracker's current zone, and restyle that zone's cells when you render. The marker tags carry no color, and they are zero-width to the scanner, so they never change a style or a layout.
Accessibility
Zone tags are private-use codepoints. Screen readers announce them as placeholder glyphs or as unknown-character noise, so print only the stripped frame. At the Zones\Manager layer, scan() returns it display-ready. At the primitive layer, Scan::strip() removes the tags, because Scanner never modifies the string. Never echo marked bytes.
The pointer-only affordances need keyboard twins. Hover needs a focus-revealed twin, which shows on keyboard focus what ZoneEnterMsg shows on pointer entry, and hides on blur. Drag needs a no-motion fallback, a select-then-choose flow, because terminals without 1002 or 1003 report no crossings. Never gate a command on tracker state alone, such as the hovered zone or a click streak. Give the multi-click gesture a single-action twin, and expose clickIntervalMs as a setting, because the 500 ms default is a pointer-timing tolerance.
Examples
Each example is a standalone script under examples/. It runs on built-in input and prints a frame, so no terminal is needed to run it.
examples/zones-buttons.phplays out a button row withManager::newUnprefixed(), marks and scans it, then resolves clicks to zone ids.examples/zones-list-default.phprenders a selectable list, resolves click-to-focus, and runs a scripted keyboard twin that drives the same cursor with Down and Enter.examples/zones-nested-components.phpruns twoManager::newPrefix()managers for the left and right panes, so their identically named ids stay apart.
php examples/zones-buttons.php
php examples/zones-list-default.php
php examples/zones-nested-components.php
Two clickable buttons
A button row resolves clicks to zone ids.
List with zones
A selectable list with click-to-focus and a keyboard twin.
Nested components
Two prefixed managers keep identically named ids apart.Testing
composer install
vendor/bin/phpunit
The suite pins the scanner grammar in ScanTest, and the malformed-markup rules in ScanMalformedMarkupTest. ScannerTest covers the registry, MarkTest the encoding, and SelectionTest and SelectionRangeTest the selection machine. ZoneClickTrackerTest covers the click dedup, and the tests/Zones directory covers the managers and trackers. LangTest checks the refusal messages, and FactorySurfaceTest checks the factory methods.
Troubleshooting and FAQ
Clicks never fire
The terminal is not reporting presses. Enable 1000 with its 1006 companion, and check that your input layer decodes the SGR form. Without the companion, the reports arrive in a form this library cannot read.
Hover never fires without a press
Hover needs all-motion reporting, 1003. Mode 1000 reports only presses, so enter and exit fire on a press but not on plain motion. Design a fallback for terminals that send no motion reports.
Escape sequences or sentinel bytes appear on screen
The marked frame was echoed. Print the output of scan() or Scan::strip(), which removes the tags, and never the marked string itself.
get() returns null for a zone I rendered
The zone is either not scanned yet, or it painted no cell. A zone whose content is empty, or whose box is clipped away by scan()'s width, is never recorded. Scan the full root frame after you render it.
Two components respond to the same click
Their ids collide in one manager. Give each sub-tree its own Manager::newPrefix(). Scanning a sub-tree on its own also shifts the boxes, so scan the full root frame once.
A zone disappears when a tag is unbalanced
An orphan close or an unclosed open is skipped, and it records no zone. Balance each open and close pair, and check the id against Mark::isValidId(). An id with a space, an escape or a non-ASCII byte is not a valid id.
Columns drift on CJK or emoji text
Scanning measures cells with sugar-core's Width::string(), which counts wide East Asian characters as two columns. Clusters such as ZWJ emoji and flags depend on the host's grapheme support. Install ext-intl on machines where the layout must be pinned.
Upstream mapping
The primitive layer follows the Mark, Scan and Get pattern of bubblezone. The mapping below notes where the port differs.
| Upstream concept | SugarCraft | Notes |
|---|---|---|
| Mark a zone | Mark::zone(), Manager::mark() | The same wrap-and-scan pattern, with sentinels in the private-use area. |
| Scan the frame and look up a zone | Scanner::scan(), Manager::get() | An unknown id returns null, not a zero zone. |
| Press and release pairing | ZoneClickTracker | Addresses bubblezone issue #10. A click fires only when the release re-hits the press zone. |
| Prefixed managers | Manager::newPrefix() | Keeps nested components apart. |
| Text selection | Selection, SelectionRange | Row-first addressing, with the one-based inclusive range. |
Architecture and sentinel design
The sentinel tags are the trust boundary. Ordinary ASCII UI text cannot carry them, so normal rendering cannot forge a zone boundary. Pasted text and other untrusted input can carry them, though, so sweep untrusted input before you compose it into a marked frame. Mark::untrusted() strips the sentinels, and Sanitize::untrustedForMarkedFrames() in sugar-core also strips ANSI. The two sweeps are different.
The scanner bounds its work. Mark caps ids at 256 bytes and content at 1 MiB, so an oversized span is rejected before any substring is built. Parsing has no cap of its own, so feed it only frames you expect to be terminal-sized. A lone sentinel costs its own three bytes, and the text after it is kept and measured as visible text, so a stray tag cannot move the zones around it.
A zone that spans several rows is stored as the smallest bounding box that holds every cell it painted. The box is a union rectangle, so a gap next to a short line still counts as inside. Hit-testing multi-line content is therefore approximate, by design.
Coordinates are (col, row) everywhere, except for the selection API, which is row first, as a text selection is addressed like a file. Every cell is one-based. SelectionRange::new() refuses a zero or negative coordinate at construction. Zone::new() stores its box as given, and Selection::new() floors its region into the terminal grid, so validate untrusted coordinates before you pass them to either. A lone carriage return returns to column one on the same row, the way a terminal does.
Changelog and versioning
The renamed and superseded names stay as deprecated aliases, which include newGlobal(), setMotionTracking(), prefixed(), setPressZone() and ClickCounter. Their removal is a deliberate backward-compatibility decision, and each alias delegates byte for byte to its replacement.
Source
Related
- sugar-widgets and sugar-gallery drive
Zones\Managerinstances. - sugar-core supplies the mouse messages, the sentinel constants and the width oracle.