Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(glyphgrid): cursor styles, a wide-glyph cursor, and the outline a blurred terminal draws

enes7bd292c48d63
diff --git a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
index 876413861..1cd5ecdd9 100644
--- a/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
+++ b/docs/superpowers/plans/2026-08-03-phase1b-device-checklist.md
@@ -226,13 +226,27 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
the selected cells, with correct fg/bg inversion, and matches what the DOM renderer draws.
- [ ] **2.9 Cursor.** A focused terminal shows a solid block cursor at the right cell. It is
**static** — it does not blink even with "Cursor blink" on (known limitation L1).
+ **The cursor honours Settings → Terminal → Cursor style.** Walk all three: `block` INVERTS the
+ glyph under it (the letter goes dark on a bright cell — a block is drawn as a CELL, and that is
+ the only path that can invert), `bar` is a hairline down the LEFT edge with the glyph still
+ readable beside it, `underline` is one along the bottom. Change the setting while the terminal
+ is focused: the shape follows immediately, with no refresh. Then **zoom out to ~30% and back**:
+ a bar/underline stays a visible hairline at every step (its thickness is held at one device
+ pixel), never fading away and never growing into a block.
- [ ] **2.10 Cursor at end of line.** Type until the cursor sits past the last column (deferred
wrap): the cursor is drawn on the LAST column, not off-screen or on the next row.
- [ ] **2.11 Cursor hidden by a TUI.** Open a fullscreen CLI that hides the cursor (any agent CLI,
`less`, `htop`): no stray block cursor is painted anywhere on the grid.
-- [ ] **2.12 Blur.** Click away from a terminal: the cursor DISAPPEARS (the DOM renderer draws a
- hollow outline — known limitation L2), and the selection stays visible in the same color as
- when focused (known limitation L3). Judge whether either is acceptable to ship.
+- [ ] **2.12 Blur.** Click away from a terminal. Two things change, and both are the point of the
+ item: the block cursor becomes a **hollow outline** — a one-pixel box around the cell with the
+ glyph inside it readable, which is exactly what xterm's DOM renderer draws for an unfocused
+ terminal — and a selection made before the blur is **dimmer** than it was, in the same hue.
+ Compare a focused and a blurred terminal side by side; the two selections must be
+ distinguishable at a glance. Then set Settings → Terminal → **Inactive cursor style** to
+ `none` (no cursor at all on blur), to `block` (a solid one, glyph inverted, on the blurred
+ terminal) and back to `outline`. **The outline is the DEFAULT** — every terminal on the canvas
+ except the focused one is drawing it, so judge it at normal zoom on a busy canvas, not only on
+ one node.
- [ ] **2.13 Plate geometry.** Look at the four corners and the right/bottom edges of a terminal
body. Expected: **no bands anywhere** — the plate is the body rect, so the fit slack at the
right/bottom and the padding seams on the left/top are all inside it (the round-2 fix; the
@@ -247,9 +261,12 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
- [ ] **2.14 Scroll area after a font change.** Change the font size while shared is on, then look
at the scrollbar/scroll area geometry: the thumb matches the content, no phantom region.
- [ ] **2.15 Cursor on a wide glyph.** Put the cursor ON a double-width character (type `日本語`
- and walk the cursor back over it, or `vim` with the cursor on an emoji): KNOWN — the block
- covers only the LEFT half-cell of the glyph instead of both columns (L13). Confirm that is
- what you see, and judge how visible it is at normal zoom.
+ and walk the cursor back over it, or `vim` with the cursor on an emoji). The block covers
+ **both columns** — the whole character, with no un-inverted right half — and walking off it
+ leaves nothing behind. Repeat with **Cursor style = underline** (the rule runs the full width
+ of the character, not half of it) and with the terminal **blurred** (the outline boxes the
+ whole character). `bar` is the deliberate exception: it stays ONE hairline on the left edge,
+ because it marks the insertion point rather than the cell.
## 3. Interactions
@@ -462,10 +479,6 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
- **L1 — The cursor does not blink.** The shared renderer paints a static block cursor regardless
of the "Cursor blink" setting. Decide on device whether this ships as-is or the setting should be
gated in shared mode.
-- **L2 — A blurred terminal paints no cursor.** xterm's DOM renderer draws a hollow outline for an
- unfocused terminal; the engine has no outline flag, so the cursor simply disappears on blur.
-- **L3 — Selection does not dim on blur.** The theme lanes carry no *inactive* selection color, so
- an unfocused terminal's selection keeps the active color.
- **L4 — Square plate corners.** The grid's plate is a rectangle; the node has `border-radius: 10px`
and cannot clip the canvas (it is not a DOM child), so the body's corners read square in shared
mode. Phase 2: rounded/stencilled plate.
@@ -513,11 +526,6 @@ Auto after you switched builds, that is why: re-select Shared and carry on.
- **L11 — Grids keep drawing while the kanban board covers the canvas.** The board overlay is
opaque, so nothing is visible; it is wasted work, measured by item 4.16 and closed in Phase 2 if
it shows up.
-- **L13 — The block cursor on a double-width glyph paints only the left half-cell.** The cursor rect
- is emitted at one cell's width, while a CJK/emoji cell occupies two columns, so the block covers
- the left column and the right half of the glyph stays uncovered. Cosmetic and position-correct
- (the cursor is on the right cell); Phase 2, with the same wide-cell geometry work as the rest of
- the plate/rect family.
- **L14 — The atlas cell and the baseline latch to the FIRST terminal's usable measurement.** The
atlas is rasterized into xterm's own `dimensions.device.cell`, handed over by whichever terminal
builds the shared context first, and the baseline is derived from that same font at that moment.
diff --git a/src/renderer/glyphgrid/addon.test.ts b/src/renderer/glyphgrid/addon.test.ts
index cd658bb0c..40adbb6f9 100644
--- a/src/renderer/glyphgrid/addon.test.ts
+++ b/src/renderer/glyphgrid/addon.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { GlyphAtlas } from './atlas'
import { CELL_STRIDE, FLAG_CURSOR, FLAG_SELECTED, packColor, readCell } from './cells'
+import type { GridCursor } from './cursor'
import type { GridHandle } from './engine'
import {
GlyphGridRendererAddonCore,
@@ -57,14 +58,18 @@ function recordingHandle(): GridHandle & {
rows: RecordedRow[]
log: string[]
resizes: Array<[number, number]>
+ /** Every cursor spec pushed to the grid, newest last — `at(-1)` is what a frame would draw. */
+ cursors: Array<GridCursor | null>
} {
const rows: RecordedRow[] = []
const log: string[] = []
const resizes: Array<[number, number]> = []
+ const cursors: Array<GridCursor | null> = []
return {
rows,
log,
resizes,
+ cursors,
updateRow(row, cells) {
log.push(`updateRow:${row}`)
rows.push({ row, cells: cells.slice(), buf: cells })
@@ -73,6 +78,9 @@ function recordingHandle(): GridHandle & {
// The addon owns CELLS, never geometry — the plate is the node's business. A stub, present
// only to satisfy the handle contract.
setPlateRect() {},
+ setCursor(cursor) {
+ cursors.push(cursor)
+ },
setZ() {},
resize(cols, r) {
log.push(`resize:${cols}x${r}`)
@@ -166,9 +174,16 @@ interface FakeTermOpts {
cursorVisible?: boolean
focus?: boolean
decorations?: ReturnType<typeof fakeDecorations>
+ /** xterm's two cursor options, verbatim. ABSENT on purpose in every test that does not name them:
+ * an xterm build that stopped reporting them must degrade to xterm's own defaults (a focused
+ * block, a blurred outline), never to no cursor at all. */
+ cursorStyle?: { style?: string; inactiveStyle?: string }
+ /** Columns whose cell reports width 2 — a wide glyph's LEAD. The column after one reports width
+ * 0, exactly as xterm's buffer stores a double-width character. */
+ wideCols?: readonly number[]
}
-type FakeTermState = Required<Omit<FakeTermOpts, 'decorations'>>
+type FakeTermState = Required<Omit<FakeTermOpts, 'decorations' | 'cursorStyle' | 'wideCols'>>
function fakeTerm(o: FakeTermOpts = {}): TermInternals & { state: FakeTermState } {
const state: FakeTermState = {
@@ -191,12 +206,19 @@ function fakeTerm(o: FakeTermOpts = {}): TermInternals & { state: FakeTermState
cursorX: () => state.cursorX,
cursorY: () => state.cursorY,
cursorVisible: () => state.cursorVisible,
- readCell: (absRow, col) => rowCodedCell(absRow, col),
+ readCell: (absRow, col) => {
+ const wide = o.wideCols ?? []
+ if (wide.includes(col)) return { ...rowCodedCell(absRow, col), getWidth: () => 2 }
+ if (wide.includes(col - 1)) return { ...rowCodedCell(absRow, col), getWidth: () => 0 }
+ return rowCodedCell(absRow, col)
+ },
makeWorkCell: () => workCell,
deviceMetrics: () => ({ charW: 16, charH: 34, cellW: 16, cellH: 34 }),
dpr: () => 2,
theme: () => THEME,
hasFocus: () => state.focus,
+ // Absent unless a test names them — see FakeTermOpts.cursorStyle.
+ cursorStyle: o.cursorStyle ? () => o.cursorStyle as { style?: string } : undefined,
// Absent unless a test asks for them — an xterm build with no decoration service hands the
// addon exactly this, and every other test in this file is that case.
decorations: o.decorations?.reader,
@@ -451,6 +473,207 @@ describe('GlyphGridRendererAddonCore cursor + focus', () => {
})
})
+/** THE CURSOR SHAPE — which half of the renderer draws it, and where.
+ *
+ * A block is a CELL rewrite (only the cell path can invert the glyph) and every other shape is an
+ * OVERLAY pushed to the grid. So each test here asserts BOTH halves: the shape that should be drawn
+ * as an overlay, and the absence of the one that should not be drawn as cells — a bug that put the
+ * cursor on both paths would paint an opaque quad over the very inversion it just produced. */
+describe('GlyphGridRendererAddonCore cursor shape', () => {
+ const last = (h: ReturnType<typeof recordingHandle>): GridCursor | null | undefined =>
+ h.cursors.at(-1)
+
+ it('pushes NO overlay for a focused block — the cells carry it', () => {
+ const { core, handle } = make({ rows: 4, cursorY: 1, cursorX: 2, cursorStyle: { style: 'block' } })
+ core.renderRows(0, 3)
+ expect(last(handle)).toBe(null)
+ expect(readCell(handle.rows.find((r) => r.row === 1)!.cells, 2).flags & FLAG_CURSOR).toBe(
+ FLAG_CURSOR
+ )
+ })
+
+ it('pushes a BAR overlay, and leaves the cell un-inverted', () => {
+ const { core, handle } = make({ rows: 4, cursorY: 1, cursorX: 2, cursorStyle: { style: 'bar' } })
+ core.renderRows(0, 3)
+ expect(last(handle)).toEqual({
+ col: 2,
+ row: 1,
+ shape: 'bar',
+ widthCells: 1,
+ color: THEME.cursorBg
+ })
+ expect(readCell(handle.rows.find((r) => r.row === 1)!.cells, 2).flags & FLAG_CURSOR).toBe(0)
+ })
+
+ it('pushes an UNDERLINE overlay for that style', () => {
+ const { core, handle } = make({ rows: 4, cursorY: 0, cursorX: 1, cursorStyle: { style: 'underline' } })
+ core.renderRows(0, 3)
+ expect(last(handle)?.shape).toBe('underline')
+ })
+
+ it('a BLURRED terminal gets the hollow outline xterm draws by default', () => {
+ // The row this task exists for: `outline` is xterm's default `cursorInactiveStyle`, so this is
+ // the DEFAULT path, not an exotic setting. Limitation L2 was that it could not be expressed.
+ const { core, handle } = make({ rows: 4, cursorY: 2, cursorX: 3, focus: false })
+ core.renderRows(0, 3)
+ expect(last(handle)).toEqual({
+ col: 3,
+ row: 2,
+ shape: 'outline',
+ widthCells: 1,
+ color: THEME.cursorBg
+ })
+ expect(readCell(handle.rows.find((r) => r.row === 2)!.cells, 3).flags & FLAG_CURSOR).toBe(0)
+ })
+
+ it('honours an inactive style of none — nothing on either path', () => {
+ const { core, handle } = make({
+ rows: 4,
+ cursorY: 2,
+ cursorX: 3,
+ focus: false,
+ cursorStyle: { inactiveStyle: 'none' }
+ })
+ core.renderRows(0, 3)
+ expect(last(handle)).toBe(null)
+ for (const rec of handle.rows)
+ for (let c = 0; c < 4; c++) expect(readCell(rec.cells, c).flags & FLAG_CURSOR).toBe(0)
+ })
+
+ it('honours an inactive style of BLOCK through the cell path, not the overlay', () => {
+ const { core, handle } = make({
+ rows: 4,
+ cursorY: 2,
+ cursorX: 3,
+ focus: false,
+ cursorStyle: { inactiveStyle: 'block' }
+ })
+ core.renderRows(0, 3)
+ expect(last(handle)).toBe(null)
+ expect(readCell(handle.rows.find((r) => r.row === 2)!.cells, 3).flags & FLAG_CURSOR).toBe(
+ FLAG_CURSOR
+ )
+ })
+
+ it('clears the overlay when the app hides the cursor', () => {
+ // DECTCEM inside a TUI. A stale overlay would leave a bar sitting in the middle of vim — and
+ // unlike a packed row, nothing else ever erases a grid-level value.
+ const { core, term, handle } = make({
+ rows: 4,
+ cursorY: 1,
+ cursorX: 1,
+ cursorStyle: { style: 'bar' }
+ })
+ core.renderRows(0, 3)
+ expect(last(handle)?.shape).toBe('bar')
+ term.state.cursorVisible = false
+ core.renderRows(0, 3)
+ expect(last(handle)).toBe(null)
+ })
+
+ it('reports widthCells 2 when the cursor sits on a WIDE glyph', () => {
+ // The overlay's half of L13: a bar on 日 is still one hairline, but an underline or an outline
+ // has to span the whole character — which needs the cell's width, not the cursor's column.
+ const { core, handle } = make({
+ rows: 4,
+ cursorY: 0,
+ cursorX: 1,
+ wideCols: [1],
+ cursorStyle: { style: 'underline' }
+ })
+ core.renderRows(0, 3)
+ expect(last(handle)?.widthCells).toBe(2)
+ })
+
+ it('clamps the overlay column exactly as the cell path does (deferred wrap)', () => {
+ const { core, handle } = make({ cols: 4, rows: 2, cursorX: 4, cursorY: 0, cursorStyle: { style: 'bar' } })
+ core.renderRows(0, 1)
+ expect(last(handle)?.col).toBe(3)
+ })
+
+ it('clears the overlay when the cursor scrolls out of the viewport', () => {
+ // The cursor's row is baseY + cursorY - viewportY; scroll back far enough and it is off the top
+ // of the viewport. An overlay is a GRID-level value, so nothing else would erase it — a stale
+ // one would draw a cursor over whatever text scrolled into that row.
+ const { core, term, handle } = make({
+ rows: 4,
+ baseY: 100,
+ viewportY: 100,
+ cursorY: 1,
+ cursorStyle: { style: 'bar' }
+ })
+ core.renderRows(0, 3)
+ expect(last(handle)?.row).toBe(1)
+ term.state.viewportY = 106
+ core.renderRows(0, 3)
+ expect(last(handle)).toBe(null)
+ })
+
+ it('degrades to a block / outline when the shell reports no cursor options at all', () => {
+ // An xterm bump that renames the options must cost the user their chosen SHAPE, never their
+ // cursor — so the fallbacks are xterm's own defaults.
+ const focused = make({ rows: 4, cursorY: 1, cursorX: 1 })
+ focused.core.renderRows(0, 3)
+ expect(focused.handle.cursors.at(-1)).toBe(null)
+ expect(readCell(focused.handle.rows.find((r) => r.row === 1)!.cells, 1).flags & FLAG_CURSOR).toBe(
+ FLAG_CURSOR
+ )
+
+ const blurred = make({ rows: 4, cursorY: 1, cursorX: 1, focus: false })
+ blurred.core.renderRows(0, 3)
+ expect(blurred.handle.cursors.at(-1)?.shape).toBe('outline')
+ })
+
+ it('follows blur and focus without waiting for a redraw', () => {
+ const { core, handle } = make({ rows: 4, cursorY: 1, cursorX: 1, cursorStyle: { style: 'bar' } })
+ core.renderRows(0, 3)
+ expect(last(handle)?.shape).toBe('bar')
+ core.handleBlur()
+ expect(last(handle)?.shape).toBe('outline')
+ core.handleFocus()
+ expect(last(handle)?.shape).toBe('bar')
+ })
+})
+
+/** BLUR AND THE SELECTION — limitation L3.
+ *
+ * xterm paints an unfocused terminal's selection in a quieter colour; this engine's theme lanes
+ * carry no inactive colour, so the feed blends toward the plate. The addon's share is the REPAINT:
+ * blur used to repack the cursor row only, which would have left the selection bright until
+ * something else happened to touch those rows. */
+describe('GlyphGridRendererAddonCore blur dims the selection', () => {
+ /** THEME.selectionBg blended half-way to THEME.bg — see feed.ts's INACTIVE_SELECTION_BLEND. */
+ const DIMMED = packColor(0x20, 0x31, 0x49, 0xff)
+
+ it('repacks the selected rows on blur, in the inactive colour', () => {
+ const { core, handle } = make({ rows: 8, cols: 4, cursorY: 0 })
+ core.handleSelectionChanged([0, 2], [4, 3], false)
+ handle.rows.length = 0
+ core.handleBlur()
+ expect([...new Set(handle.rows.map((r) => r.row))].sort((a, b) => a - b)).toEqual([0, 2, 3])
+ const row2 = handle.rows.find((r) => r.row === 2)!
+ expect(readCell(row2.cells, 0).bg).toBe(DIMMED)
+ expect(readCell(row2.cells, 0).flags & FLAG_SELECTED).toBe(FLAG_SELECTED)
+ })
+
+ it('paints the ACTIVE colour back on focus', () => {
+ const { core, handle } = make({ rows: 8, cols: 4, cursorY: 0 })
+ core.handleSelectionChanged([0, 2], [4, 3], false)
+ core.handleBlur()
+ handle.rows.length = 0
+ core.handleFocus()
+ const row2 = handle.rows.find((r) => r.row === 2)!
+ expect(readCell(row2.cells, 0).bg).toBe(THEME.selectionBg)
+ })
+
+ it('packs a selection made WHILE blurred in the inactive colour', () => {
+ const { core, handle } = make({ rows: 8, cols: 4, focus: false })
+ core.handleSelectionChanged([0, 2], [4, 3], false)
+ const row2 = handle.rows.find((r) => r.row === 2)!
+ expect(readCell(row2.cells, 0).bg).toBe(DIMMED)
+ })
+})
+
describe('GlyphGridRendererAddonCore redraw requests', () => {
it('clear() repacks everything and asks xterm for a full redraw', () => {
const { core, handle } = make({ rows: 5 })
diff --git a/src/renderer/glyphgrid/addon.ts b/src/renderer/glyphgrid/addon.ts
index 293dc1699..b301d99a4 100644
--- a/src/renderer/glyphgrid/addon.ts
+++ b/src/renderer/glyphgrid/addon.ts
@@ -10,6 +10,7 @@
import type { GlyphAtlas, GlyphAtlasSubscription } from './atlas'
import { CELL_STRIDE } from './cells'
+import { resolveCursorShape, type CursorShape, type GridCursor } from './cursor'
import type { DecorationReader } from './decorations'
import type { GridHandle } from './engine'
import { packViewportRow, type CellView, type ThemeLanes } from './feed'
@@ -48,6 +49,17 @@ export interface TermInternals {
theme(): ThemeLanes
/** Read ONCE, at construction — see `focused`. */
hasFocus(): boolean
+ /** xterm's `options.cursorStyle` and `options.cursorInactiveStyle`, verbatim strings.
+ *
+ * OPTIONAL, and read on every pack rather than cached: the user can change either from Settings
+ * at any moment, and the option object is the shell's live view of the terminal. A build that
+ * reports neither degrades to xterm's own defaults (a focused block, a blurred outline) —
+ * a bumped xterm must cost the user their chosen SHAPE, never their cursor.
+ *
+ * The FOCUS half is deliberately not read from here: this addon tracks focus itself (see
+ * `focused`), because whether the browser service's flag has flipped by the time xterm calls
+ * handleBlur is an ordering detail the cursor's correctness must not rest on. */
+ cursorStyle?(): { style?: string; inactiveStyle?: string }
/** The terminal's decorations — the cell colours a ⌘F hit paints — or undefined.
*
* ALL THREE DECORATION MEMBERS ARE OPTIONAL, together: an xterm build whose decoration service
@@ -247,13 +259,13 @@ export class GlyphGridRendererAddonCore {
handleBlur(): void {
if (this.disposed) return
this.focused = false
- this.packCursorRow()
+ this.repaintFocusDependent()
}
handleFocus(): void {
if (this.disposed) return
this.focused = true
- this.packCursorRow()
+ this.repaintFocusDependent()
}
/** Not part of xterm's renderer surface — the shell calls it from `_themeService.onChangeColors`.
@@ -280,6 +292,11 @@ export class GlyphGridRendererAddonCore {
* (it outlives a renderer swap back to DOM). */
dispose(): void {
this.disposed = true
+ // The overlay cursor is a GRID-level value, so — unlike a packed row — nothing will ever
+ // overwrite it. A renderer swapped back to xterm's DOM one would otherwise leave a bar or an
+ // outline painted on the shared canvas under a terminal now drawing its own. A silent no-op when
+ // the owner has already dropped the handle, which is the ordinary teardown order.
+ this.handle.setCursor(null)
this.redrawListeners.clear()
this.atlasResetSub.dispose()
for (const sub of this.decorationSubs) sub.dispose()
@@ -359,6 +376,63 @@ export class GlyphGridRendererAddonCore {
this.packRows(row, row)
}
+ /** Everything a focus change repaints. The cursor row, because its shape changes (a focused block
+ * becomes a blurred outline), AND the selected rows, because an unfocused terminal's selection is
+ * painted in a quieter colour (limitation L3). Repacking only the cursor row — which is what this
+ * used to do — left the selection band bright until something unrelated happened to touch it. */
+ private repaintFocusDependent(): void {
+ this.packCursorRow()
+ const sel = this.selectionRowRange()
+ if (sel) this.packRows(sel[0], sel[1])
+ }
+
+ /** The shape the cursor takes right now, from the shell's options and OUR focus flag. */
+ private cursorShape(): CursorShape {
+ const opts = this.internals.cursorStyle?.()
+ return resolveCursorShape(this.focused, opts?.style, opts?.inactiveStyle)
+ }
+
+ /**
+ * The overlay cursor this grid should draw, or null.
+ *
+ * Null for a BLOCK as well as for `none`: a block is a cell rewrite (only that path can invert the
+ * glyph under it), and drawing it here too would paint an opaque quad over the inversion the feed
+ * just produced. Null for a hidden cursor (DECTCEM inside a TUI) and for one scrolled out of the
+ * viewport, both for the same reason: the overlay is a GRID-level value, so nothing else would
+ * ever erase a stale one — unlike a packed row, which the next frame rewrites wholesale.
+ */
+ private cursorSpec(): GridCursor | null {
+ const shape = this.cursorShape()
+ if (shape === 'block' || shape === 'none') return null
+ if (!this.internals.cursorVisible()) return null
+ if (this.cols <= 0 || this.rows <= 0) return null
+ const row = this.cursorViewportRow()
+ if (row < 0 || row >= this.rows) return null
+ // Clamped exactly as the cell path clamps it: with a deferred wrap pending the buffer's x sits
+ // ON `cols`, and an overlay drawn there would hang off the right edge of the terminal.
+ const col = Math.min(this.internals.cursorX(), this.cols - 1)
+ const cell = this.internals.readCell(
+ this.internals.baseY() + this.internals.cursorY(),
+ col,
+ this.workCell
+ )
+ return {
+ col,
+ row,
+ shape,
+ // A wide glyph's lead: the cursor covers the whole character, not its left half (L13). Read
+ // from the CELL, since the cursor's column says nothing about how wide what it sits on is.
+ widthCells: cell && cell.getWidth() === 2 ? 2 : 1,
+ color: this.internals.theme().cursorBg
+ }
+ }
+
+ /** Push the current overlay cursor at the grid. Cheap and idempotent — the engine change-gates it
+ * — which is what lets every pack path call it without reasoning about whether it moved. */
+ private syncCursor(): void {
+ this.handle.setCursor(this.cursorSpec())
+ }
+
/** The single funnel: every path that changes what a row should look like ends here.
*
* Reads viewport/theme/cursor ONCE for the whole range — they cannot change mid-loop, and
@@ -366,18 +440,24 @@ export class GlyphGridRendererAddonCore {
* re-read per row. */
private packRows(from: number, to: number): void {
if (this.disposed) return
+ // FIRST, and independent of the range: the overlay cursor is a property of the terminal, not of
+ // the rows this pass happens to touch, and every path that repacks anything is also a path
+ // along which the cursor may have moved, changed shape or gone away.
+ this.syncCursor()
const start = Math.max(0, from)
const end = Math.min(this.rows - 1, to)
if (end < start || this.cols <= 0) return
const theme = this.internals.theme()
const viewportY = this.internals.viewportY()
- // -1 = no cursor anywhere in this pass (hidden by the app, or the terminal is not focused —
- // xterm draws a hollow outline there, which this engine has no flag for; painting nothing is
- // the honest v1 degradation and is what handleBlur repacks the row to produce).
- const cursorRow =
- this.focused && this.internals.cursorVisible()
- ? this.internals.baseY() + this.internals.cursorY() - viewportY
- : -1
+ // -1 = no cursor row in this pass (the app hid it — DECTCEM inside a TUI). NOT focus-gated any
+ // more: a blurred terminal still has a cursor, it just wears a different shape, and which of the
+ // two paths draws it is `cursorShape`'s answer below — not this row's.
+ const cursorRow = this.internals.cursorVisible()
+ ? this.internals.baseY() + this.internals.cursorY() - viewportY
+ : -1
+ // Resolved ONCE for the range: only a `block` is a cell rewrite, and the feed ignores
+ // `cursorCol` for every other shape (the overlay pass draws those — see `cursorSpec`).
+ const cursorShape = this.cursorShape()
// CLAMPED, exactly as xterm's own renderers do (`Math.min(buffer.x, cols - 1)`): with a
// deferred wrap pending, the buffer's x sits ON `cols`, one past the last column. Left
// unclamped it matches no column and the cursor simply VANISHES at the end of a full line —
@@ -393,10 +473,11 @@ export class GlyphGridRendererAddonCore {
atlas: this.atlas,
theme,
selection: this.selectionOnRow(this.absRow),
- // A block cursor on a DOUBLE-WIDTH glyph paints the left half only: the cursor is one
- // column and the glyph is two. Known v1 limitation (the two-column rule needs the wide
- // flag honoured in the shader) — visible, harmless, tracked for Phase 2.
cursorCol: row === cursorRow ? cursorCol : -1,
+ cursorShape,
+ // Only the SELECTION colour depends on this (an unfocused terminal's band is quieter — L3);
+ // the blurred cursor is a shape, and shapes are the overlay's business.
+ focused: this.focused,
decorations,
// Decoration markers are keyed by ABSOLUTE buffer row, so this is the row the lookup needs
// — the viewport row would slide the highlights off their matches on every scroll.
diff --git a/src/renderer/glyphgrid/cursor.test.ts b/src/renderer/glyphgrid/cursor.test.ts
new file mode 100644
index 000000000..e3113b917
--- /dev/null
+++ b/src/renderer/glyphgrid/cursor.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it } from 'vitest'
+import {
+ cursorOverlays,
+ cursorThicknessWorld,
+ MAX_CURSOR_RECTS,
+ resolveCursorShape,
+ type CursorShape
+} from './cursor'
+
+describe('cursorOverlays', () => {
+ it('draws nothing for a block — the cell path inverts the glyph instead', () => {
+ expect(cursorOverlays('block', 1, 1, 10, 20)).toEqual([])
+ })
+
+ it('draws nothing for none', () => {
+ expect(cursorOverlays('none', 1, 1, 10, 20)).toEqual([])
+ })
+
+ it('puts a bar on the LEFT edge, one thickness wide, full height', () => {
+ expect(cursorOverlays('bar', 1, 2, 10, 20)).toEqual([{ x: 0, y: 0, w: 2, h: 20 }])
+ })
+
+ it('puts an underline on the BOTTOM edge, full width', () => {
+ expect(cursorOverlays('underline', 1, 2, 10, 20)).toEqual([{ x: 0, y: 18, w: 10, h: 2 }])
+ })
+
+ it('outlines all four edges without doubling the corners', () => {
+ // top, bottom, left, right — the verticals are inset by the horizontals' thickness so the
+ // corner texel is written once. Two overlapping rects would be twice the alpha on a corner
+ // the moment anything but an opaque colour is used.
+ expect(cursorOverlays('outline', 1, 1, 10, 20)).toEqual([
+ { x: 0, y: 0, w: 10, h: 1 },
+ { x: 0, y: 19, w: 10, h: 1 },
+ { x: 0, y: 1, w: 1, h: 18 },
+ { x: 9, y: 1, w: 1, h: 18 }
+ ])
+ })
+
+ it('spans BOTH columns of a wide glyph', () => {
+ expect(cursorOverlays('underline', 2, 2, 10, 20)).toEqual([{ x: 0, y: 18, w: 20, h: 2 }])
+ })
+
+ it('keeps a BAR at one thickness on a wide glyph — only the span grows, not the mark', () => {
+ // The bar marks the INSERTION POINT, which is the left edge of the cell whatever the glyph
+ // there is; widening it with the cell would draw a half-block on every CJK character.
+ expect(cursorOverlays('bar', 2, 2, 10, 20)).toEqual([{ x: 0, y: 0, w: 2, h: 20 }])
+ })
+
+ it('outlines both columns of a wide glyph, with the right edge on the FAR column', () => {
+ expect(cursorOverlays('outline', 2, 1, 10, 20)).toEqual([
+ { x: 0, y: 0, w: 20, h: 1 },
+ { x: 0, y: 19, w: 20, h: 1 },
+ { x: 0, y: 1, w: 1, h: 18 },
+ { x: 19, y: 1, w: 1, h: 18 }
+ ])
+ })
+
+ it('draws nothing at zero (or negative) thickness rather than empty rects', () => {
+ // A rect of no area is a draw call that paints nothing; the caller skips the whole pass on an
+ // empty list, so answering [] is what makes a degenerate cell cost zero GL calls.
+ expect(cursorOverlays('bar', 1, 0, 10, 20)).toEqual([])
+ expect(cursorOverlays('outline', 1, -3, 10, 20)).toEqual([])
+ })
+
+ it('clamps a thickness larger than the cell instead of emitting negative rects', () => {
+ // A hairline is a fraction of a cell in every real configuration, but the thickness is derived
+ // from the camera (see cursorThicknessWorld) and a deeply zoomed-out cell is smaller than one
+ // device pixel — where an unclamped underline would sit at a NEGATIVE y and an outline's
+ // verticals would have negative height, which draws either nothing or a stripe across the row.
+ expect(cursorOverlays('underline', 1, 50, 10, 20)).toEqual([{ x: 0, y: 0, w: 10, h: 20 }])
+ expect(cursorOverlays('bar', 1, 50, 10, 20)).toEqual([{ x: 0, y: 0, w: 10, h: 20 }])
+ // Half the cell each way is the most an outline can take before the two horizontals meet.
+ expect(cursorOverlays('outline', 1, 50, 10, 20)).toEqual([
+ { x: 0, y: 0, w: 10, h: 10 },
+ { x: 0, y: 10, w: 10, h: 10 }
+ ])
+ })
+})
+
+/** The overlay pass sizes a UNIFORM ARRAY from `MAX_CURSOR_RECTS` and truncates anything longer, so
+ * a shape that ever produced more rects than that would silently lose an edge on screen with
+ * nothing failing anywhere. Pinned here, over every shape and both widths. */
+describe('MAX_CURSOR_RECTS', () => {
+ it('bounds what any shape can produce', () => {
+ const shapes: CursorShape[] = ['block', 'bar', 'underline', 'outline', 'none']
+ for (const shape of shapes) {
+ for (const widthCells of [1, 2]) {
+ for (const t of [0.5, 1, 2, 7, 40]) {
+ expect(cursorOverlays(shape, widthCells, t, 10, 20).length).toBeLessThanOrEqual(
+ MAX_CURSOR_RECTS
+ )
+ }
+ }
+ }
+ })
+})
+
+/** The shape a terminal's cursor takes, from xterm's two options and the focus flag.
+ *
+ * The pair is what makes this worth a function: xterm has a style for a FOCUSED terminal and a
+ * separate one for a blurred one, and the blurred default — `outline` — is precisely the hollow box
+ * the shared renderer could not draw. */
+describe('resolveCursorShape', () => {
+ it('maps the focused styles one-to-one', () => {
+ expect(resolveCursorShape(true, 'block', 'outline')).toBe('block')
+ expect(resolveCursorShape(true, 'bar', 'outline')).toBe('bar')
+ expect(resolveCursorShape(true, 'underline', 'outline')).toBe('underline')
+ })
+
+ it('reads the INACTIVE style when the terminal is blurred', () => {
+ expect(resolveCursorShape(false, 'block', 'outline')).toBe('outline')
+ expect(resolveCursorShape(false, 'block', 'none')).toBe('none')
+ expect(resolveCursorShape(false, 'block', 'bar')).toBe('bar')
+ expect(resolveCursorShape(false, 'bar', 'underline')).toBe('underline')
+ expect(resolveCursorShape(false, 'bar', 'block')).toBe('block')
+ })
+
+ it("falls back to xterm's OWN defaults when an option is missing", () => {
+ // Which is the case this whole task exists for: `outline` is xterm's default
+ // `cursorInactiveStyle`, so an app that never sets the option — nodeterm's own default —
+ // wants a hollow box on every blurred terminal.
+ expect(resolveCursorShape(true, undefined, undefined)).toBe('block')
+ expect(resolveCursorShape(false, undefined, undefined)).toBe('outline')
+ })
+
+ it('treats an unknown option as the default for that focus state, never as no cursor', () => {
+ // The strings come from `term.options`, i.e. from settings on disk. A value this renderer does
+ // not know must degrade to the shape xterm would have drawn, not to an invisible cursor.
+ expect(resolveCursorShape(true, 'wobble', 'outline')).toBe('block')
+ expect(resolveCursorShape(false, 'block', 'wobble')).toBe('outline')
+ })
+
+ it('never answers `outline` for a FOCUSED terminal', () => {
+ // xterm's `cursorStyle` has no outline member; accepting one here would let a settings typo
+ // put every focused terminal on a hollow cursor.
+ expect(resolveCursorShape(true, 'outline', 'outline')).toBe('block')
+ expect(resolveCursorShape(true, 'none', 'outline')).toBe('block')
+ })
+})
+
+/** The hairline's world-unit thickness, derived from the camera.
+ *
+ * World units are CSS px at zoom 1, and the mark has to read as a HAIRLINE at every zoom: one CSS
+ * px, except that it may never fall below one DEVICE px, which is where it would start to
+ * disappear into the gaps between sampled pixels. */
+describe('cursorThicknessWorld', () => {
+ it('is one CSS pixel at zoom 1', () => {
+ expect(cursorThicknessWorld(1, 1)).toBe(1)
+ expect(cursorThicknessWorld(1, 2)).toBe(1)
+ })
+
+ it('grows in WORLD units as the camera zooms out, so the mark stays one device pixel', () => {
+ // zoom 0.25 on a dpr-2 display: one device px is 2 world units, and a 1-unit line would be
+ // half a device pixel — a cursor that fades out as the user zooms away from it.
+ expect(cursorThicknessWorld(0.25, 2)).toBe(2)
+ expect(cursorThicknessWorld(0.1, 1)).toBe(10)
+ })
+
+ it('does not SHRINK when zoomed in — the mark stays a CSS pixel, like every other renderer', () => {
+ expect(cursorThicknessWorld(4, 2)).toBe(1)
+ })
+
+ it('survives a degenerate camera rather than answering NaN or 0', () => {
+ // A zoom or dpr of 0 reaches here only from a half-initialized camera, and a NaN rect poisons
+ // the whole draw call it lands in.
+ expect(cursorThicknessWorld(0, 2)).toBe(1)
+ expect(cursorThicknessWorld(1, 0)).toBe(1)
+ expect(cursorThicknessWorld(Number.NaN, Number.NaN)).toBe(1)
+ })
+})
diff --git a/src/renderer/glyphgrid/cursor.ts b/src/renderer/glyphgrid/cursor.ts
new file mode 100644
index 000000000..d9d787413
--- /dev/null
+++ b/src/renderer/glyphgrid/cursor.ts
@@ -0,0 +1,174 @@
+/** The cursor's geometry, and nothing else: shapes in, rects in cell units out.
+ *
+ * Like the rest of this directory it imports NOTHING — no GL, no xterm. The two option strings it
+ * resolves a shape from arrive as plain strings through the attach shell, so a bumped xterm that
+ * renames or extends them breaks one file (`glyphgrid-attach.ts`) rather than this one.
+ *
+ * THE SPLIT THIS MODULE EXISTS TO EXPRESS. A BLOCK cursor is a CELL REWRITE — the feed swaps the
+ * cell's fg/bg for the cursor pair, which is the only way the glyph under it can be inverted, since
+ * the atlas is colour-keyed and the slot is rasterized in the colours it was asked for. Every OTHER
+ * shape draws NEXT TO the glyph rather than through it, so it is an overlay: a handful of small
+ * quads drawn after the cells, in the cursor colour, sampling no atlas. `cursorOverlays` returns
+ * `[]` for `block` for exactly that reason — it is not "unimplemented", it is the cell path's job —
+ * and the two must never be unified: a unified path would either lose the inversion or draw the
+ * block twice, once inverted and once as an opaque quad over the glyph it just inverted. */
+
+/** The shapes this renderer can draw. Superset of xterm's `cursorStyle` (block/bar/underline) and
+ * `cursorInactiveStyle` (those three plus outline/none) — see `resolveCursorShape`. */
+export type CursorShape = 'block' | 'bar' | 'underline' | 'outline' | 'none'
+
+/** One overlay rect, relative to the TOP-LEFT of the cursor's cell and in the SAME units as the
+ * `cellW`/`cellH` it was computed from (world units — CSS px at zoom 1). Not normalized: the caller
+ * adds the cell's world origin and hands the result to the GPU, and a 0..1 fraction would only mean
+ * every call site multiplying by the cell again. */
+export interface CursorOverlay {
+ x: number
+ y: number
+ w: number
+ h: number
+}
+
+/** Everything a draw needs to know about one grid's cursor. Lives here rather than in `gl.ts`
+ * because `shape` is this module's type and the rects are this module's job; `gl.ts` consumes it
+ * through `GridDrawParams.cursor`.
+ *
+ * `widthCells` is 2 on a wide glyph's LEAD and 1 everywhere else — the cursor covers the whole
+ * character, not the left half of it (limitation L13). `color` is a packed lane (`packColor`),
+ * normally the theme's cursor background. */
+export interface GridCursor {
+ col: number
+ row: number
+ shape: CursorShape
+ widthCells: number
+ color: number
+}
+
+/** The most rects any shape produces (`outline`'s four edges) — the overlay pass sizes its uniform
+ * array from this, so the two cannot drift apart. */
+export const MAX_CURSOR_RECTS = 4
+
+/** One CSS pixel at zoom 1 — the same hairline xterm's DOM renderer draws as a 1px border. */
+const BASE_THICKNESS_WORLD = 1
+
+/**
+ * The overlay rects for a shape, in fractions of ONE cell's units.
+ *
+ * `block` and `none` return `[]`: the first is drawn by the cell path (see the module comment) and
+ * the second draws nothing at all. An empty list is the caller's signal to skip the whole pass, so a
+ * degenerate cell or a zero thickness costs zero GL calls rather than a draw of no pixels.
+ *
+ * THE CORNERS ARE WRITTEN ONCE. The verticals are inset by the horizontals' thickness rather than
+ * running the full height, so no two rects of an `outline` overlap. It costs nothing today — the
+ * cursor colour is opaque — and it is what keeps the shape correct the moment anything translucent
+ * is drawn through this path (a blink fade, a themed cursor with alpha): two overlapping rects put
+ * twice the alpha on each corner, which reads as four bright dots around the cell.
+ *
+ * CLAMPED, because the thickness is derived from the CAMERA (`cursorThicknessWorld`) while the cell
+ * comes from the font: zoomed far enough out, one device pixel is thicker than the whole cell. An
+ * unclamped underline would sit at a negative `y` and an unclamped outline's verticals would have
+ * negative height — a rect that either vanishes or paints a stripe across the row.
+ */
+export function cursorOverlays(
+ shape: CursorShape,
+ widthCells: number,
+ thicknessPx: number,
+ cellW: number,
+ cellH: number
+): CursorOverlay[] {
+ if (shape === 'block' || shape === 'none') return []
+ // Guarded rather than trusted: these arrive from a live camera and a live font measurement, and a
+ // NaN here would propagate into the vertex positions of the draw call it lands in.
+ if (!(thicknessPx > 0) || !(cellW > 0) || !(cellH > 0)) return []
+ const span = cellW * (widthCells >= 2 ? 2 : 1)
+
+ if (shape === 'bar') {
+ // The bar marks the INSERTION POINT — the left edge of the cell, whatever glyph sits there — so
+ // it is one thickness wide even on a wide glyph, where widening it with the cell would draw a
+ // half-block over every CJK character.
+ return [{ x: 0, y: 0, w: Math.min(thicknessPx, span), h: cellH }]
+ }
+ if (shape === 'underline') {
+ const h = Math.min(thicknessPx, cellH)
+ return [{ x: 0, y: cellH - h, w: span, h }]
+ }
+ // outline — the hollow box a blurred terminal draws.
+ const th = Math.min(thicknessPx, cellH / 2)
+ const tv = Math.min(thicknessPx, span / 2)
+ const innerH = cellH - 2 * th
+ const rects: CursorOverlay[] = [
+ { x: 0, y: 0, w: span, h: th },
+ { x: 0, y: cellH - th, w: span, h: th }
+ ]
+ // Dropped rather than emitted with zero height: at a thickness of half the cell the two
+ // horizontals already meet, and a rect of no area is a draw the GPU does nothing with.
+ if (innerH > 0 && tv > 0) {
+ rects.push({ x: 0, y: th, w: tv, h: innerH })
+ rects.push({ x: span - tv, y: th, w: tv, h: innerH })
+ }
+ return rects
+}
+
+/**
+ * Which shape a terminal's cursor takes, from xterm's two options and the focus flag.
+ *
+ * The options arrive as plain strings — this module never imports xterm — and an UNKNOWN one
+ * degrades to the default for that focus state rather than to `none`: the values come from settings
+ * on disk, and a typo must cost the user their chosen shape, never their cursor.
+ *
+ * The row worth stating: xterm's DEFAULT `cursorInactiveStyle` is `outline`, the hollow box a
+ * blurred terminal draws. That is the shape limitation L2 said this engine could not express, so
+ * the DEFAULT path is the one this whole task exists to light up — not an exotic setting.
+ *
+ * `outline` and `none` are deliberately NOT accepted for a focused terminal: xterm's `cursorStyle`
+ * has no such members, and honouring them would let a settings typo hollow out (or extinguish) the
+ * cursor of the terminal the user is typing into.
+ */
+export function resolveCursorShape(
+ focused: boolean,
+ style: string | undefined,
+ inactiveStyle: string | undefined
+): CursorShape {
+ if (focused) {
+ // A switch, not a lookup table: `style` is an arbitrary string from disk, and indexing an object
+ // with it can answer inherited members ('constructor') as readily as own ones.
+ switch (style) {
+ case 'bar':
+ return 'bar'
+ case 'underline':
+ return 'underline'
+ default:
+ return 'block'
+ }
+ }
+ switch (inactiveStyle) {
+ case 'block':
+ return 'block'
+ case 'bar':
+ return 'bar'
+ case 'underline':
+ return 'underline'
+ case 'none':
+ return 'none'
+ default:
+ return 'outline'
+ }
+}
+
+/**
+ * The hairline's thickness in WORLD units (CSS px at zoom 1), for a camera.
+ *
+ * One CSS pixel is the mark every other renderer draws — xterm's DOM renderer uses a 1px border,
+ * and its canvas renderers scale with the same CSS transform this canvas does. The floor is the
+ * addition: `1 / (zoom * dpr)` is one DEVICE pixel expressed in world units, and a line thinner than
+ * that lands between sampled pixels — the cursor fades out exactly as the user zooms away from the
+ * terminal they are looking for. Taking the max keeps it at a CSS pixel while zoomed in (where the
+ * device pixel is the smaller number) and holds it at a device pixel once zoomed out past 1:1.
+ *
+ * A degenerate camera (zoom or dpr 0/NaN — a half-initialized context) answers the base thickness
+ * rather than Infinity or NaN, either of which would poison the rects computed from it.
+ */
+export function cursorThicknessWorld(zoom: number, dpr: number): number {
+ const scale = zoom * dpr
+ if (!(scale > 0) || !Number.isFinite(scale)) return BASE_THICKNESS_WORLD
+ return Math.max(BASE_THICKNESS_WORLD, 1 / scale)
+}
diff --git a/src/renderer/glyphgrid/engine.test.ts b/src/renderer/glyphgrid/engine.test.ts
index 364834a86..2f330497b 100644
--- a/src/renderer/glyphgrid/engine.test.ts
+++ b/src/renderer/glyphgrid/engine.test.ts
@@ -768,8 +768,100 @@ describe('plate params', () => {
plateX: -6,
plateY: -4,
plateW: 40,
- plateH: 44
+ plateH: 44,
+ // A grid nobody has told about a cursor draws none — the overlay pass is skipped whole.
+ cursor: null
}
])
})
})
+
+/** THE CURSOR OVERLAY — the per-grid spec the GL layer turns into a bar / underline / outline.
+ *
+ * The engine's job here is exactly the job it does for the plate: hold the latest value, gate it on
+ * change, and hand it to `drawGrid`. It never computes geometry (that is `cursor.ts`) and never
+ * learns what a shape looks like. */
+describe('cursor params', () => {
+ const CURSOR = { col: 3, row: 1, shape: 'bar' as const, widthCells: 1, color: 0xff00ffff }
+
+ it('a cursor set on the handle reaches drawGrid', () => {
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('a', 0))
+ h.setCursor(CURSOR)
+ e.frame()
+ expect(gl.params.at(-1)?.cursor).toEqual(CURSOR)
+ })
+
+ it('is change-gated — re-setting the same cursor draws nothing', () => {
+ // The caller re-derives this whenever it packs rows (the cursor's position comes from the same
+ // buffer state), so an unconditional dirty here would keep the shared canvas redrawing forever
+ // — the same discipline as setPlateRect.
+ const e = new GlyphGridEngine(fakeGL(), atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('a', 0))
+ h.setCursor(CURSOR)
+ expect(e.frame()).toBe(true)
+ h.setCursor({ ...CURSOR })
+ expect(e.frame()).toBe(false)
+ // Every field is compared, not just the position: a shape, width or colour change repaints too.
+ h.setCursor({ ...CURSOR, col: 4 })
+ expect(e.frame()).toBe(true)
+ h.setCursor({ ...CURSOR, col: 4, shape: 'underline' })
+ expect(e.frame()).toBe(true)
+ h.setCursor({ ...CURSOR, col: 4, shape: 'underline', widthCells: 2 })
+ expect(e.frame()).toBe(true)
+ h.setCursor({ ...CURSOR, col: 4, shape: 'underline', widthCells: 2, color: 1 })
+ expect(e.frame()).toBe(true)
+ })
+
+ it('clearing it is a change once, and a no-op thereafter', () => {
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('a', 0))
+ h.setCursor(CURSOR)
+ e.frame()
+ h.setCursor(null)
+ expect(e.frame()).toBe(true)
+ expect(gl.params.at(-1)?.cursor).toBe(null)
+ h.setCursor(null)
+ expect(e.frame()).toBe(false)
+ })
+
+ it('a HIDDEN grid’s cursor change does not wake the canvas, and rides the frame that reveals it', () => {
+ // Visibility-scoped, like updateRow and for the same reason: a cursor moves on every keystroke,
+ // and forty-five off-screen terminals typing would each wake the shared canvas for a grid the
+ // frame culls anyway. Safe for the same reason too — the cursor is a VALUE on the grid, not a
+ // range that could be lost, and every input that can change visibility dirties unconditionally.
+ const gl = fakeGL()
+ const e = new GlyphGridEngine(gl, atlas())
+ e.setViewport(100, 100, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('far', 5000))
+ e.frame() // registration damage; the grid is culled, so it is recorded as hidden
+ const woke = vi.fn()
+ e.onDamage(woke)
+ h.setCursor(CURSOR)
+ expect(woke).not.toHaveBeenCalled()
+ expect(e.frame()).toBe(false)
+ e.setCamera({ x: -5000, y: 0, zoom: 1 })
+ expect(e.frame()).toBe(true)
+ expect(gl.params.at(-1)?.cursor).toEqual(CURSOR)
+ })
+
+ it('setCursor on a disposed handle is inert — it must not un-idle the canvas', () => {
+ const e = new GlyphGridEngine(fakeGL(), atlas())
+ e.setViewport(800, 600, 1)
+ e.setCamera({ x: 0, y: 0, zoom: 1 })
+ const h = e.register(spec('a', 0))
+ h.dispose()
+ e.frame()
+ h.setCursor(CURSOR)
+ expect(e.frame()).toBe(false)
+ })
+})
diff --git a/src/renderer/glyphgrid/engine.ts b/src/renderer/glyphgrid/engine.ts
index 031efce27..520280b79 100644
--- a/src/renderer/glyphgrid/engine.ts
+++ b/src/renderer/glyphgrid/engine.ts
@@ -1,6 +1,7 @@
import type { GlyphAtlas } from './atlas'
import { rectsIntersect, visibleWorldRect, type Camera, type Rect } from './camera'
import { CELL_STRIDE } from './cells'
+import type { GridCursor } from './cursor'
import type { GlyphGL } from './gl'
/** One registered grid: a cols×rows character matrix placed in world space. `z` is the node
@@ -53,6 +54,19 @@ export interface GridHandle {
* ResizeObserver) calls both and each change-gates itself.
*/
setPlateRect(x: number, y: number, w: number, h: number): void
+ /**
+ * The cursor drawn OVER this grid's cells, or null for none.
+ *
+ * Only non-block shapes belong here: a block cursor is expressed in the CELL data (the feed swaps
+ * that cell's colours so the glyph inverts), and an overlay quad would paint over the inversion it
+ * just produced. The owner decides which — see `cursor.ts`.
+ *
+ * Change-gated on every field, and its damage is VISIBILITY-SCOPED like `updateRow`'s: the cursor
+ * moves on every keystroke, so an off-screen terminal being typed into must not wake the shared
+ * canvas. Safe for a simpler reason than the row ranges — the cursor is a VALUE, replayed from the
+ * grid on whatever frame draws it next, so nothing can be lost by deferring it.
+ */
+ setCursor(cursor: GridCursor | null): void
setZ(z: number): void
resize(cols: number, rows: number): void
/** Drops the grid. After this the handle is INERT — every mutator above becomes a silent
@@ -62,6 +76,21 @@ export interface GridHandle {
dispose(): void
}
+/** Are two cursor specs the same paint? Null-tolerant, field-by-field — the handle re-derives its
+ * spec from live buffer state, so equality is what keeps a re-derivation from dirtying the
+ * engine. */
+function sameCursor(a: GridCursor | null, b: GridCursor | null): boolean {
+ if (a === b) return true
+ if (!a || !b) return false
+ return (
+ a.col === b.col &&
+ a.row === b.row &&
+ a.shape === b.shape &&
+ a.widthCells === b.widthCells &&
+ a.color === b.color
+ )
+}
+
interface Grid extends GridSpec {
/** Row-major: the cell at (row, col) starts at lane `(row * cols + col) * CELL_STRIDE`.
* This is the layout the instanced shader binds — see gl.ts / gl-webgl2.ts.
@@ -89,6 +118,10 @@ interface Grid extends GridSpec {
* Lives on the GRID rather than in a per-frame set so `updateRow` — the hot path, called per
* terminal row — reads it off the object it already holds. */
lastVisible: boolean
+ /** The overlay cursor drawn after this grid's cells, or null. Not part of `GridSpec`: a grid is
+ * registered before its terminal has ever packed a row, so "no cursor yet" is the only honest
+ * starting state and every owner would otherwise have to spell it out. */
+ cursor: GridCursor | null
/** Set by this grid's `dispose()` AND by `disposeAll()`. It is the ONE inertness flag every
* handle reads: a handle closes over its Grid, so marking the grid reaches the handle without
* the engine having to keep a list of live handles (which would be a leak of its own — a
@@ -189,6 +222,7 @@ export class GlyphGridEngine {
dirtyFrom: 0,
dirtyTo: spec.rows - 1,
lastVisible: true,
+ cursor: null,
dead: false
}
this.grids.set(spec.id, grid)
@@ -249,6 +283,19 @@ export class GlyphGridEngine {
grid.plateH = h
engine.markDirty()
},
+ setCursor(cursor) {
+ if (grid.dead) return
+ if (sameCursor(grid.cursor, cursor)) return
+ // COPIED, not aliased: the owner re-derives one spec object per pack and would otherwise be
+ // free to mutate the value the next frame draws from — and the change gate above would
+ // never see the difference, so the canvas would keep drawing a cursor that has moved.
+ grid.cursor = cursor ? { ...cursor } : null
+ // Visibility-scoped, the ONLY mutator besides updateRow that is — see the interface comment
+ // and the long argument in updateRow. The frame that brings a hidden grid back into view is
+ // always drawn (every visibility input dirties unconditionally) and reads `grid.cursor` as
+ // it stands then, so nothing is lost by not waking the canvas for an off-screen keystroke.
+ if (grid.lastVisible) engine.markDirty()
+ },
setZ(z) {
if (grid.dead) return
if (grid.z === z) return
@@ -466,7 +513,8 @@ export class GlyphGridEngine {
plateX: g.plateX,
plateY: g.plateY,
plateW: g.plateW,
- plateH: g.plateH
+ plateH: g.plateH,
+ cursor: g.cursor
})
}
this.gl.endFrame()
diff --git a/src/renderer/glyphgrid/feed.test.ts b/src/renderer/glyphgrid/feed.test.ts
index f92b5e96f..8f765feb3 100644
--- a/src/renderer/glyphgrid/feed.test.ts
+++ b/src/renderer/glyphgrid/feed.test.ts
@@ -105,7 +105,17 @@ function decoReader(
function pack(
cells: readonly (CellView | undefined)[],
o: Partial<
- Pick<RowFeedOpts, 'cols' | 'selection' | 'cursorCol' | 'atlas' | 'decorations' | 'bufferRow'>
+ Pick<
+ RowFeedOpts,
+ | 'cols'
+ | 'selection'
+ | 'cursorCol'
+ | 'cursorShape'
+ | 'focused'
+ | 'atlas'
+ | 'decorations'
+ | 'bufferRow'
+ >
> = {}
): { out: Uint32Array; atlas: ReturnType<typeof fakeAtlas> } {
const atlas = (o.atlas as ReturnType<typeof fakeAtlas>) ?? fakeAtlas()
@@ -117,6 +127,8 @@ function pack(
theme: THEME,
selection: o.selection ?? null,
cursorCol: o.cursorCol ?? -1,
+ cursorShape: o.cursorShape,
+ focused: o.focused,
decorations: o.decorations,
bufferRow: o.bufferRow
})
@@ -344,6 +356,119 @@ describe('packViewportRow — cursor and selection', () => {
const { out } = pack([makeCell()], { selection: null, cursorCol: -1 })
expect(readCell(out, 0).flags).toBe(0)
})
+
+ it('paints BOTH cells of a wide glyph under a block cursor', () => {
+ // The lead is at col 0 and its follower (width 0) at col 1. L13 was: only col 0 got the cursor
+ // colours, so the block covered the left half of 日 and the right half stayed un-inverted.
+ const lead = makeCell({ chars: '日', code: 0x65e5, width: 2, bg: ['rgb', 0x223344] })
+ const follower = makeCell({ code: 0, width: 0, bg: ['rgb', 0x223344] })
+ const { out } = pack([lead, follower], { cursorCol: 0, cursorShape: 'block' })
+ for (const col of [0, 1]) {
+ const c = readCell(out, col)
+ expect(c.bg).toBe(THEME.cursorBg)
+ expect(c.fg).toBe(THEME.cursorFg)
+ expect(c.flags & FLAG_CURSOR).toBe(FLAG_CURSOR)
+ }
+ // The follower still owns no glyph — the lead's ink covers both columns (Phase 1c contract).
+ expect(readCell(out, 1).glyph).toBe(0)
+ })
+
+ it('carries the cursor no further than the follower of the covered lead', () => {
+ const lead = makeCell({ chars: '日', code: 0x65e5, width: 2 })
+ const follower = makeCell({ code: 0, width: 0 })
+ const after = makeCell({ code: 0x41 })
+ const { out } = pack([lead, follower, after], { cursorCol: 0, cursorShape: 'block' })
+ expect(readCell(out, 2).flags & FLAG_CURSOR).toBe(0)
+ expect(readCell(out, 2).bg).toBe(THEME.bg)
+ })
+
+ it('does not carry a cursor into a stray width-0 cell that follows a NARROW one', () => {
+ // Only a WIDE lead has a follower. A stray zero-width cell after a one-column cell under the
+ // cursor is not the other half of anything, and painting it would smear the block sideways.
+ const narrow = makeCell({ code: 0x41, width: 1 })
+ const stray = makeCell({ code: 0x300, width: 0 })
+ const { out } = pack([narrow, stray], { cursorCol: 0, cursorShape: 'block' })
+ expect(readCell(out, 1).flags & FLAG_CURSOR).toBe(0)
+ })
+
+ it('a NON-block shape leaves the cell alone — the overlay pass draws those', () => {
+ // Only the cell path can invert the glyph, and only a block wants to; bar/underline/outline are
+ // small quads drawn AFTER the cells, so rewriting the cell here would paint the block as well.
+ for (const shape of ['bar', 'underline', 'outline', 'none'] as const) {
+ const { out } = pack([makeCell({ code: 0x41, fg: ['palette', 3] })], {
+ cursorCol: 0,
+ cursorShape: shape
+ })
+ const c = readCell(out, 0)
+ expect(c.fg).toBe(THEME.ansi[3])
+ expect(c.bg).toBe(THEME.bg)
+ expect(c.flags).toBe(0)
+ }
+ })
+
+ it('a non-block shape leaves a wide glyph alone too', () => {
+ const lead = makeCell({ chars: '日', code: 0x65e5, width: 2, bg: ['rgb', 0x223344] })
+ const follower = makeCell({ code: 0, width: 0, bg: ['rgb', 0x223344] })
+ const { out } = pack([lead, follower], { cursorCol: 0, cursorShape: 'outline' })
+ for (const col of [0, 1]) {
+ expect(readCell(out, col).bg).toBe(packColor(0x22, 0x33, 0x44, 0xff))
+ expect(readCell(out, col).flags & FLAG_CURSOR).toBe(0)
+ }
+ })
+
+ it('defaults to a block when the caller names no shape', () => {
+ // Every caller that predates cursor styles passes only `cursorCol`, and a block is what it got.
+ const { out } = pack([makeCell({ code: 0x41 })], { cursorCol: 0 })
+ expect(readCell(out, 0).bg).toBe(THEME.cursorBg)
+ })
+})
+
+/** BLUR — the one thing focus changes about a packed row (limitation L3).
+ *
+ * The cursor's own blurred shape is an OVERLAY and never reaches this module; what does reach it is
+ * the selection, which xterm's own renderers paint in a separate `selectionInactiveBackground`.
+ * This engine's theme lanes carry no such colour, so the honest answer is to blend the active one
+ * toward the plate: same hue, visibly quieter, and it cannot disagree with a theme that never
+ * defined an inactive colour in the first place. */
+describe('packViewportRow — an unfocused terminal', () => {
+ it('dims the selection toward the plate when the terminal is not focused', () => {
+ const { out } = pack([makeCell({ code: 0x41 })], { selection: [0, 1], focused: false })
+ // selectionBg (0x30,0x50,0x80) blended half-way to the theme background (0x10,0x11,0x12).
+ expect(readCell(out, 0).bg).toBe(packColor(0x20, 0x31, 0x49, 0xff))
+ // Still a selection as far as the flags are concerned — only the paint is quieter.
+ expect(readCell(out, 0).flags).toBe(FLAG_SELECTED)
+ })
+
+ it('asks the atlas for a slot painted on the DIMMED selection background', () => {
+ // The atlas is colour-keyed, so a slot requested in the active colour renders in the active
+ // colour however correct the lanes are — the same trap the selection/cursor ordering exists for.
+ const { atlas } = pack([makeCell({ code: 0x41 })], { selection: [0, 1], focused: false })
+ expect(atlas.colors).toEqual([[THEME.fg, packColor(0x20, 0x31, 0x49, 0xff)]])
+ })
+
+ it('leaves everything OUTSIDE the selection exactly as it was', () => {
+ const cells = [makeCell({ code: 0x41, bg: ['palette', 7] }), makeCell({ code: 0x42 })]
+ const { out } = pack(cells, { selection: [1, 2], focused: false })
+ expect(readCell(out, 0).bg).toBe(THEME.ansi[7])
+ })
+
+ it('keeps the ACTIVE selection colour when the caller says nothing about focus', () => {
+ // Every caller that predates this passes no flag, and a focused terminal is what it meant.
+ const { out } = pack([makeCell({ code: 0x41 })], { selection: [0, 1] })
+ expect(readCell(out, 0).bg).toBe(THEME.selectionBg)
+ })
+
+ it('still lets a block cursor win over the dimmed selection', () => {
+ // A blurred terminal whose inactive style IS a block (a user setting) must not lose its cursor
+ // to the selection band under it — the precedence is a property of the overrides, not of focus.
+ const { out } = pack([makeCell({ code: 0x41 })], {
+ selection: [0, 1],
+ cursorCol: 0,
+ cursorShape: 'block',
+ focused: false
+ })
+ expect(readCell(out, 0).bg).toBe(THEME.cursorBg)
+ })
})
/** DECORATIONS — a search hit's highlight, and the precedence that makes it readable.
@@ -508,9 +633,11 @@ describe('packViewportRow — the colours the atlas is asked for', () => {
const cont = makeCell({ code: 0, width: 0, bg: ['rgb', 0x223344] })
const { out, atlas } = pack([wide, cont], { cursorCol: 0 })
expect(atlas.colors).toEqual([[THEME.cursorFg, THEME.cursorBg]])
- // The follower carries the lead's RESOLVED colours (not the cursor override, which is a
- // per-column paint) and asks for no slot of its own.
- expect(readCell(out, 1).bg).toBe(packColor(0x22, 0x33, 0x44, 0xff))
+ // The follower asks for no slot of its own — it never has — but it now PAINTS in the cursor
+ // pair rather than in the lead's own colours: the block covers the whole character, which is
+ // what closes L13. Its glyph lane stays 0, so the shader paints exactly this bg lane.
+ expect(readCell(out, 1).bg).toBe(THEME.cursorBg)
+ expect(readCell(out, 1).glyph).toBe(0)
})
})
diff --git a/src/renderer/glyphgrid/feed.ts b/src/renderer/glyphgrid/feed.ts
index b1fb7151a..ae67180fd 100644
--- a/src/renderer/glyphgrid/feed.ts
+++ b/src/renderer/glyphgrid/feed.ts
@@ -6,6 +6,7 @@
* xterm's internals, which are the part of that library most likely to move under us. */
import type { GlyphAtlas } from './atlas'
+import type { CursorShape } from './cursor'
import { decorationAt, type DecorationReader } from './decorations'
import {
FLAG_BOLD,
@@ -59,8 +60,18 @@ export interface RowFeedOpts {
theme: ThemeLanes
/** Selection span on THIS viewport row, in columns [startCol, endColExclusive), or null. */
selection: readonly [number, number] | null
- /** Block-cursor column on THIS row, or -1. (Bar/underline cursors: Phase 2 — block only.) */
+ /** The cursor's column on THIS row, or -1. */
cursorCol: number
+ /** The shape the cursor at `cursorCol` takes. Only `block` is expressible as a cell rewrite —
+ * inverting the glyph needs the atlas asked for the swapped colours, which only this pass can do
+ * — so every other shape is drawn as an OVERLAY after the cells and leaves this row untouched
+ * (see `cursor.ts`). Defaults to `block`: every caller that predates cursor styles passes only a
+ * column, and a block is what it meant. */
+ cursorShape?: CursorShape
+ /** Whether the terminal has focus. The only thing it changes HERE is the selection colour — the
+ * blurred cursor is an overlay and never reaches this module. Defaults to true, so a caller that
+ * says nothing keeps the active colours it has always had. */
+ focused?: boolean
/** The terminal's decorations (search highlights and anything else that colours cells), or
* undefined for "this terminal has none" — which is what every caller that predates them passes,
* and what an xterm build with no decoration service degrades to. */
@@ -137,6 +148,25 @@ function dimLane(c: number): number {
)
}
+/**
+ * How far an UNFOCUSED terminal's selection is blended toward the plate — limitation L3's fix.
+ *
+ * A fixed factor rather than a colour, because there is no colour to read: `ThemeLanes` carries one
+ * selection background, and xterm's own `selectionInactiveBackground` is a theme entry most themes
+ * (including nodeterm's) never define. Blending toward the background keeps the hue the theme chose
+ * and simply quiets it, which cannot disagree with a theme that never stated an inactive colour.
+ * Half-way is enough to read as "not this one" at a glance without making the selection vanish.
+ */
+const INACTIVE_SELECTION_BLEND = 0.5
+
+/** Blend two packed lanes per channel, `t` of the way from `a` to `b`. Alpha rides along, which is
+ * a no-op for the opaque lanes this feed deals in and correct if one ever is not. */
+function blendLane(a: number, b: number, t: number): number {
+ const mix = (shift: number): number =>
+ Math.round(((a >>> shift) & 0xff) + ((((b >>> shift) & 0xff) - ((a >>> shift) & 0xff)) * t))
+ return packColor(mix(0), mix(8), mix(16), mix(24))
+}
+
function resolveFg(cell: CellView, theme: ThemeLanes): number {
if (cell.isFgPalette()) return paletteLane(theme, cell.getFgColor(), theme.fg)
if (cell.isFgRGB()) return rgbLane(cell.getFgColor())
@@ -170,6 +200,13 @@ function resolveBg(cell: CellView, theme: ThemeLanes): number {
* skipped: this row buffer is REUSED across frames, so "write nothing" would leave the previous
* frame's lanes standing at that column. Every column in [0, cols) is always written.
*
+ * THE BLOCK CURSOR REACHES THE FOLLOWER, and that is the fix for limitation L13. The cursor is one
+ * COLUMN and a wide glyph is two, so applying the override to the cursor's column alone painted the
+ * left half of 日 and left the right half un-inverted. A cursor sitting on a wide LEAD therefore
+ * carries into its follower (and nowhere else — not past it, and not into a stray zero-width cell
+ * that follows a narrow one). The follower's glyph lane stays 0, per the Phase 1c contract, so the
+ * shader paints its bg lane — which is now the cursor colour.
+ *
* DECORATIONS (a search hit's highlight is one) sit between the cell's own colours and the
* selection: they OVERRIDE base/inverse/dim — a hit on coloured output has to be visible — and
* LOSE to selection and cursor. That end matters just as much: a highlight that punched a hole in
@@ -182,6 +219,10 @@ function resolveBg(cell: CellView, theme: ThemeLanes): number {
* On overlap the CURSOR WINS the colors, and BOTH flags stay set — the flags describe the cell's
* state (this cell is selected AND under the cursor), only the paint has to pick a winner.
*
+ * An UNFOCUSED terminal's selection is blended toward the plate (`INACTIVE_SELECTION_BLEND`) —
+ * limitation L3. Only the selection: the blurred CURSOR is a shape (xterm's hollow outline), and a
+ * shape is an overlay drawn after the cells, so `focused` changes nothing else in this pass.
+ *
* THE ATLAS REQUEST IS THE LAST THING THAT HAPPENS, and it has to be. The atlas is keyed by
* COLOUR: the rasterizer bakes the requested fg/bg into the slot's pixels and the shader blits
* them unmodified, so a slot requested before the overrides is painted in the cell's UNSELECTED,
@@ -199,6 +240,14 @@ export function packViewportRow(
const { cols, atlas, theme, selection, cursorCol } = opts
const selStart = selection ? selection[0] : -1
const selEnd = selection ? selection[1] : -1
+ // Only a block is a cell rewrite; every other shape is the overlay pass's business (cursor.ts).
+ const blockCursor = (opts.cursorShape ?? 'block') === 'block'
+ // Resolved ONCE per row: the selection colour cannot change mid-row, and blending it per cell
+ // would put a multiply and four roundings in the hot loop for an answer that never differs.
+ const selectionBg =
+ opts.focused === false
+ ? blendLane(theme.selectionBg, theme.bg, INACTIVE_SELECTION_BLEND)
+ : theme.selectionBg
// Hoisted out of the loop: `empty()` is answered ONCE per row rather than once per cell, and a
// terminal with no decorations leaves this null so the per-cell branch below is a null test.
const decorations = opts.decorations && !opts.decorations.empty() ? opts.decorations : null
@@ -208,9 +257,16 @@ export function packViewportRow(
let carryPending = false
let carryFg = 0
let carryBg = 0
+ /** Was the wide lead we are carrying from the one the BLOCK cursor covers? Separate from the
+ * colour carry because the colours are captured PRE-override and the cursor is applied post — the
+ * follower has to re-apply it, not inherit an already-overridden pair. */
+ let carryCursor = false
for (let col = 0; col < cols; col++) {
const cell = readCell(col, workCell)
+ // Whether the block cursor paints THIS column: its own column, or the follower half of a wide
+ // glyph whose lead it covers (set in the width-0 branch below).
+ let cursorHere = blockCursor && col === cursorCol
let fg = theme.fg
let bg = theme.bg
let flags = 0
@@ -240,8 +296,11 @@ export function packViewportRow(
if (carryPending) {
fg = carryFg
bg = carryBg
+ // The other half of the character the cursor is on — see the doc comment's L13 note.
+ if (carryCursor) cursorHere = true
}
carryPending = false
+ carryCursor = false
} else {
bold = cell.isBold() !== 0
italic = cell.isItalic() !== 0
@@ -254,18 +313,22 @@ export function packViewportRow(
if (width === 2) {
flags |= FLAG_WIDE
carryPending = true
- // The lead's RESOLVED colors, captured before the selection/cursor overrides on purpose:
- // those are decided per COLUMN, so the follower applies whichever ones cover IT. A lead
- // under the cursor therefore paints one cursor cell, not two.
+ // The lead's RESOLVED colors, captured before the selection/decoration overrides on
+ // purpose: those are decided per COLUMN, so the follower applies whichever ones cover IT.
+ // The CURSOR is the one exception, carried explicitly — a block on a wide glyph covers
+ // the whole character (L13), which a per-column rule alone cannot express.
carryFg = fg
carryBg = bg
+ carryCursor = cursorHere
} else {
carryPending = false
+ carryCursor = false
}
}
} else {
// Past the end of a short line (or no line at all): a blank cell on the theme background.
carryPending = false
+ carryCursor = false
}
// Over the cell's own colours (base/inverse/dim), under the selection and the cursor below.
@@ -278,10 +341,10 @@ export function packViewportRow(
}
if (col >= selStart && col < selEnd) {
- bg = theme.selectionBg
+ bg = selectionBg
flags |= FLAG_SELECTED
}
- if (col === cursorCol) {
+ if (cursorHere) {
fg = theme.cursorFg
bg = theme.cursorBg
flags |= FLAG_CURSOR
diff --git a/src/renderer/glyphgrid/gl-webgl2.ts b/src/renderer/glyphgrid/gl-webgl2.ts
index 0d580015e..b11cc8570 100644
--- a/src/renderer/glyphgrid/gl-webgl2.ts
+++ b/src/renderer/glyphgrid/gl-webgl2.ts
@@ -1,6 +1,7 @@
import { GUTTER_PX } from './atlas'
import { snapPanToDevicePx, type Camera } from './camera'
import { CELL_STRIDE, unpackColor } from './cells'
+import { cursorOverlays, cursorThicknessWorld, MAX_CURSOR_RECTS } from './cursor'
import type { GlyphGL, GridDrawParams } from './gl'
import { plateRectDevice } from './plate'
@@ -129,6 +130,45 @@ void main() {
outColor = texture(uAtlas, vUv);
}`
+/**
+ * The CURSOR OVERLAY program: flat-coloured quads drawn over a grid's cells.
+ *
+ * It exists because a bar / underline / outline cursor is not expressible as a cell. The cell path
+ * can only repaint a whole cell (which is exactly what a BLOCK cursor is, and why a block never
+ * reaches this program), so every other shape has to be geometry drawn on top.
+ *
+ * IT DOES NOT SAMPLE THE ATLAS, and must not: these quads are pure colour, and reading the texture
+ * would both cost a fetch per fragment and make the cursor's appearance depend on whatever slot the
+ * uv happened to land in. One instance per rect, positions taken from a uniform array rather than a
+ * vertex buffer — the whole cursor is at most four small rects (`MAX_CURSOR_RECTS`), so a buffer per
+ * frame would be more bookkeeping and more GL calls than the draw itself.
+ *
+ * The camera uniforms are duplicated rather than shared: uniforms live on a PROGRAM, so there is no
+ * such thing as sharing them between two. They are pushed per cursor draw (at most one per grid, and
+ * only for a grid that has one) instead of per frame, which keeps a canvas of terminals with block
+ * cursors — the default — at exactly zero extra GL calls.
+ */
+const CURSOR_VERT = `#version 300 es
+uniform vec2 uPan;
+uniform float uZoom;
+uniform vec2 uView;
+uniform vec4 uRects[${MAX_CURSOR_RECTS}]; // (x, y, w, h) in WORLD px, one per instance
+void main() {
+ vec4 r = uRects[gl_InstanceID];
+ int corner = gl_VertexID;
+ vec2 unit = vec2((corner == 1 || corner == 4 || corner == 5) ? 1.0 : 0.0,
+ (corner == 2 || corner == 3 || corner == 5) ? 1.0 : 0.0);
+ vec2 world = r.xy + unit * r.zw;
+ vec2 screen = world * uZoom + uPan;
+ gl_Position = vec4(screen.x / uView.x * 2.0 - 1.0, 1.0 - screen.y / uView.y * 2.0, 0.0, 1.0);
+}`
+
+const CURSOR_FRAG = `#version 300 es
+precision highp float;
+uniform vec4 uColor;
+out vec4 outColor;
+void main() { outColor = uColor; }`
+
export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
const gl = canvas.getContext('webgl2', { alpha: true, antialias: false, depth: false })
if (!gl) return null
@@ -147,6 +187,22 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
return loc
}
const aCellLoc = gl.getAttribLocation(program, 'aCell')
+ /** The overlay program, and null when it failed to build. Null is a DEGRADE, not a failure: the
+ * cells still draw, and the terminal loses only a non-block cursor — never its text. */
+ const cursorProgram = buildProgram(gl, CURSOR_VERT, CURSOR_FRAG)
+ const cursorUniforms = new Map<string, WebGLUniformLocation | null>()
+ const cu = (name: string): WebGLUniformLocation | null => {
+ if (!cursorProgram) return null
+ let loc = cursorUniforms.get(name)
+ if (loc === undefined) {
+ loc = gl.getUniformLocation(cursorProgram, name)
+ cursorUniforms.set(name, loc)
+ }
+ return loc
+ }
+ /** Scratch for the overlay's rect uniforms — one allocation for the life of the context rather
+ * than one per cursor per frame. */
+ const cursorRectData = new Float32Array(MAX_CURSOR_RECTS * 4)
/** One GPU buffer PER GRID, so a change costs only the rows that changed (bufferSubData)
* instead of re-uploading every visible grid's whole cell array into one shared buffer. */
const grids = new Map<string, { buf: WebGLBuffer; cols: number; rows: number }>()
@@ -266,6 +322,62 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
gl.disable(gl.SCISSOR_TEST)
}
+ /**
+ * The cursor overlay for one grid — the bar / underline / outline a cell cannot express.
+ *
+ * Damage-driven like everything else: this runs inside a frame the engine decided to draw, and the
+ * engine only decides that when something changed (`setCursor` is change-gated). Nothing here
+ * schedules, times or holds the rAF loop awake — a blinking cursor is Task 3's `pulse()`, not a
+ * timer hidden in the GL layer.
+ *
+ * The GEOMETRY is computed here rather than carried in `GridDrawParams` because it depends on the
+ * CAMERA: the mark is a hairline, defined in device pixels, so its world-unit thickness changes
+ * with every zoom tick (`cursorThicknessWorld`). Recomputing it per draw is four multiplications;
+ * pushing a new spec through the engine on every zoom step would be damage on every frame of a
+ * pinch gesture.
+ */
+ const drawCursor = (g: GridDrawParams): void => {
+ const c = g.cursor
+ if (!c || !cursorProgram) return
+ const rects = cursorOverlays(
+ c.shape,
+ c.widthCells,
+ cursorThicknessWorld(cam.zoom, dpr),
+ g.cellW,
+ g.cellH
+ )
+ // Empty for a block (the cell path drew it), for `none`, and for a degenerate cell. No program
+ // switch, no draw call — which is what keeps the default block cursor free.
+ if (rects.length === 0) return
+ const baseX = g.originX + c.col * g.cellW
+ const baseY = g.originY + c.row * g.cellH
+ const n = Math.min(rects.length, MAX_CURSOR_RECTS)
+ for (let i = 0; i < n; i++) {
+ const r = rects[i]
+ cursorRectData[i * 4] = baseX + r.x
+ cursorRectData[i * 4 + 1] = baseY + r.y
+ cursorRectData[i * 4 + 2] = r.w
+ cursorRectData[i * 4 + 3] = r.h
+ }
+ // The cell attribute array is disabled for the duration: it is enabled with divisor 1 and bound
+ // to the GRID's buffer, and this instanced draw asks for as many instances as there are rects.
+ // A driver that fetches enabled-but-unused arrays would read past a small grid's buffer.
+ // `drawGrid` re-enables it per grid, so nothing downstream depends on it staying on.
+ gl.disableVertexAttribArray(aCellLoc)
+ gl.useProgram(cursorProgram)
+ gl.uniform2f(cu('uPan'), cam.x, cam.y)
+ gl.uniform1f(cu('uZoom'), cam.zoom)
+ gl.uniform2f(cu('uView'), view[0], view[1])
+ gl.uniform4fv(cu('uRects'), cursorRectData.subarray(0, n * 4))
+ const col = unpackColor(c.color)
+ gl.uniform4f(cu('uColor'), col.r / 255, col.g / 255, col.b / 255, col.a / 255)
+ gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, n)
+ // RESTORED, always: `beginFrame` binds the cell program once for the whole frame, so leaving
+ // this one current would make the NEXT grid draw its cells through a shader that paints flat
+ // rectangles — a canvas of blank coloured boxes after the first terminal with a bar cursor.
+ gl.useProgram(program)
+ }
+
return {
resize(w, h, ratio) {
canvas.width = Math.round(w * ratio)
@@ -405,6 +517,10 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
gl.vertexAttribIPointer(aCellLoc, 4, gl.UNSIGNED_INT, CELL_STRIDE * 4, 0)
gl.vertexAttribDivisor(aCellLoc, 1)
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.cols * g.rows)
+
+ // --- (3) the cursor overlay, ON TOP of this grid's own cells and UNDER whatever grid is
+ // drawn after it — the same painter's order the plate and the cells already obey.
+ drawCursor(g)
},
endFrame() {
/* single-pass for now; flush point reserved for Phase 1 layering */
@@ -414,6 +530,7 @@ export function createWebgl2GL(canvas: HTMLCanvasElement): GlyphGL | null {
grids.clear()
gl.deleteTexture(atlasTex)
gl.deleteProgram(program)
+ if (cursorProgram) gl.deleteProgram(cursorProgram)
}
}
}
diff --git a/src/renderer/glyphgrid/gl.ts b/src/renderer/glyphgrid/gl.ts
index 8a81412b4..3f5f679ff 100644
--- a/src/renderer/glyphgrid/gl.ts
+++ b/src/renderer/glyphgrid/gl.ts
@@ -1,4 +1,5 @@
import type { Camera } from './camera'
+import type { GridCursor } from './cursor'
/** Per-draw parameters for one grid: where/how big it sits in world space, plus the plate.
*
@@ -39,6 +40,19 @@ export interface GridDrawParams {
plateY: number
plateW: number
plateH: number
+ /**
+ * The cursor to draw OVER this grid's cells, or null for none.
+ *
+ * Only the shapes that are not a block ever arrive here: a block cursor is a CELL REWRITE (the
+ * feed swaps the cell's colours, which is the only way to invert the glyph under it), so the cell
+ * data already carries it and an overlay would paint an opaque quad over the inversion. See
+ * `cursor.ts` — `cursorOverlays` answers `[]` for `block` for the same reason.
+ *
+ * The GEOMETRY is not carried: the rects depend on the camera (a hairline is defined in device
+ * pixels), so the implementation derives them per draw from `cursor.ts`'s pure functions rather
+ * than having the engine recompute a spec on every zoom tick.
+ */
+ cursor: GridCursor | null
}
/** Everything engine.ts is allowed to know about the GPU. Draw order is the painter's
@@ -76,8 +90,9 @@ export interface GlyphGL {
): void
/** Clears the frame and sets the camera uniforms. */
beginFrame(camera: Camera): void
- /** Draws the plate (a scissored clear of the grid's PLATE rect) and then the instanced cells
- * from the grid's OWN buffer, in call order (painter's algorithm). */
+ /** Draws the plate (a scissored clear of the grid's PLATE rect), then the instanced cells from
+ * the grid's OWN buffer, then the cursor overlay if it has one — in call order (painter's
+ * algorithm), so a grid drawn later covers all three. */
drawGrid(g: GridDrawParams): void
endFrame(): void
dispose(): void
diff --git a/src/renderer/terminal/glyphgrid-attach.ts b/src/renderer/terminal/glyphgrid-attach.ts
index da86c4a57..633e841a6 100644
--- a/src/renderer/terminal/glyphgrid-attach.ts
+++ b/src/renderer/terminal/glyphgrid-attach.ts
@@ -304,6 +304,21 @@ export function attachGlyphGrid(
dpr: () => core._coreBrowserService.dpr || 1,
theme: () => theme,
hasFocus: () => core._coreBrowserService.isFocused,
+ // The PUBLIC options object, not an internal — so this needs no guard in `coreOf` and cannot
+ // refuse an attach. Read live on every pack: the user can change either from Settings → Terminal
+ // at any moment (`applyVisualOptions` writes straight into `term.options`), and a cached copy
+ // would keep drawing yesterday's shape until the terminal happened to be re-created.
+ //
+ // xterm's DEFAULT `cursorInactiveStyle` is `outline` — the hollow box a blurred terminal draws,
+ // and precisely the shape limitation L2 said this engine could not express. So the row that
+ // looks most exotic in the mapping table is in fact the DEFAULT path: every terminal on the
+ // canvas that is not the focused one takes it. The mapping itself lives in `cursor.ts`
+ // (`resolveCursorShape`), where it is pure and unit-tested; this file only hands over the two
+ // strings, and never the focus flag — the addon tracks focus itself, see `TermInternals`.
+ cursorStyle: () => ({
+ style: term.options.cursorStyle,
+ inactiveStyle: term.options.cursorInactiveStyle
+ }),
// Spread, so a terminal with no usable decoration service leaves all three members undefined —
// the addon's "this terminal has no highlights" case.
...(decorationsOf(core) ?? {})