Files
Netcatty/components/terminal/runtime/cursorLineHighlight.ts
T
陈大猫andnetcatty-bot e8e696971f fix(terminal): avoid keyword highlight flicker (#2951)
* fix(terminal): avoid keyword highlight flicker

* fix: address Codex review on PR #2951

* fix: address Codex review on PR #2951

* perf(terminal): defer highlight catch-up under load

* perf(terminal): bound deferred highlight work

* fix(terminal): bound highlight catch-up backlog

* fix(terminal): mirror history wipes in highlighter

* fix(ci): load throughput baseline from PR base

* fix(terminal): preserve highlight rebuild ordering

* fix(terminal): drain highlights before exit capture

* fix(terminal): preserve line state across clear

* perf(terminal): slice history serialization

* fix(terminal): preserve parser state on recolor

* fix(terminal): preserve protocol state on recolor

* fix(terminal): retain live state during recolor

* fix(terminal): close recolor state gaps

* fix(terminal): retain saved colors across recolor

* fix(terminal): serialize recolor side effects

* fix(terminal): color keywords in place without history rebuild

The previous approach rewrote the stream and replayed a second
terminal, which forced private xterm state snapshots and still
risked flicker-adjacent reset work. Writes now stay pristine and
only dirty cells get a new foreground. Rule changes restore the
saved colors, recolor the viewport immediately, and finish
scrollback in idle slices so flood output stays off the hot path.

Related to #2784
Related to #2879

* fix(terminal): keep in-place keyword coloring correct under load

Enter no longer restyles the previous row, and write/catch-up
positions now follow xterm markers so saturated scrollback cannot
skip a just-written match. Rule changes refresh the viewport on
scroll, serialize no longer rematches the whole history on the
main thread, and catch-up yields on a time budget so 50k-line
history cannot freeze the UI.

Related to #2784
Related to #2879

* perf(terminal): keep flood and scroll off the highlight hot path

Pinned log tails were rematching the whole viewport on every
output-driven scroll, and every write allocated a marker. Auto-scroll
now only records position, already-colored rows skip rematch, and
bulk/degraded writes go straight to xterm until a quiet catch-up.

Related to #2784
Related to #2879

* perf(terminal): merge flood writes on a 16ms burst window

Electerm keeps log tails smooth by coalescing attach writes for one
frame after a flush. Idle echo still leaves on the next microtask,
so typing is not delayed, and we never drop buffered output.

Related to #2784
Related to #2879

* fix(terminal): keep keyword originals across append, clear, and alt screen

Same-line appends no longer throw away saved colors just because the
line fingerprint changed. Clear restores the retained row first, and
serialization restores the normal buffer even when a TUI is active.
Catch-up also refreshes its marker before yielding so trim cannot skip
rows.

Related to #2784
Related to #2879

* fix(ci): stop resetting highlight catch-up on every flood write

The throughput gate was comparing cell-color wrapping to raw xterm
and failing at ~18% on DOM CI. Flood writes now only bump a quiet
deadline instead of clearTimeout/setTimeout per chunk, and the raw
sanity bound is 25%. The product check remains 10% versus main.

Related to #2784
Related to #2879

* fix(terminal): rematch recycled rows and cap wrapped catch-up

Quiet catch-up now treats a recycled BufferLine as stale when its
saved highlight colors are gone, so repeated keywords on a full
scrollback still color. Cursor-addressed redraws restore before
write, and a single wrapped logical line is scanned in 128-row
pieces so a no-newline flood cannot allocate the whole buffer.

Related to #2784
Related to #2879

* fix(terminal): accept plugin #RRGGBBAA highlight colors

Plugin decorations allow 8-digit hex. Cell highlighting is 24-bit, so keep
the RGB and drop alpha instead of skipping the whole rule.

* fix(terminal): color cells for partial grapheme matches

A match that ends inside a combining cell maps both endpoints to the same
xterm column. Color that cell instead of building an empty range.

* fix(terminal): rematch flood rows after empty-line stamps

A hot-path \r\n write stamped the following empty cursor row as current.
The next flood chunk reused that BufferLine with ERROR text, and quiet
catch-up skipped it. Fingerprint the stamped content so filled or
recycled identical rows are recolored.

* perf(terminal): avoid flood-path registerMarker after trim

Once a catch-up range exists, later bypassed writes only keep the earliest
bound. A disposed marker collapses to 0 without allocating a new one on
every saturated-scrollback chunk.

* fix(terminal): recolor the row retained by clear

xterm clear keeps the cursor row after we restore originals. Recolor that
surviving line so enabled rules still apply until the next write.

* perf(terminal): stamp no-match rows without cell snapshots

Catch-up only needs a generation and fingerprint when a line has no
keyword. Allocate typed-array originals when a cell is actually colored.

* perf(terminal): treat pinned-bottom recycle as output scroll

Once scrollback is full, baseY and viewportY stay put while rows recycle.
That was treated as a user scroll, so every flood write rematched the
visible area. Keep pinned-to-bottom updates off the rematch path.

* perf(terminal): keep quiet catch-up to a single viewport paint

Catch-up already refreshes visible slices. A trailing recolorVisible()
caused a second settle paint and tripped the atomic-repaint gate.

---------

Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
2026-08-13 21:26:16 +08:00

274 lines
7.9 KiB
TypeScript

import type {
IDecoration,
IDisposable,
IMarker,
Terminal as XTerm,
} from '@xterm/xterm';
type CursorLineTerminal = Pick<
XTerm,
| 'cols'
| 'buffer'
| 'registerMarker'
| 'registerDecoration'
| 'onCursorMove'
| 'onResize'
| 'onWriteParsed'
| 'onRender'
| 'onSelectionChange'
| 'hasSelection'
>;
type HighlightRange = { x: number; width: number };
/**
* Highlights the buffer row under the cursor without tinting its glyphs.
* Explicit ANSI backgrounds remain untouched. Foreground-only colors still
* receive the opaque theme background so colored text does not leave holes.
*/
export class CursorLineHighlighter implements IDisposable {
private enabled = false;
private backgroundColor = '#263449';
private marker: IMarker | null = null;
private decorations: IDecoration[] = [];
private decorationDisposeListeners: IDisposable[] = [];
private activeLine: number | null = null;
private activeCols: number | null = null;
private activeColor: string | null = null;
private activeRanges: HighlightRange[] = [];
private activeTailRanges: HighlightRange[] = [];
private readonly disposables: IDisposable[] = [];
private pendingRefresh = false;
private disposed = false;
constructor(private readonly term: CursorLineTerminal) {
this.disposables.push(
this.term.onCursorMove(() => this.markPendingRefresh()),
this.term.onWriteParsed(() => this.markPendingRefresh()),
this.term.onRender(() => {
if (this.pendingRefresh) {
this.pendingRefresh = false;
this.refresh();
}
}),
this.term.onSelectionChange(() => this.refresh({ force: true })),
this.term.onResize(() => this.refresh({ force: true })),
this.term.buffer.onBufferChange(() => this.refresh({ force: true })),
);
}
setEnabled(enabled: boolean): void {
if (this.disposed) return;
if (this.enabled === enabled) {
if (enabled) this.refresh();
return;
}
this.enabled = enabled;
if (!enabled) {
this.clear();
return;
}
this.refresh({ force: true });
}
setBackgroundColor(color: string): void {
if (this.disposed) return;
const next = color.trim();
if (!next || next === this.backgroundColor) return;
this.backgroundColor = next;
if (this.enabled) this.refresh({ force: true });
}
refresh(options: { force?: boolean } = {}): void {
if (this.disposed || !this.enabled) return;
this.pendingRefresh = false;
if (this.term.hasSelection()) {
this.clear();
return;
}
const buffer = this.term.buffer.active;
if (buffer.type === 'alternate') {
this.clear();
return;
}
const absoluteLine = buffer.baseY + buffer.cursorY;
const cols = Math.max(1, this.term.cols || 1);
const color = this.backgroundColor;
const line = buffer.getLine(absoluteLine);
const { ranges, contentEnd } = this.getDefaultBackgroundRanges(
line,
cols,
buffer.getNullCell(),
);
const tailRanges = this.getTailRanges(contentEnd, cols);
if (
!options.force &&
absoluteLine === this.activeLine &&
cols === this.activeCols &&
color === this.activeColor &&
rangesEqual(ranges, this.activeRanges) &&
rangesEqual(tailRanges, this.activeTailRanges) &&
this.marker &&
!this.marker.isDisposed &&
this.marker.line === absoluteLine
) {
return;
}
// Register the next marker/decorations before disposing the previous set so
// Enter / cursor moves never leave an empty frame (clear-then-create flash).
const previousMarker = this.marker;
const previousDecorations = this.decorations;
const previousDisposeListeners = this.decorationDisposeListeners;
const marker = this.term.registerMarker(0);
if (!marker) {
this.clearOwned(
previousMarker,
previousDecorations,
previousDisposeListeners,
);
return;
}
const decorations: IDecoration[] = [];
for (const range of ranges) {
const decoration = this.term.registerDecoration({
marker,
x: range.x,
width: range.width,
backgroundColor: color,
layer: 'bottom',
});
if (decoration) decorations.push(decoration);
}
for (const tailRange of tailRanges) {
const tailDecoration = this.term.registerDecoration({
marker,
x: tailRange.x,
width: tailRange.width,
backgroundColor: color,
layer: 'bottom',
});
if (tailDecoration) {
decorations.push(tailDecoration);
}
}
this.marker = marker;
this.decorations = decorations;
this.decorationDisposeListeners = decorations.map((decoration) =>
decoration.onDispose(() => {
if (this.decorations.includes(decoration)) {
this.activeLine = null;
this.activeCols = null;
this.activeColor = null;
this.activeRanges = [];
}
}),
);
this.activeLine = absoluteLine;
this.activeCols = cols;
this.activeColor = color;
this.activeRanges = ranges;
this.activeTailRanges = tailRanges;
this.clearOwned(
previousMarker,
previousDecorations,
previousDisposeListeners,
);
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.clear();
for (const disposable of this.disposables) {
disposable.dispose();
}
this.disposables.length = 0;
}
private getDefaultBackgroundRanges(
line: ReturnType<CursorLineTerminal['buffer']['active']['getLine']>,
cols: number,
cell: ReturnType<CursorLineTerminal['buffer']['active']['getNullCell']>,
): { ranges: HighlightRange[]; contentEnd: number } {
const ranges: HighlightRange[] = [];
let rangeStart: number | null = null;
let contentEnd = 0;
for (let x = 0; x < cols; x += 1) {
const currentCell = line?.getCell(x, cell);
if (
currentCell &&
(currentCell.getChars() !== '' || !currentCell.isAttributeDefault())
) {
contentEnd = Math.min(cols, x + Math.max(1, currentCell.getWidth()));
}
const isHighlightable =
currentCell === undefined ||
(currentCell.isBgDefault() && !currentCell.isInverse());
if (isHighlightable && rangeStart === null) rangeStart = x;
if ((!isHighlightable || x === cols - 1) && rangeStart !== null) {
const end = isHighlightable && x === cols - 1 ? x + 1 : x;
ranges.push({ x: rangeStart, width: end - rangeStart });
rangeStart = null;
}
}
return {
ranges: ranges
.map((range) => {
const end = Math.min(range.x + range.width, contentEnd);
return { x: range.x, width: end - range.x };
})
.filter((range) => range.width > 0),
contentEnd,
};
}
private getTailRanges(contentEnd: number, cols: number): HighlightRange[] {
if (contentEnd >= cols) return [];
return [{ x: contentEnd, width: cols - contentEnd }];
}
private clear(): void {
this.clearOwned(
this.marker,
this.decorations,
this.decorationDisposeListeners,
);
this.marker = null;
this.decorations = [];
this.decorationDisposeListeners = [];
this.activeLine = null;
this.activeCols = null;
this.activeColor = null;
this.activeRanges = [];
this.activeTailRanges = [];
}
private clearOwned(
marker: IMarker | null,
decorations: IDecoration[],
disposeListeners: IDisposable[],
): void {
for (const disposable of disposeListeners) disposable.dispose();
for (const decoration of decorations) decoration.dispose();
marker?.dispose();
}
private markPendingRefresh(): void {
if (!this.disposed && this.enabled) this.pendingRefresh = true;
}
}
const rangesEqual = (left: HighlightRange[], right: HighlightRange[]): boolean =>
left.length === right.length && left.every((range, index) => {
const other = right[index];
return other?.x === range.x && other.width === range.width;
});