Report applied terminal glyph writes from the native editor

Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com>
This commit is contained in:
Brennan Benson
2026-11-13 19:07:43 -08:00
co-authored by Jinjing
parent 33e946399c
commit 656a6d0870
10 changed files with 253 additions and 39 deletions
File diff suppressed because one or more lines are too long
@@ -0,0 +1,52 @@
diff --git a/src/common/buffer/BufferLine.ts b/src/common/buffer/BufferLine.ts
index d21032f31175f9f6d738b5724e4365e85a2e2a54..eaa998c7c1159b12005ceeb81aeefd10aa04f3fb 100644
--- a/src/common/buffer/BufferLine.ts
+++ b/src/common/buffer/BufferLine.ts
@@ -66,7 +66,13 @@ const $extended = DEFAULT_ATTR_DATA.extended.clone() as IExtendedAttrsExt;
* (if only one particular value is needed) or `loadCell`. For `loadCell` in a loop
* memory allocs / GC pressure can be greatly reduced by reusing the CellData object.
*/
+export interface IBufferLineMutationObserver {
+ codepointWritten(line: BufferLine, column: number, codepoint: number, width: number): void;
+ codepointCombined(line: BufferLine, column: number, beforeUtf16Length: number, afterUtf16Length: number): void;
+}
+
export class BufferLine implements IBufferLine {
+ declare mutationObserver?: IBufferLineMutationObserver;
protected _data: Uint32Array;
/** Sparse cache; only read when `IS_COMBINED_MASK` is set in `_data`. */
protected _combined: {[index: number]: string} = {};
@@ -281,6 +287,7 @@ export class BufferLine implements IBufferLine {
this._data[$idx + Cell.CONTENT] = codePoint | (width << Content.WIDTH_SHIFT);
this._data[$idx + Cell.FG] = attrs.fg;
this._data[$idx + Cell.BG] = attrs.bg;
+ this.mutationObserver?.codepointWritten(this, index, codePoint, width);
}
/**
@@ -292,6 +299,12 @@ export class BufferLine implements IBufferLine {
public addCodepointToCell(index: number, codePoint: number, width: number): void {
this._cacheValid = false;
let content = this._data[index * Constants.CELL_INDICIES + Cell.CONTENT];
+ const observer = this.mutationObserver;
+ const beforeLength = observer
+ ? (content & Content.IS_COMBINED_MASK)
+ ? this._combined[index].length
+ : (content & Content.CODEPOINT_MASK) ? ((content & Content.CODEPOINT_MASK) > 0xffff ? 2 : 1) : 0
+ : 0;
if (content & Content.IS_COMBINED_MASK) {
// we already have a combined string, simply add
this._combined[index] += stringFromCodePoint(codePoint);
@@ -314,6 +327,12 @@ export class BufferLine implements IBufferLine {
content |= width << Content.WIDTH_SHIFT;
}
this._data[index * Constants.CELL_INDICIES + Cell.CONTENT] = content;
+ if (observer) {
+ const afterLength = (content & Content.IS_COMBINED_MASK)
+ ? this._combined[index].length
+ : (content & Content.CODEPOINT_MASK) ? ((content & Content.CODEPOINT_MASK) > 0xffff ? 2 : 1) : 0;
+ observer.codepointCombined(this, index, beforeLength, afterLength);
+ }
}
public insertCells(pos: number, n: number, fillCellData: ICellData): void {
+23
View File
@@ -136,6 +136,29 @@
"args": ["run", "esbuild-package"]
}
]
},
{
"name": "@xterm/headless",
"version": "6.1.0-beta.334",
"packageDir": ".",
"publishedDir": "headless",
"sourceMaps": ["lib-headless/xterm-headless.js.map", "lib-headless/xterm-headless.mjs.map"],
"cleanPaths": ["out", "out-esbuild", "headless/lib-headless", "headless/typings"],
"sourcePatch": "config/patches/xterm-src/@xterm__headless@6.1.0-beta.334.src.patch",
"patch": "config/patches/@xterm__headless@6.1.0-beta.334.patch",
"generatedPaths": ["lib-headless/"],
"build": [
{
"cwd": ".",
"command": "npm",
"args": ["run", "build"]
},
{
"cwd": ".",
"command": "npm",
"args": ["run", "package-headless"]
}
]
}
],
"forbiddenBuildScripts": {
@@ -24,7 +24,8 @@ import {
escapeRegExp,
formatCheckFailure,
normalizePnpmDiff,
pnpmDiffEnvironment
pnpmDiffEnvironment,
splitPatchEntries
} from './xterm-patch-text.mjs'
const DEFAULT_REPO_ROOT = path.resolve(import.meta.dirname, '../../..', '..')
@@ -252,8 +253,67 @@ function assertToolchain(upstreamRoot, manifest) {
}
}
function publishedRoot(upstreamRoot, packageEntry) {
return path.join(upstreamRoot, packageEntry.packageDir, packageEntry.publishedDir ?? '.')
}
function mapSources(directory, relative) {
const map = JSON.parse(readFileSync(path.join(directory, relative), 'utf8'))
const sources = new Map()
for (let index = 0; index < map.sources.length; index++) {
const match = /(?:^|\/)src\/(.+)$/.exec(map.sources[index])
if (!match) {
continue
}
const source = `src/${match[1]}`
const content = map.sourcesContent?.[index]
if (source.split('/').includes('..') || typeof content !== 'string' || !content) {
throw new Error(`${relative}: invalid embedded source ${source}`)
}
sources.set(source, content)
}
if (!sources.size) {
throw new Error(`${relative}: no embedded package source`)
}
return sources
}
function assertMapSourcesMatch(directory, upstreamRoot, packageEntry) {
for (const relative of packageEntry.sourceMaps) {
for (const [source, content] of mapSources(directory, relative)) {
const checkout = readFileSync(
path.join(upstreamRoot, packageEntry.packageDir, source),
'utf8'
)
if (content !== checkout) {
throw new Error(`${relative}: embedded ${source} differs from the checkout`)
}
}
}
}
function assertMapSourceChanges(pristineDir, patchedDir, packageEntry, sourcePatch) {
const expected = splitPatchEntries(sourcePatch)
.map((entry) => entry.path)
.sort()
for (const relative of packageEntry.sourceMaps) {
const pristine = mapSources(pristineDir, relative)
const patched = mapSources(patchedDir, relative)
const changed = [...new Set([...pristine.keys(), ...patched.keys()])]
.filter((source) => pristine.get(source) !== patched.get(source))
.sort()
if (JSON.stringify(changed) !== JSON.stringify(expected)) {
throw new Error(`${relative}: embedded source changes disagree with the source patch`)
}
}
}
// Match published src to pinned commit except publish-time version stamp; mismatch invalidates generated hunks.
function assertPristineSourceMatches(pristineDir, upstreamRoot, packageEntry) {
if (packageEntry.sourceMaps) {
assertMapSourcesMatch(pristineDir, upstreamRoot, packageEntry)
return
}
const stampFile = packageEntry.versionStampFile
const sourceRoot = path.join(pristineDir, 'src')
const drifted = listFilesRelative(sourceRoot)
@@ -275,7 +335,7 @@ function assertPristineSourceMatches(pristineDir, upstreamRoot, packageEntry) {
function buildPackage(upstreamRoot, packageEntry, manifest) {
const packageRoot = path.join(upstreamRoot, packageEntry.packageDir)
for (const directory of ['lib', 'out', 'out-esbuild']) {
for (const directory of packageEntry.cleanPaths ?? ['lib', 'out', 'out-esbuild']) {
rmSync(path.join(packageRoot, directory), { recursive: true, force: true })
}
if (packageEntry.versionStampFile) {
@@ -293,7 +353,7 @@ function buildPackage(upstreamRoot, packageEntry, manifest) {
/** Proves the pinned toolchain still reproduces the untouched published bundles. */
function assertReproducesPristineBundles(pristineDir, upstreamRoot, packageEntry) {
const packageRoot = path.join(upstreamRoot, packageEntry.packageDir)
const packageRoot = publishedRoot(upstreamRoot, packageEntry)
const drifted = listFilesRelative(pristineDir)
.filter((relative) =>
packageEntry.generatedPaths.some((prefix) => toPosix(relative).startsWith(prefix))
@@ -321,7 +381,7 @@ function toPosix(value) {
function overlayBuildOutput(pristineDir, upstreamRoot, packageEntry, destination) {
rmSync(destination, { recursive: true, force: true })
cpSync(pristineDir, destination, { recursive: true })
const packageRoot = path.join(upstreamRoot, packageEntry.packageDir)
const packageRoot = publishedRoot(upstreamRoot, packageEntry)
for (const relative of listFilesRelative(pristineDir)) {
// Exclude registry version/commit stamp: build tree cannot reproduce it and patch must not change it.
if (relative === 'package.json') {
@@ -409,7 +469,12 @@ function regeneratePackage(packageEntry, manifest, context) {
)
}
const patch = diffFolders(pristineDir, patchedDir)
assertSourceDerivationsAgree(source, patch)
if (packageEntry.sourceMaps) {
assertMapSourcesMatch(patchedDir, upstreamRoot, packageEntry)
assertMapSourceChanges(pristineDir, patchedDir, packageEntry, source)
} else {
assertSourceDerivationsAgree(source, patch)
}
return { patch, source }
}
+3 -2
View File
@@ -206,6 +206,7 @@ patchedDependencies:
'@xterm/addon-search@0.17.0-beta.330': eee5338dd2621ece46e79c61ec06766cd7fadaf79ffdb24e2a8ab68e97ef31f0
'@xterm/addon-serialize@0.15.0-beta.330': 17ca66ab9c7f52fc2fee94053b3b587c1210da468f3ddc7c4f5dba50b521c93e
'@xterm/addon-webgl@0.20.0-beta.329': 0d63e956bc68b3f56942e2ed9325e2bf2b1dab76ab403a0690b94232b5ef4aab
'@xterm/headless@6.1.0-beta.334': ecd2211461223bbd077cd6667672781ca503cde23ffdff382c20db6003804254
'@xterm/xterm@6.1.0-beta.336': 4b7fbfe7a7f626843ab88535cc6e2181872ea7c107876b15406a295182bc3c2c
glob@13.0.6: 163edae2cab27bf7a8cf791c9a0ee368b596bfef898e490b3b77e7e44a8f0223
i18next-cli@1.74.2: 2ee32eef742615cd133e1a6940f027deb3723a8430bb7953bba3a6769b0aac47
@@ -246,7 +247,7 @@ importers:
version: 0.15.0-beta.330(patch_hash=17ca66ab9c7f52fc2fee94053b3b587c1210da468f3ddc7c4f5dba50b521c93e)(@xterm/xterm@6.1.0-beta.336(patch_hash=4b7fbfe7a7f626843ab88535cc6e2181872ea7c107876b15406a295182bc3c2c))
'@xterm/headless':
specifier: 6.1.0-beta.334
version: 6.1.0-beta.334
version: 6.1.0-beta.334(patch_hash=ecd2211461223bbd077cd6667672781ca503cde23ffdff382c20db6003804254)
agent-browser:
specifier: ~0.39.4
version: 0.39.4
@@ -11515,7 +11516,7 @@ snapshots:
dependencies:
'@xterm/xterm': 6.1.0-beta.336(patch_hash=4b7fbfe7a7f626843ab88535cc6e2181872ea7c107876b15406a295182bc3c2c)
'@xterm/headless@6.1.0-beta.334': {}
'@xterm/headless@6.1.0-beta.334(patch_hash=ecd2211461223bbd077cd6667672781ca503cde23ffdff382c20db6003804254)': {}
'@xterm/xterm@6.1.0-beta.336(patch_hash=4b7fbfe7a7f626843ab88535cc6e2181872ea7c107876b15406a295182bc3c2c)': {}
+1
View File
@@ -118,6 +118,7 @@ overrides:
katex@>=0.11.0 <0.18.2: 0.18.10
patchedDependencies:
'@xterm/headless@6.1.0-beta.334': config/patches/@xterm__headless@6.1.0-beta.334.patch
'@xterm/addon-image@0.10.0-beta.331': config/patches/@xterm__addon-image@0.10.0-beta.331.patch
node-pty@1.1.0: config/patches/node-pty@1.1.0.patch
'@xterm/addon-ligatures@0.11.0-beta.330': config/patches/@xterm__addon-ligatures@0.11.0-beta.330.patch
@@ -12,6 +12,7 @@ import {
export type OriginCell = IBufferCell
type OriginCellAttributes = { fg?: number; bg?: number }
export type OriginBufferLine = {
mutationObserver?: Pick<HeadlessContentOrigins, 'codepointWritten' | 'codepointCombined'>
length: number
getString(index: number): string
hasContent(index: number): number
@@ -76,8 +77,6 @@ export type OriginLineMethods = Pick<
OriginBufferLine,
| 'loadCell'
| 'setCell'
| 'setCellFromCodepoint'
| 'addCodepointToCell'
| 'set'
| 'insertCells'
| 'deleteCells'
@@ -135,8 +135,25 @@ export class HeadlessContentOrigins {
}
}
combined(line: OriginBufferLine, index: number, code: number, width: number): void {
const combine = readOriginLineAttachment(line)!.originals.addCodepointToCell
codepointWritten(line: OriginBufferLine, index: number, code: number, width: number): void {
const state = readOriginLineAttachment(line)!
if (state.editing) {
this.edits.erase(state, index)
} else {
this.printed(line, index, width, code)
}
}
codepointCombined(
line: OriginBufferLine,
index: number,
beforeLength: number,
afterLength: number
): void {
if (beforeLength === 0 && afterLength > 0) {
this.writeCell(line, index, terminalOriginSpan(1, this.origin))
return
}
const pending = this.pending
if (
pending?.line === line &&
@@ -144,7 +161,6 @@ export class HeadlessContentOrigins {
index < pending.end &&
pending.origin === this.origin
) {
combine.call(line, index, code, width)
return
}
const state = this.state(line)
@@ -157,25 +173,19 @@ export class HeadlessContentOrigins {
baseOrigin.owner === this.origin.owner &&
baseOrigin.epoch === this.origin.epoch))
) {
combine.call(line, index, code, width)
this.revision++
return
}
const before = line.getString(index)
const base =
state.components?.get(index) ??
terminalOriginSpan(before.length, terminalOriginAt(state.runs, index))
combine.call(line, index, code, width)
const base = state.components?.get(index) ?? terminalOriginSpan(beforeLength, baseOrigin)
let components = state.components
const after = line.getString(index)
const joined = writeTerminalOrigins(
base,
before.length,
after.length,
terminalOriginSpan(after.length - before.length, this.origin)
beforeLength,
afterLength,
terminalOriginSpan(afterLength - beforeLength, this.origin)
)
const uniform = this.origin
? joined.length === 1 && joined[0]!.start === 0 && joined[0]!.end === after.length
? joined.length === 1 && joined[0]!.start === 0 && joined[0]!.end === afterLength
: joined.length === 0
if (uniform) {
components?.delete(index)
@@ -277,6 +287,7 @@ export class HeadlessContentOrigins {
editing: false,
recordSets: true
})
line.mutationObserver = this
Object.assign(line, originals.set ? ORIGIN_LINE_HOOKS : REQUIRED_ORIGIN_LINE_HOOKS)
return line
}
@@ -7,8 +7,6 @@ import {
const LINE_METHOD_NAMES = [
'loadCell',
'setCell',
'setCellFromCodepoint',
'addCodepointToCell',
'set',
'insertCells',
'deleteCells',
@@ -28,18 +26,6 @@ export const ORIGIN_LINE_HOOKS: OriginLineMethods = {
setCell(this: OriginBufferLine, index, cell) {
readOriginLineAttachment(this)!.owner.setCell(this, index, cell)
},
setCellFromCodepoint(this: OriginBufferLine, index, code, width, attrs) {
const state = readOriginLineAttachment(this)!
state.originals.setCellFromCodepoint.call(this, index, code, width, attrs)
if (state.editing) {
state.owner.edits.erase(state, index)
} else {
state.owner.printed(this, index, width, code)
}
},
addCodepointToCell(this: OriginBufferLine, index, code, width) {
readOriginLineAttachment(this)!.owner.combined(this, index, code, width)
},
set(this: OriginBufferLine, index, cell) {
const state = readOriginLineAttachment(this)!
state.originals.set.call(this, index, cell)
@@ -91,8 +77,6 @@ export function captureOriginLineMethods(
return {
loadCell: line.loadCell,
setCell: line.setCell,
setCellFromCodepoint: line.setCellFromCodepoint,
addCodepointToCell: line.addCodepointToCell,
set: line.set,
insertCells: line.insertCells,
deleteCells: line.deleteCells,
@@ -455,3 +455,35 @@ it('keeps loaded-cell snapshots and copied mixed glyphs independent of later sou
terminal.dispose()
}
})
it('attributes an empty-base native combine without affecting an interleaved default editor', async () => {
const terminal = new Terminal({ cols: 8, rows: 2, allowProposedApi: true })
const plain = new Terminal({ cols: 8, rows: 2, allowProposedApi: true })
const origins = new HeadlessContentOrigins(terminal)
const owner = {}
const old = { owner, epoch: 1 }
const current = { owner, epoch: 2 }
try {
origins.begin(old)
await new Promise<void>((resolve) => terminal.write('界X', resolve))
origins.end()
origins.begin(current)
await new Promise<void>((resolve) => terminal.write('\r\x1b[2G\x1b[@', resolve))
const line = originTerminalCore(terminal)!.buffers.active.lines.get(0)!
const defaultLine = originTerminalCore(plain)!.buffers.active.lines.get(0)!
defaultLine.addCodepointToCell(0, 0x1f600, 0)
line.addCodepointToCell(2, 0x1f600, 0)
origins.end()
const lines = origins.read(current)
expect(lines[0]).toBe(' 😀X')
expect(plain.buffer.active.getLine(0)!.translateToString(true)).toBe('😀')
expect(terminalScreenSupport(lines, current)?.(0, 2, 4)).toBe(true)
expect(terminalScreenSupport(lines, current)?.(0, 4, 5)).toBe(false)
expect(
terminalScreenSupport(origins.read({ owner, epoch: 3 }), { owner, epoch: 3 })?.(0, 2, 4)
).toBe(false)
} finally {
terminal.dispose()
plain.dispose()
}
})