Compare commits

..
Author SHA1 Message Date
Anthony Kim c9beccb3d1 Prevent image jitter when resizing in demo 2026-02-11 22:03:02 -08:00
Anthony Kim f0d291f645 Merge pull request #5694 from xtermjs/anthonykim1/cleanDemoClientTypes
Correct alphabetical ordering in demo/client/types.ts
2026-02-11 09:45:22 -08:00
Daniel Imms f6b98291cf Merge pull request #5692 from xtermjs/anthonykim1/bumpWasmIIPHandlerChanges
Update wasm decoder to 0.3.0 changes in IIPHandler.ts
2026-02-11 05:43:44 -08:00
Anthony Kim f7118b19c6 Correct alphabetical ordering in demo/client/types.ts 2026-02-10 19:08:12 -08:00
Anthony Kim d9b5d150ae Put the const integer into local const enum, save indirection time at runtime 2026-02-10 16:31:17 -08:00
Anthony Kim a25db1c76d Update wasm to 0.3.0 changes in IIPHandler.ts 2026-02-10 14:35:34 -08:00
Daniel Imms c6a572fe21 Merge pull request #5688 from Tyriar/5687
Fix kitty modifier events when only flag 2 is used
2026-02-10 01:31:15 -08:00
Daniel Imms b9fa53169f Fix kitty modifier events when only flag 2 is used
Fixes #5687
2026-02-10 01:17:44 -08:00
26 changed files with 118 additions and 2298 deletions
-3
View File
@@ -1,3 +0,0 @@
[submodule "vendor/ghostty"]
path = vendor/ghostty
url = https://github.com/ghostty-org/ghostty
+1 -1
View File
@@ -25,6 +25,6 @@
},
"devDependencies": {
"sixel": "^0.16.0",
"xterm-wasm-parts": "^0.1.0"
"xterm-wasm-parts": "^0.3.0"
}
}
+27 -14
View File
@@ -9,8 +9,15 @@ import Base64Decoder from 'xterm-wasm-parts/lib/base64/Base64Decoder.wasm';
import { HeaderParser, IHeaderFields, HeaderState } from './IIPHeaderParser';
import { imageType, UNSUPPORTED_TYPE } from './IIPMetrics';
// limit hold memory in base64 decoder
const KEEP_DATA = 4194304;
// Local const enum mirror - esbuild can't inline const enums from external packages
const enum DecoderConst {
// Limit held memory in base64 decoder (encoded bytes).
KEEP_DATA = 4194304,
// Initial buffer allocation for the decoder.
INITIAL_DATA = 1048576,
// Local mirror of const enum (esbuild can't inline const enums from external packages)
OK = 0
}
// default IIP header values
const DEFAULT_HEADER: IHeaderFields = {
@@ -27,7 +34,7 @@ export class IIPHandler implements IOscHandler, IResetHandler {
private _aborted = false;
private _hp = new HeaderParser();
private _header: IHeaderFields = DEFAULT_HEADER;
private _dec = new Base64Decoder(KEEP_DATA);
private _dec: Base64Decoder;
private _metrics = UNSUPPORTED_TYPE;
constructor(
@@ -35,7 +42,11 @@ export class IIPHandler implements IOscHandler, IResetHandler {
private readonly _renderer: ImageRenderer,
private readonly _storage: ImageStorage,
private readonly _coreTerminal: ITerminalExt
) {}
) {
const maxEncodedBytes = Math.ceil(this._opts.iipSizeLimit * 4 / 3);
const initialBytes = Math.min(DecoderConst.INITIAL_DATA, maxEncodedBytes);
this._dec = new Base64Decoder(DecoderConst.KEEP_DATA, maxEncodedBytes, initialBytes);
}
public reset(): void {}
@@ -50,7 +61,7 @@ export class IIPHandler implements IOscHandler, IResetHandler {
if (this._aborted) return;
if (this._hp.state === HeaderState.END) {
if (this._dec.put(data, start, end)) {
if ((this._dec.put(data.subarray(start, end)) as number) !== DecoderConst.OK) {
this._dec.release();
this._aborted = true;
}
@@ -66,8 +77,8 @@ export class IIPHandler implements IOscHandler, IResetHandler {
this._aborted = true;
return;
}
this._dec.init(this._header.size);
if (this._dec.put(data, dataPos, end)) {
this._dec.init();
if ((this._dec.put(data.subarray(dataPos, end)) as number) !== DecoderConst.OK) {
this._dec.release();
this._aborted = true;
}
@@ -85,13 +96,15 @@ export class IIPHandler implements IOscHandler, IResetHandler {
let cond: number | boolean = true;
if (cond = success) {
if (cond = !this._dec.end()) {
this._metrics = imageType(this._dec.data8);
if (cond = this._metrics.mime !== 'unsupported') {
w = this._metrics.width;
h = this._metrics.height;
if (cond = w && h && w * h < this._opts.pixelLimit) {
[w, h] = this._resize(w, h).map(Math.floor);
cond = w && h && w * h < this._opts.pixelLimit;
if (cond = this._dec.data8.length === this._header.size) {
this._metrics = imageType(this._dec.data8);
if (cond = this._metrics.mime !== 'unsupported') {
w = this._metrics.width;
h = this._metrics.height;
if (cond = w && h && w * h < this._opts.pixelLimit) {
[w, h] = this._resize(w, h).map(Math.floor);
cond = w && h && w * h < this._opts.pixelLimit;
}
}
}
}
+6 -8
View File
@@ -183,14 +183,12 @@ export class ImageRenderer extends Disposable implements IDisposable {
const finalWidth = count * width + sx > img.width ? img.width - sx : count * width;
const finalHeight = sy + height > img.height ? img.height - sy : height;
// Floor all pixel offsets to get stable tile mapping without any overflows.
// Note: For not pixel perfect aligned cells like in the DOM renderer
// this will move a tile slightly to the top/left (subpixel range, thus ignore it).
// FIX #34: avoid striping on displays with pixelDeviceRatio != 1 by ceiling height and width
// Let the canvas handle sub-pixel coordinates natively to avoid
// inconsistent rounding that causes tile gaps/overlaps during resize.
this._ctx.drawImage(
img,
Math.floor(sx), Math.floor(sy), Math.ceil(finalWidth), Math.ceil(finalHeight),
Math.floor(dx), Math.floor(dy), Math.ceil(finalWidth), Math.ceil(finalHeight)
sx, sy, finalWidth, finalHeight,
dx, dy, finalWidth, finalHeight
);
}
@@ -216,8 +214,8 @@ export class ImageRenderer extends Disposable implements IDisposable {
if (ctx) {
ctx.drawImage(
img,
Math.floor(sx), Math.floor(sy), Math.floor(finalWidth), Math.floor(finalHeight),
0, 0, Math.floor(finalWidth), Math.floor(finalHeight)
sx, sy, finalWidth, finalHeight,
0, 0, canvas.width, canvas.height
);
return canvas;
}
-3
View File
@@ -64,9 +64,6 @@ export class SearchEngine {
throw new Error(`Invalid col: ${startCol} to search in terminal of ${this._terminal.cols} cols`);
}
startRow = Math.max(0, startRow);
startCol = Math.max(0, startCol);
this._lineCache.initLinesCache();
const searchPosition: ISearchPosition = {
-42
View File
@@ -1,42 +0,0 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { spawnSync } from 'child_process';
import { copyFileSync, mkdirSync, renameSync } from 'fs';
import path from 'path';
import process from 'process';
import { fileURLToPath } from 'url';
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const ghosttyDir = path.join(repoRoot, 'vendor', 'ghostty');
const wasmOutDir = path.join(repoRoot, 'vendor', 'ghostty-wasm');
const wasmBinDir = path.join(wasmOutDir, 'bin');
const wasmFile = path.join(wasmOutDir, 'ghostty-vt.wasm');
const wasmBinFile = path.join(wasmBinDir, 'ghostty-vt.wasm');
mkdirSync(wasmOutDir, { recursive: true });
const result = spawnSync('zig', [
'build',
'lib-vt',
'-Dtarget=wasm32-freestanding',
'-Doptimize=ReleaseSmall',
'-p',
path.relative(ghosttyDir, wasmOutDir)
], {
cwd: ghosttyDir,
stdio: 'inherit',
shell: true
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
try {
renameSync(wasmBinFile, wasmFile);
} catch {
copyFileSync(wasmBinFile, wasmFile);
}
-3
View File
@@ -6,9 +6,6 @@
const cp = require('child_process');
const path = require('path');
globalThis.require = require;
globalThis.XTERM_GHOSTTY_WASM_URL = path.resolve(__dirname, '../vendor/ghostty-wasm/ghostty-vt.wasm');
const COVERAGE_LINES_THRESHOLD = 40;
// Add `out` to the NODE_PATH so absolute paths can be resolved.
+1 -1
View File
@@ -19,7 +19,7 @@ import type { WebFontsAddon } from '@xterm/addon-web-fonts';
import type { WebLinksAddon } from '@xterm/addon-web-links';
import type { WebglAddon } from '@xterm/addon-webgl';
export type AddonType = 'attach' | 'clipboard' | 'fit' | 'image' | 'progress' | 'search' | 'serialize' | 'unicode11' | 'unicodeGraphemes' | 'webFonts' | 'webLinks' | 'webgl' | 'ligatures';
export type AddonType = 'attach' | 'clipboard' | 'fit' | 'image' | 'ligatures' | 'progress' | 'search' | 'serialize' | 'unicode11' | 'unicodeGraphemes' | 'webFonts' | 'webLinks' | 'webgl';
export interface IDemoAddon<T extends AddonType> {
name: T;
-1
View File
@@ -46,7 +46,6 @@ function startServer(): void {
});
app.use('/fonts', express.static(demoRoot + '/fonts'));
app.use('/vendor/ghostty-wasm', express.static(demoRoot + '/../vendor/ghostty-wasm'));
app.use('/dist', express.static(demoRoot + '/dist'));
app.use('/src', express.static(demoRoot + '/src'));
+11 -279
View File
@@ -79,7 +79,7 @@
"license": "MIT",
"devDependencies": {
"sixel": "^0.16.0",
"xterm-wasm-parts": "^0.1.0"
"xterm-wasm-parts": "^0.3.0"
}
},
"addons/addon-ligatures": {
@@ -1278,102 +1278,6 @@
"url": "https://github.com/sponsors/nzakas"
}
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
"integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
"dev": true,
"dependencies": {
"string-width": "^5.1.2",
"string-width-cjs": "npm:string-width@^4.2.0",
"strip-ansi": "^7.0.1",
"strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
"wrap-ansi": "^8.1.0",
"wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@isaacs/cliui/node_modules/ansi-regex": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
"integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==",
"dev": true,
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
}
},
"node_modules/@isaacs/cliui/node_modules/ansi-styles": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"dev": true,
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/@isaacs/cliui/node_modules/emoji-regex": {
"version": "9.2.2",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
"dev": true
},
"node_modules/@isaacs/cliui/node_modules/string-width": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
"integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
"dev": true,
"dependencies": {
"eastasianwidth": "^0.2.0",
"emoji-regex": "^9.2.2",
"strip-ansi": "^7.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@isaacs/cliui/node_modules/strip-ansi": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz",
"integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==",
"dev": true,
"dependencies": {
"ansi-regex": "^6.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
"node_modules/@isaacs/cliui/node_modules/wrap-ansi": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
"integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
"dev": true,
"dependencies": {
"ansi-styles": "^6.1.0",
"string-width": "^5.0.1",
"strip-ansi": "^7.0.1"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/@istanbuljs/load-nyc-config": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
@@ -1546,16 +1450,6 @@
"pako": "^2.0.4"
}
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
"integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
"dev": true,
"optional": true,
"engines": {
"node": ">=14"
}
},
"node_modules/@playwright/test": {
"version": "1.57.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.57.0.tgz",
@@ -3511,12 +3405,6 @@
"node": ">= 0.4"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
"integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
"dev": true
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
@@ -4868,54 +4756,12 @@
"node": ">= 0.10"
}
},
"node_modules/inwasm": {
"version": "0.0.13",
"resolved": "https://registry.npmjs.org/inwasm/-/inwasm-0.0.13.tgz",
"integrity": "sha512-gmULhw1wfF3tQ19y0TvcNH6A5jN7IuTD51kbZuy+ittUU59d+ZTQMb53wbGQuciMrledgagL3/ohnjUj5qJikQ==",
"node_modules/inwasm-runtime": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/inwasm-runtime/-/inwasm-runtime-0.1.2.tgz",
"integrity": "sha512-in+Lk4d7PGwQnG1zxRe6qHB2nvvc5LUOsI9ByoJRuaDONTY8xDlaF+CvapGoPiqreJ0cMHxRzKtS0SJBccpYfA==",
"dev": true,
"dependencies": {
"acorn": "^8.8.2",
"acorn-walk": "^8.2.0",
"chokidar": "^3.5.3",
"colorette": "^2.0.20",
"glob": "^10.0.0",
"wabt": "^1.0.32"
},
"bin": {
"inwasm": "lib/cli.js"
}
},
"node_modules/inwasm/node_modules/acorn-walk": {
"version": "8.3.4",
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz",
"integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==",
"dev": true,
"dependencies": {
"acorn": "^8.11.0"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/inwasm/node_modules/glob": {
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
"dev": true,
"dependencies": {
"foreground-child": "^3.1.0",
"jackspeak": "^3.1.2",
"minimatch": "^9.0.4",
"minipass": "^7.1.2",
"package-json-from-dist": "^1.0.0",
"path-scurry": "^1.11.1"
},
"bin": {
"glob": "dist/esm/bin.mjs"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
"license": "MIT"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
@@ -5415,21 +5261,6 @@
"node": ">=8"
}
},
"node_modules/jackspeak": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
"integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
"dev": true,
"dependencies": {
"@isaacs/cliui": "^8.0.2"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
},
"optionalDependencies": {
"@pkgjs/parseargs": "^0.11.0"
}
},
"node_modules/javascript-natural-sort": {
"version": "0.7.1",
"resolved": "https://registry.npmjs.org/javascript-natural-sort/-/javascript-natural-sort-0.7.1.tgz",
@@ -5878,15 +5709,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/minipass": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
"integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
"dev": true,
"engines": {
"node": ">=16 || 14 >=14.17"
}
},
"node_modules/mkdirp": {
"version": "0.5.5",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz",
@@ -6424,12 +6246,6 @@
"node": ">=8"
}
},
"node_modules/package-json-from-dist": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"dev": true
},
"node_modules/pako": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz",
@@ -6517,28 +6333,6 @@
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
"dev": true
},
"node_modules/path-scurry": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
"integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
"dev": true,
"dependencies": {
"lru-cache": "^10.2.0",
"minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
},
"engines": {
"node": ">=16 || 14 >=14.18"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/path-scurry/node_modules/lru-cache": {
"version": "10.4.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
"dev": true
},
"node_modules/path-to-regexp": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
@@ -7532,21 +7326,6 @@
"node": ">=8"
}
},
"node_modules/string-width-cjs": {
"name": "string-width",
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dev": true,
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -7559,19 +7338,6 @@
"node": ">=8"
}
},
"node_modules/strip-ansi-cjs": {
"name": "strip-ansi",
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dev": true,
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-bom": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz",
@@ -8090,23 +7856,6 @@
"node": ">=18"
}
},
"node_modules/wabt": {
"version": "1.0.39",
"resolved": "https://registry.npmjs.org/wabt/-/wabt-1.0.39.tgz",
"integrity": "sha512-ba+dRL/75VQQY7RkU/CgriGbkoWAfS8TDyUlJfJhJ8KhtXgMl5dhNvoPNUcQ9IWRhW8u41glMSuZeTvsYq2rRg==",
"dev": true,
"bin": {
"wasm-decompile": "bin/wasm-decompile",
"wasm-interp": "bin/wasm-interp",
"wasm-objdump": "bin/wasm-objdump",
"wasm-stats": "bin/wasm-stats",
"wasm-strip": "bin/wasm-strip",
"wasm-validate": "bin/wasm-validate",
"wasm2c": "bin/wasm2c",
"wasm2wat": "bin/wasm2wat",
"wat2wasm": "bin/wat2wasm"
}
},
"node_modules/watchpack": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.0.tgz",
@@ -8450,24 +8199,6 @@
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/wrap-ansi-cjs": {
"name": "wrap-ansi",
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
"dev": true,
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
@@ -8580,12 +8311,13 @@
}
},
"node_modules/xterm-wasm-parts": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/xterm-wasm-parts/-/xterm-wasm-parts-0.1.0.tgz",
"integrity": "sha512-GFE8yNJfdkytGpcsOZhkL3B8XyUqkR/Du3SdxRyFbJg+BBCKm3raaaflgIM4TwNQ2AOLz01BEEuB5FZXx8aNTQ==",
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/xterm-wasm-parts/-/xterm-wasm-parts-0.3.0.tgz",
"integrity": "sha512-V/lhvDv2Scov2ukhTNmmur6jMq2DSL8QOdQdXWgfqcAYbUf7bgixwl2sB1gYPGE21NTw2OvbAw+vANRncWzR4w==",
"dev": true,
"license": "MIT",
"dependencies": {
"inwasm": "^0.0.13"
"inwasm-runtime": "^0.1.2"
}
},
"node_modules/y18n": {
-1
View File
@@ -45,7 +45,6 @@
"esbuild-demo-client-watch": "node bin/esbuild.mjs --demo-client --watch",
"esbuild-demo-server": "node bin/esbuild.mjs --demo-server",
"esbuild-demo-server-watch": "node bin/esbuild.mjs --demo-server --watch",
"ghostty-wasm": "node bin/build_ghostty_wasm.mjs",
"test": "npm run test-unit",
"posttest": "npm run lint",
"lint": "eslint --max-warnings 0 src/ addons/ demo/ test/",
+6 -21
View File
@@ -17,21 +17,6 @@ const INIT_ROWS = 24;
// grab wcwidth from mock unicode service (hardcoded to V6)
const wcwidth = (new MockUnicodeService()).wcwidth;
function assertLineEqual(actual: any, expected: any): void {
assert.isOk(actual);
assert.isOk(expected);
assert.equal(actual.length, expected.length);
assert.equal(actual.isWrapped, expected.isWrapped);
const actualCell = new CellData();
const expectedCell = new CellData();
for (let i = 0; i < actual.length; i++) {
assert.deepEqual(
actual.loadCell(i, actualCell).getAsCharData(),
expected.loadCell(i, expectedCell).getAsCharData()
);
}
}
describe('Terminal', () => {
let term: TestTerminal;
const termOptions = {
@@ -198,9 +183,9 @@ describe('Terminal', () => {
assert.equal(term.buffer.ybase, 0);
assert.equal(term.buffer.ydisp, 0);
assert.equal(term.buffer.lines.length, term.rows);
assertLineEqual(term.buffer.lines.get(0), promptLine);
assert.deepEqual(term.buffer.lines.get(0), promptLine);
for (let i = 1; i < term.rows; i++) {
assertLineEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
assert.deepEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
}
});
it('should clear a buffer larger than rows', async () => {
@@ -213,9 +198,9 @@ describe('Terminal', () => {
assert.equal(term.buffer.ybase, 0);
assert.equal(term.buffer.ydisp, 0);
assert.equal(term.buffer.lines.length, term.rows);
assertLineEqual(term.buffer.lines.get(0), promptLine);
assert.deepEqual(term.buffer.lines.get(0), promptLine);
for (let i = 1; i < term.rows; i++) {
assertLineEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
assert.deepEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
}
});
it('should not break the prompt when cleared twice', () => {
@@ -226,9 +211,9 @@ describe('Terminal', () => {
assert.equal(term.buffer.ybase, 0);
assert.equal(term.buffer.ydisp, 0);
assert.equal(term.buffer.lines.length, term.rows);
assertLineEqual(term.buffer.lines.get(0), promptLine);
assert.deepEqual(term.buffer.lines.get(0), promptLine);
for (let i = 1; i < term.rows; i++) {
assertLineEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
assert.deepEqual(term.buffer.lines.get(i), term.buffer.getBlankLine(DEFAULT_ATTR_DATA));
}
});
});
+7 -9
View File
@@ -7,13 +7,13 @@
import { IInputHandler, IAttributeData, IDisposable, IWindowOptions, IColorEvent, IParseStack, ColorIndex, ColorRequestType, SpecialColorIndex } from 'common/Types';
import { C0, C1 } from 'common/data/EscapeSequences';
import { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets';
import { GhosttyWasmParser } from 'common/parser/GhosttyWasmParser';
import { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser';
import { Disposable } from 'common/Lifecycle';
import { StringToUtf32, stringFromCodePoint, Utf8ToUtf32 } from 'common/input/TextDecoder';
import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
import { CellData } from 'common/buffer/CellData';
import { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
import { IParsingState, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types';
import { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content, UnderlineStyle } from 'common/buffer/Constants';
import { CellData } from 'common/buffer/CellData';
import { AttributeData } from 'common/buffer/AttributeData';
import { ICoreService, IBufferService, IOptionsService, ILogService, ICoreMouseService, ICharsetService, IUnicodeService, LogLevelEnum, IOscLinkService } from 'common/services/Services';
import { UnicodeService } from 'common/services/UnicodeService';
@@ -109,7 +109,6 @@ const SLOW_ASYNC_LIMIT = 5000;
// Work variables to avoid garbage collection
let $temp = 0;
const $workCell = new CellData();
/**
* The terminal's standard implementation of IInputHandler, this handles all
@@ -181,7 +180,7 @@ export class InputHandler extends Disposable implements IInputHandler {
private readonly _oscLinkService: IOscLinkService,
private readonly _coreMouseService: ICoreMouseService,
private readonly _unicodeService: IUnicodeService,
private readonly _parser: IEscapeSequenceParser = new GhosttyWasmParser()
private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser()
) {
super();
this._register(this._parser);
@@ -617,12 +616,11 @@ export class InputHandler extends Disposable implements IInputHandler {
if (!bufferRow) {
return;
}
if (oldWidth > 0) {
if (oldWidth > 0 && bufferRow instanceof BufferLine) {
// Combining character widens 1 column to 2.
// Move old character to next line.
for (let copyIndex = 0; copyIndex < oldWidth; copyIndex++) {
bufferRow.setCell(copyIndex, oldRow.loadCell(oldCol + copyIndex, $workCell));
}
bufferRow.copyCellsFrom(oldRow as BufferLine,
oldCol, 0, oldWidth, false);
}
// clear left over cells to the right
while (oldCol < cols) {
+17 -3
View File
@@ -5,6 +5,7 @@
import { assert } from 'chai';
import { Buffer } from 'common/buffer/Buffer';
import { CircularList } from 'common/CircularList';
import { MockOptionsService, MockBufferService, MockLogService } from 'common/TestUtils.test';
import { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
import { CellData } from 'common/buffer/CellData';
@@ -27,6 +28,7 @@ describe('Buffer', () => {
describe('constructor', () => {
it('should create a CircularList with max length equal to rows + scrollback, for its lines', () => {
assert.instanceOf(buffer.lines, CircularList);
assert.equal(buffer.lines.maxLength, bufferService.rows + INIT_SCROLLBACK);
});
it('should set the Buffer\'s scrollBottom value equal to the terminal\'s rows -1', () => {
@@ -1178,19 +1180,31 @@ describe('Buffer', () => {
});
describe('memory cleanup after shrinking', () => {
it('should keep line sizes consistent after shrinking', async () => {
it('should realign memory from idle task execution', async () => {
buffer.fillViewportRows();
// shrink more than 2 times to trigger lazy memory cleanup
buffer.resize(INIT_COLS / 2 - 1, INIT_ROWS);
// sync
for (let i = 0; i < INIT_ROWS; i++) {
const line = buffer.lines.get(i)!;
// line memory is still at old size from initialization
assert.equal((line as any)._data.buffer.byteLength, INIT_COLS * 3 * 4);
// array.length and .length get immediately adjusted
assert.equal((line as any)._data.length, (INIT_COLS / 2 - 1) * 3);
assert.equal(line.length, INIT_COLS / 2 - 1);
assert.equal(line.cleanupMemory(), 0);
}
await new Promise(r => setTimeout(r, 10));
// wait for a bit to give IdleTaskQueue a chance to kick in
// and finish memory cleaning
await new Promise(r => setTimeout(r, 30));
// cleanup should have realigned memory with exact bytelength
for (let i = 0; i < INIT_ROWS; i++) {
const line = buffer.lines.get(i)!;
assert.equal((line as any)._data.buffer.byteLength, (INIT_COLS / 2 - 1) * 3 * 4);
}
});
});
});
+11 -50
View File
@@ -3,7 +3,7 @@
* @license MIT
*/
import { IInsertEvent } from 'common/CircularList';
import { CircularList, IInsertEvent } from 'common/CircularList';
import { IdleTaskQueue } from 'common/TaskQueue';
import { IAttributeData, IBufferLine, ICellData, ICharset } from 'common/Types';
import { ExtendedAttrs } from 'common/buffer/AttributeData';
@@ -13,16 +13,11 @@ import { CellData } from 'common/buffer/CellData';
import { NULL_CELL_CHAR, NULL_CELL_CODE, NULL_CELL_WIDTH, WHITESPACE_CELL_CHAR, WHITESPACE_CELL_CODE, WHITESPACE_CELL_WIDTH } from 'common/buffer/Constants';
import { Marker } from 'common/buffer/Marker';
import { IBuffer } from 'common/buffer/Types';
import { GhosttyCircularList } from 'common/buffer/GhosttyCircularList';
import { GhosttyWasmBuffer } from 'common/buffer/GhosttyWasmBuffer';
import { DEFAULT_CHARSET } from 'common/data/Charsets';
import { IBufferService, ILogService, IOptionsService } from 'common/services/Services';
export const MAX_BUFFER_SIZE = 4294967295; // 2^32 - 1
// Work variable to avoid garbage collection during reflow
const $workCell = new CellData();
/**
* This class represents a terminal buffer (an internal state of the terminal), where the
* following information is stored (in high-level):
@@ -31,7 +26,7 @@ const $workCell = new CellData();
* - scroll position
*/
export class Buffer implements IBuffer {
public lines: GhosttyCircularList;
public lines: CircularList<IBufferLine>;
public ydisp: number = 0;
public ybase: number = 0;
public y: number = 0;
@@ -55,7 +50,6 @@ export class Buffer implements IBuffer {
private _isClearing: boolean = false;
private _memoryCleanupQueue: InstanceType<typeof IdleTaskQueue>;
private _memoryCleanupPosition = 0;
private _ghosttyBuffer: GhosttyWasmBuffer;
constructor(
private _hasScrollback: boolean,
@@ -65,9 +59,7 @@ export class Buffer implements IBuffer {
) {
this._cols = this._bufferService.cols;
this._rows = this._bufferService.rows;
const maxLength = this._getCorrectBufferLength(this._rows);
this._ghosttyBuffer = new GhosttyWasmBuffer(this._cols, this._rows, maxLength);
this.lines = new GhosttyCircularList(this._ghosttyBuffer, maxLength);
this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));
this.scrollTop = 0;
this.scrollBottom = this._rows - 1;
this.setupTabStops();
@@ -150,10 +142,7 @@ export class Buffer implements IBuffer {
this.ybase = 0;
this.y = 0;
this.x = 0;
const maxLength = this._getCorrectBufferLength(this._rows);
this._ghosttyBuffer.dispose();
this._ghosttyBuffer = new GhosttyWasmBuffer(this._cols, this._rows, maxLength);
this.lines = new GhosttyCircularList(this._ghosttyBuffer, maxLength);
this.lines = new CircularList<IBufferLine>(this._getCorrectBufferLength(this._rows));
this.scrollTop = 0;
this.scrollBottom = this._rows - 1;
this.setupTabStops();
@@ -167,8 +156,6 @@ export class Buffer implements IBuffer {
public resize(newCols: number, newRows: number): void {
// store reference to null cell with default attrs
const nullCell = this.getNullCell(DEFAULT_ATTR_DATA);
const oldCols = this._cols;
const oldMaxLength = this.lines.maxLength;
// count bufferlines with overly big memory to be cleaned afterwards
let dirtyMemoryLines = 0;
@@ -176,14 +163,6 @@ export class Buffer implements IBuffer {
// Increase max length if needed before adjustments to allow space to fill
// as required.
const newMaxLength = this._getCorrectBufferLength(newRows);
const shouldDelayColResize = this._isReflowEnabled && newCols < oldCols;
const shouldDelayRowResize = newRows < this._rows;
const canDelayResize = newMaxLength <= oldMaxLength;
const shouldDelayResize = canDelayResize && (shouldDelayColResize || shouldDelayRowResize);
const initialCols = shouldDelayColResize ? oldCols : newCols;
const initialRows = shouldDelayRowResize ? this._rows : newRows;
const initialMaxLength = shouldDelayResize ? oldMaxLength : newMaxLength;
this._ghosttyBuffer.resize(initialCols, initialRows, initialMaxLength);
if (newMaxLength > this.lines.maxLength) {
this.lines.maxLength = newMaxLength;
}
@@ -284,13 +263,6 @@ export class Buffer implements IBuffer {
}
}
if (shouldDelayResize) {
if (newRows < this._rows || newMaxLength < oldMaxLength) {
this.lines.normalize();
}
this._ghosttyBuffer.resize(newCols, newRows, newMaxLength);
}
this._cols = newCols;
this._rows = newRows;
@@ -332,7 +304,11 @@ export class Buffer implements IBuffer {
}
private get _isReflowEnabled(): boolean {
return true;
const windowsPty = this._optionsService.rawOptions.windowsPty;
if (windowsPty && windowsPty.buildNumber) {
return this._hasScrollback && windowsPty.backend === 'conpty' && windowsPty.buildNumber >= 21376;
}
return this._hasScrollback;
}
private _reflow(newCols: number, newRows: number): void {
@@ -456,19 +432,7 @@ export class Buffer implements IBuffer {
// which would stop the reflow from happening if an exception would throw.
break;
}
const destStart = destCol - cellsToCopy;
const srcStart = srcCol - cellsToCopy;
const sameLine = wrappedLines[destLineIndex] === wrappedLines[srcLineIndex];
const overlaps = sameLine && destStart < srcStart + cellsToCopy && srcStart < destStart + cellsToCopy;
if (overlaps && destStart > srcStart) {
for (let cell = cellsToCopy - 1; cell >= 0; cell--) {
wrappedLines[destLineIndex].setCell(destStart + cell, wrappedLines[srcLineIndex].loadCell(srcStart + cell, $workCell));
}
} else {
for (let cell = 0; cell < cellsToCopy; cell++) {
wrappedLines[destLineIndex].setCell(destStart + cell, wrappedLines[srcLineIndex].loadCell(srcStart + cell, $workCell));
}
}
wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol - cellsToCopy, destCol - cellsToCopy, cellsToCopy, true);
destCol -= cellsToCopy;
if (destCol === 0) {
destLineIndex--;
@@ -524,10 +488,7 @@ export class Buffer implements IBuffer {
// Record original lines so they don't get overridden when we rearrange the list
const originalLines: BufferLine[] = [];
for (let i = 0; i < this.lines.length; i++) {
const line = this.lines.get(i);
if (line) {
originalLines.push(line.clone() as BufferLine);
}
originalLines.push(this.lines.get(i) as BufferLine);
}
const originalLinesLength = this.lines.length;
+15 -28
View File
@@ -3,8 +3,9 @@
* @license MIT
*/
import { CellData } from 'common/buffer/CellData';
import { ICircularList, IBufferLine, ICellData } from 'common/Types';
import { BufferLine } from 'common/buffer/BufferLine';
import { CircularList } from 'common/CircularList';
import { IBufferLine, ICellData } from 'common/Types';
export interface INewLayoutResult {
layout: number[];
@@ -21,7 +22,7 @@ export interface INewLayoutResult {
* @param nullCell The cell data to use when filling in empty cells.
* @param reflowCursorLine Whether to reflow the line containing the cursor.
*/
export function reflowLargerGetLinesToRemove(lines: ICircularList<IBufferLine>, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData, reflowCursorLine: boolean): number[] {
export function reflowLargerGetLinesToRemove(lines: CircularList<IBufferLine>, oldCols: number, newCols: number, bufferAbsoluteY: number, nullCell: ICellData, reflowCursorLine: boolean): number[] {
// Gather all BufferLines that need to be removed from the Buffer here so that they can be
// batched up and only committed once
const toRemove: number[] = [];
@@ -29,16 +30,16 @@ export function reflowLargerGetLinesToRemove(lines: ICircularList<IBufferLine>,
for (let y = 0; y < lines.length - 1; y++) {
// Check if this row is wrapped
let i = y;
let nextLine = lines.get(++i) as IBufferLine;
let nextLine = lines.get(++i) as BufferLine;
if (!nextLine.isWrapped) {
continue;
}
// Check how many lines it's wrapped for
const wrappedLines: IBufferLine[] = [lines.get(y) as IBufferLine];
const wrappedLines: BufferLine[] = [lines.get(y) as BufferLine];
while (i < lines.length && nextLine.isWrapped) {
wrappedLines.push(nextLine);
nextLine = lines.get(++i) as IBufferLine;
nextLine = lines.get(++i) as BufferLine;
}
if (!reflowCursorLine) {
@@ -61,7 +62,7 @@ export function reflowLargerGetLinesToRemove(lines: ICircularList<IBufferLine>,
const destRemainingCells = newCols - destCol;
const cellsToCopy = Math.min(srcRemainingCells, destRemainingCells);
copyCells(wrappedLines[srcLineIndex], wrappedLines[destLineIndex], srcCol, destCol, cellsToCopy);
wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[srcLineIndex], srcCol, destCol, cellsToCopy, false);
destCol += cellsToCopy;
if (destCol === newCols) {
@@ -77,7 +78,7 @@ export function reflowLargerGetLinesToRemove(lines: ICircularList<IBufferLine>,
// Make sure the last cell isn't wide, if it is copy it to the current dest
if (destCol === 0 && destLineIndex !== 0) {
if (wrappedLines[destLineIndex - 1].getWidth(newCols - 1) === 2) {
copyCells(wrappedLines[destLineIndex - 1], wrappedLines[destLineIndex], newCols - 1, destCol++, 1);
wrappedLines[destLineIndex].copyCellsFrom(wrappedLines[destLineIndex - 1], newCols - 1, destCol++, 1, false);
// Null out the end of the last row
wrappedLines[destLineIndex - 1].setCell(newCols - 1, nullCell);
}
@@ -112,7 +113,7 @@ export function reflowLargerGetLinesToRemove(lines: ICircularList<IBufferLine>,
* @param lines The buffer lines.
* @param toRemove The indexes to remove.
*/
export function reflowLargerCreateNewLayout(lines: ICircularList<IBufferLine>, toRemove: number[]): INewLayoutResult {
export function reflowLargerCreateNewLayout(lines: CircularList<IBufferLine>, toRemove: number[]): INewLayoutResult {
const layout: number[] = [];
// First iterate through the list and get the actual indexes to use for rows
let nextToRemoveIndex = 0;
@@ -147,11 +148,11 @@ export function reflowLargerCreateNewLayout(lines: ICircularList<IBufferLine>, t
* @param lines The buffer lines.
* @param newLayout The new layout to apply.
*/
export function reflowLargerApplyNewLayout(lines: ICircularList<IBufferLine>, newLayout: number[]): void {
export function reflowLargerApplyNewLayout(lines: CircularList<IBufferLine>, newLayout: number[]): void {
// Record original lines so they don't get overridden when we rearrange the list
const newLayoutLines: IBufferLine[] = [];
const newLayoutLines: BufferLine[] = [];
for (let i = 0; i < newLayout.length; i++) {
newLayoutLines.push((lines.get(newLayout[i]) as IBufferLine).clone());
newLayoutLines.push(lines.get(newLayout[i]) as BufferLine);
}
// Rearrange the list
@@ -175,7 +176,7 @@ export function reflowLargerApplyNewLayout(lines: ICircularList<IBufferLine>, ne
* @param oldCols The columns before resize.
* @param newCols The columns after resize.
*/
export function reflowSmallerGetNewLineLengths(wrappedLines: IBufferLine[], oldCols: number, newCols: number): number[] {
export function reflowSmallerGetNewLineLengths(wrappedLines: BufferLine[], oldCols: number, newCols: number): number[] {
const newLineLengths: number[] = [];
const cellsNeeded = wrappedLines.map((l, i) => getWrappedLineTrimmedLength(wrappedLines, i, oldCols)).reduce((p, c) => p + c);
@@ -208,7 +209,7 @@ export function reflowSmallerGetNewLineLengths(wrappedLines: IBufferLine[], oldC
return newLineLengths;
}
export function getWrappedLineTrimmedLength(lines: IBufferLine[], i: number, cols: number): number {
export function getWrappedLineTrimmedLength(lines: BufferLine[], i: number, cols: number): number {
// If this is the last row in the wrapped line, get the actual trimmed length
if (i === lines.length - 1) {
return lines[i].getTrimmedLength();
@@ -223,17 +224,3 @@ export function getWrappedLineTrimmedLength(lines: IBufferLine[], i: number, col
}
return cols;
}
const workCell = new CellData();
function copyCells(src: IBufferLine, dest: IBufferLine, srcCol: number, destCol: number, length: number): void {
if (src === dest && destCol > srcCol) {
for (let i = length - 1; i >= 0; i--) {
dest.setCell(destCol + i, src.loadCell(srcCol + i, workCell));
}
return;
}
for (let i = 0; i < length; i++) {
dest.setCell(destCol + i, src.loadCell(srcCol + i, workCell));
}
}
@@ -1,44 +0,0 @@
import { assert } from 'chai';
import { GhosttyWasmBuffer } from 'common/buffer/GhosttyWasmBuffer';
import { GhosttyBufferLine } from 'common/buffer/GhosttyBufferLine';
import { DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
import { CellData } from 'common/buffer/CellData';
const WASM_PATH = 'vendor/ghostty-wasm/ghostty-vt.wasm';
describe('GhosttyBufferLine', () => {
before(() => {
(globalThis as any).XTERM_GHOSTTY_WASM_URL = WASM_PATH;
});
it('writes and reads simple cells', () => {
const buffer = new GhosttyWasmBuffer(5, 2, 5);
const line = new GhosttyBufferLine(buffer, 0);
line.setCellFromCodepoint(0, 'A'.charCodeAt(0), 1, DEFAULT_ATTR_DATA);
line.setCellFromCodepoint(1, 'B'.charCodeAt(0), 1, DEFAULT_ATTR_DATA);
assert.equal(line.translateToString(true), 'AB');
assert.equal(line.getCodePoint(0), 'A'.charCodeAt(0));
assert.equal(line.getCodePoint(1), 'B'.charCodeAt(0));
buffer.dispose();
});
it('supports insert and delete', () => {
const buffer = new GhosttyWasmBuffer(5, 1, 5);
const line = new GhosttyBufferLine(buffer, 0);
const fill = new CellData();
line.setCellFromCodepoint(0, 'A'.charCodeAt(0), 1, DEFAULT_ATTR_DATA);
line.setCellFromCodepoint(1, 'B'.charCodeAt(0), 1, DEFAULT_ATTR_DATA);
line.insertCells(1, 1, fill);
assert.equal(line.translateToString(true), 'A B');
line.deleteCells(1, 1, fill);
assert.equal(line.translateToString(true), 'AB');
buffer.dispose();
});
});
-352
View File
@@ -1,352 +0,0 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { CharData, IAttributeData, IBufferLine, ICellData, IExtendedAttrs } from 'common/Types';
import { CellData } from 'common/buffer/CellData';
import { BufferLine } from 'common/buffer/BufferLine';
import { Attributes, BgFlags, CHAR_DATA_ATTR_INDEX, CHAR_DATA_CHAR_INDEX, CHAR_DATA_WIDTH_INDEX, Content, WHITESPACE_CELL_CHAR } from 'common/buffer/Constants';
import { stringFromCodePoint } from 'common/input/TextDecoder';
import { GhosttyWasmBuffer } from 'common/buffer/GhosttyWasmBuffer';
// Work variables to avoid garbage collection
const workCell = new CellData();
export class GhosttyBufferLine implements IBufferLine {
public get length(): number {
return this._buffer.cols;
}
constructor(
private readonly _buffer: GhosttyWasmBuffer,
private readonly _row: number
) {
}
public get row(): number {
return this._row;
}
public get _extendedAttrs(): { [key: number]: IExtendedAttrs | undefined } {
const rowMap = this._buffer.getExtendedRow(this._row);
if (!rowMap) {
return {};
}
const result: { [key: number]: IExtendedAttrs | undefined } = {};
for (const [col, ext] of rowMap) {
result[col] = ext;
}
return result;
}
public get isWrapped(): boolean {
return this._buffer.getRowWrap(this._row);
}
public set isWrapped(value: boolean) {
this._buffer.setRowWrap(this._row, value);
}
public get(index: number): CharData {
const [content, fg] = this._buffer.getCell(this._row, index);
const cp = content & Content.CODEPOINT_MASK;
const combined = (content & Content.IS_COMBINED_MASK)
? this._buffer.getCombined(this._row, index) ?? ''
: '';
return [
fg,
(content & Content.IS_COMBINED_MASK)
? combined
: (cp) ? stringFromCodePoint(cp) : '',
content >> Content.WIDTH_SHIFT,
(content & Content.IS_COMBINED_MASK)
? (combined.length ? combined.charCodeAt(combined.length - 1) : 0)
: cp
];
}
public set(index: number, value: CharData): void {
const fg = value[CHAR_DATA_ATTR_INDEX];
const chars = value[CHAR_DATA_CHAR_INDEX];
if (chars.length > 1) {
this._buffer.setCombined(this._row, index, chars);
this._buffer.setCell(this._row, index, index | Content.IS_COMBINED_MASK | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT), fg, 0);
} else {
this._buffer.clearCombined(this._row, index);
this._buffer.setCell(this._row, index, chars.charCodeAt(0) | (value[CHAR_DATA_WIDTH_INDEX] << Content.WIDTH_SHIFT), fg, 0);
}
}
public loadCell(index: number, cell: ICellData): ICellData {
const [content, fg, bg] = this._buffer.getCell(this._row, index);
cell.content = content;
cell.fg = fg;
cell.bg = bg;
if (cell.content & Content.IS_COMBINED_MASK) {
cell.combinedData = this._buffer.getCombined(this._row, index) ?? '';
}
if (cell.bg & BgFlags.HAS_EXTENDED) {
cell.extended = this._buffer.getExtended(this._row, index)!;
}
return cell;
}
public setCell(index: number, cell: ICellData): void {
if (cell.content & Content.IS_COMBINED_MASK) {
this._buffer.setCombined(this._row, index, cell.combinedData);
} else {
this._buffer.clearCombined(this._row, index);
}
if (cell.bg & BgFlags.HAS_EXTENDED) {
this._buffer.setExtended(this._row, index, cell.extended);
} else {
this._buffer.clearExtended(this._row, index);
}
this._buffer.setCell(this._row, index, cell.content, cell.fg, cell.bg);
}
public setCellFromCodepoint(index: number, codePoint: number, width: number, attrs: IAttributeData): void {
if (attrs.bg & BgFlags.HAS_EXTENDED) {
this._buffer.setExtended(this._row, index, attrs.extended);
} else {
this._buffer.clearExtended(this._row, index);
}
this._buffer.clearCombined(this._row, index);
this._buffer.setCell(this._row, index, codePoint | (width << Content.WIDTH_SHIFT), attrs.fg, attrs.bg);
}
public addCodepointToCell(index: number, codePoint: number, width: number): void {
const [content, fg, bg] = this._buffer.getCell(this._row, index);
let newContent = content;
if (content & Content.IS_COMBINED_MASK) {
const existing = this._buffer.getCombined(this._row, index) ?? '';
this._buffer.setCombined(this._row, index, existing + stringFromCodePoint(codePoint));
} else {
if (content & Content.CODEPOINT_MASK) {
const existing = stringFromCodePoint(content & Content.CODEPOINT_MASK);
this._buffer.setCombined(this._row, index, existing + stringFromCodePoint(codePoint));
newContent &= ~Content.CODEPOINT_MASK;
newContent |= Content.IS_COMBINED_MASK;
} else {
newContent = codePoint | (1 << Content.WIDTH_SHIFT);
}
}
if (width) {
newContent &= ~Content.WIDTH_MASK;
newContent |= width << Content.WIDTH_SHIFT;
}
this._buffer.setCell(this._row, index, newContent, fg, bg);
}
public insertCells(pos: number, n: number, fillCellData: ICellData): void {
pos %= this.length;
if (pos && this.getWidth(pos - 1) === 2) {
this.setCellFromCodepoint(pos - 1, 0, 1, fillCellData);
}
if (n < this.length - pos) {
for (let i = this.length - pos - n - 1; i >= 0; --i) {
this.setCell(pos + n + i, this.loadCell(pos + i, workCell));
}
for (let i = 0; i < n; ++i) {
this.setCell(pos + i, fillCellData);
}
} else {
for (let i = pos; i < this.length; ++i) {
this.setCell(i, fillCellData);
}
}
if (this.getWidth(this.length - 1) === 2) {
this.setCellFromCodepoint(this.length - 1, 0, 1, fillCellData);
}
}
public deleteCells(pos: number, n: number, fillCellData: ICellData): void {
pos %= this.length;
if (n < this.length - pos) {
for (let i = 0; i < this.length - pos - n; ++i) {
this.setCell(pos + i, this.loadCell(pos + n + i, workCell));
}
for (let i = this.length - n; i < this.length; ++i) {
this.setCell(i, fillCellData);
}
} else {
for (let i = pos; i < this.length; ++i) {
this.setCell(i, fillCellData);
}
}
if (pos && this.getWidth(pos - 1) === 2) {
this.setCellFromCodepoint(pos - 1, 0, 1, fillCellData);
}
if (this.getWidth(pos) === 0 && !this.hasContent(pos)) {
this.setCellFromCodepoint(pos, 0, 1, fillCellData);
}
}
public replaceCells(start: number, end: number, fillCellData: ICellData, respectProtect: boolean = false): void {
if (respectProtect) {
if (start && this.getWidth(start - 1) === 2 && !this.isProtected(start - 1)) {
this.setCellFromCodepoint(start - 1, 0, 1, fillCellData);
}
if (end < this.length && this.getWidth(end - 1) === 2 && !this.isProtected(end)) {
this.setCellFromCodepoint(end, 0, 1, fillCellData);
}
while (start < end && start < this.length) {
if (!this.isProtected(start)) {
this.setCell(start, fillCellData);
}
start++;
}
return;
}
if (start && this.getWidth(start - 1) === 2) {
this.setCellFromCodepoint(start - 1, 0, 1, fillCellData);
}
if (end < this.length && this.getWidth(end - 1) === 2) {
this.setCellFromCodepoint(end, 0, 1, fillCellData);
}
while (start < end && start < this.length) {
this.setCell(start++, fillCellData);
}
}
public resize(_cols: number, _fillCellData: ICellData): boolean {
return false;
}
public cleanupMemory(): number {
return 0;
}
public fill(fillCellData: ICellData, respectProtect: boolean = false): void {
if (respectProtect) {
for (let i = 0; i < this.length; ++i) {
if (!this.isProtected(i)) {
this.setCell(i, fillCellData);
}
}
return;
}
for (let i = 0; i < this.length; ++i) {
this.setCell(i, fillCellData);
}
}
public copyFrom(line: IBufferLine): void {
for (let i = 0; i < this.length; ++i) {
this.setCell(i, line.loadCell(i, workCell));
}
this.isWrapped = line.isWrapped;
}
public clone(): IBufferLine {
const clone = new BufferLine(this.length);
for (let i = 0; i < this.length; ++i) {
clone.setCell(i, this.loadCell(i, workCell));
}
clone.isWrapped = this.isWrapped;
return clone;
}
public getTrimmedLength(): number {
for (let i = this.length - 1; i >= 0; --i) {
if ((this._buffer.getCell(this._row, i)[0] & Content.HAS_CONTENT_MASK)) {
return i + (this._buffer.getCell(this._row, i)[0] >> Content.WIDTH_SHIFT);
}
}
return 0;
}
public getNoBgTrimmedLength(): number {
for (let i = this.length - 1; i >= 0; --i) {
const [content, , bg] = this._buffer.getCell(this._row, i);
if ((content & Content.HAS_CONTENT_MASK) || (bg & Attributes.CM_MASK)) {
return i + (content >> Content.WIDTH_SHIFT);
}
}
return 0;
}
public translateToString(trimRight?: boolean, startCol?: number, endCol?: number, outColumns?: number[]): string {
startCol = startCol ?? 0;
endCol = endCol ?? this.length;
if (trimRight) {
endCol = Math.min(endCol, this.getTrimmedLength());
}
if (outColumns) {
outColumns.length = 0;
}
let result = '';
while (startCol < endCol) {
const content = this._buffer.getCell(this._row, startCol)[0];
const cp = content & Content.CODEPOINT_MASK;
const chars = (content & Content.IS_COMBINED_MASK)
? (this._buffer.getCombined(this._row, startCol) ?? '')
: (cp) ? stringFromCodePoint(cp) : WHITESPACE_CELL_CHAR;
result += chars;
if (outColumns) {
for (let i = 0; i < chars.length; ++i) {
outColumns.push(startCol);
}
}
startCol += (content >> Content.WIDTH_SHIFT) || 1;
}
if (outColumns) {
outColumns.push(startCol);
}
return result;
}
public getWidth(index: number): number {
return this._buffer.getCell(this._row, index)[0] >> Content.WIDTH_SHIFT;
}
public hasWidth(index: number): number {
return this._buffer.getCell(this._row, index)[0] & Content.WIDTH_MASK;
}
public getFg(index: number): number {
return this._buffer.getCell(this._row, index)[1];
}
public getBg(index: number): number {
return this._buffer.getCell(this._row, index)[2];
}
public hasContent(index: number): number {
return this._buffer.getCell(this._row, index)[0] & Content.HAS_CONTENT_MASK;
}
public getCodePoint(index: number): number {
const content = this._buffer.getCell(this._row, index)[0];
if (content & Content.IS_COMBINED_MASK) {
const combined = this._buffer.getCombined(this._row, index) ?? '';
return combined.charCodeAt(combined.length - 1);
}
return content & Content.CODEPOINT_MASK;
}
public isCombined(index: number): number {
return this._buffer.getCell(this._row, index)[0] & Content.IS_COMBINED_MASK;
}
public getString(index: number): string {
const content = this._buffer.getCell(this._row, index)[0];
if (content & Content.IS_COMBINED_MASK) {
return this._buffer.getCombined(this._row, index) ?? '';
}
if (content & Content.CODEPOINT_MASK) {
return stringFromCodePoint(content & Content.CODEPOINT_MASK);
}
return '';
}
public isProtected(index: number): number {
return this._buffer.getCell(this._row, index)[2] & BgFlags.PROTECTED;
}
}
-270
View File
@@ -1,270 +0,0 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { ICircularList, IBufferLine } from 'common/Types';
import { Disposable } from 'common/Lifecycle';
import { Emitter } from 'common/Event';
import { IDeleteEvent, IInsertEvent } from 'common/CircularList';
import { GhosttyWasmBuffer } from 'common/buffer/GhosttyWasmBuffer';
import { GhosttyBufferLine } from 'common/buffer/GhosttyBufferLine';
import { CellData } from 'common/buffer/CellData';
import { BgFlags, Content } from 'common/buffer/Constants';
export class GhosttyCircularList extends Disposable implements ICircularList<IBufferLine> {
private _startIndex: number = 0;
private _length: number = 0;
private _lines: GhosttyBufferLine[];
public readonly onDeleteEmitter = this._register(new Emitter<IDeleteEvent>());
public readonly onDelete = this.onDeleteEmitter.event;
public readonly onInsertEmitter = this._register(new Emitter<IInsertEvent>());
public readonly onInsert = this.onInsertEmitter.event;
public readonly onTrimEmitter = this._register(new Emitter<number>());
public readonly onTrim = this.onTrimEmitter.event;
private _workCell = new CellData();
constructor(
private _buffer: GhosttyWasmBuffer,
private _maxLength: number
) {
super();
this._lines = new Array<GhosttyBufferLine>(_maxLength);
for (let i = 0; i < _maxLength; i++) {
this._lines[i] = new GhosttyBufferLine(this._buffer, i);
}
}
public get maxLength(): number {
return this._maxLength;
}
public set maxLength(newMaxLength: number) {
if (this._maxLength === newMaxLength) {
return;
}
const nextLength = Math.min(newMaxLength, this.length);
const oldLines = this._getLogicalLines(nextLength);
const newLines = new Array<GhosttyBufferLine>(newMaxLength);
for (let i = 0; i < newMaxLength; i++) {
newLines[i] = new GhosttyBufferLine(this._buffer, i);
}
for (let i = 0; i < nextLength; i++) {
this._buffer.copyRow(oldLines[i].row, newLines[i].row);
}
this._lines = newLines;
this._maxLength = newMaxLength;
this._startIndex = 0;
this._length = nextLength;
}
public get length(): number {
return this._length;
}
public set length(newLength: number) {
this._length = newLength;
}
public get isFull(): boolean {
return this._length === this._maxLength;
}
public get(index: number): IBufferLine | undefined {
if (index < 0 || index >= this._length) {
return undefined;
}
return this._lines[this._getCyclicIndex(index)];
}
public set(index: number, value: IBufferLine): void {
if (index < 0) {
return;
}
if (index >= this._length) {
this._length = Math.min(index + 1, this._maxLength);
}
this._setIndex(index, value);
}
public push(value: IBufferLine): void {
if (this._length === this._maxLength) {
this._startIndex = ++this._startIndex % this._maxLength;
this.onTrimEmitter.fire(1);
} else {
this._length++;
}
this.set(this._length - 1, value);
}
public recycle(): GhosttyBufferLine {
if (!this.isFull) {
throw new Error('recycle is only supported when buffer is full');
}
this._startIndex = ++this._startIndex % this._maxLength;
this.onTrimEmitter.fire(1);
return this._lines[this._getCyclicIndex(this._length - 1)];
}
public pop(): IBufferLine | undefined {
if (this._length === 0) {
return undefined;
}
const value = this._lines[this._getCyclicIndex(this._length - 1)];
this._length--;
return value;
}
public splice(start: number, deleteCount: number, ...items: IBufferLine[]): void {
if (deleteCount === 0 && items.length === 0) {
return;
}
const before = Math.max(0, Math.min(start, this._length));
const actualDeleteCount = Math.min(deleteCount, this._length - before);
if (actualDeleteCount) {
for (let i = before; i < this._length - actualDeleteCount; i++) {
const src = this.get(i + actualDeleteCount);
if (src) {
this._setIndex(i, src);
}
}
this._length -= actualDeleteCount;
this.onDeleteEmitter.fire({ index: before, amount: actualDeleteCount });
}
if (items.length) {
for (let i = this._length - 1; i >= before; i--) {
const src = this.get(i);
if (src) {
this._setIndex(i + items.length, src);
}
}
for (let i = 0; i < items.length; i++) {
this._setIndex(before + i, items[i]);
}
this.onInsertEmitter.fire({ index: before, amount: items.length });
if (this._length + items.length > this._maxLength) {
const countToTrim = this._length + items.length - this._maxLength;
this._startIndex = (this._startIndex + countToTrim) % this._maxLength;
this._length = this._maxLength;
this.onTrimEmitter.fire(countToTrim);
} else {
this._length += items.length;
}
}
}
public trimStart(count: number): void {
if (count <= 0) {
return;
}
count = Math.min(count, this._length);
if (count > 0) {
this._startIndex = (this._startIndex + count) % this._maxLength;
this._length -= count;
this.onTrimEmitter.fire(count);
}
}
public shiftElements(start: number, count: number, offset: number): void {
if (count <= 0) {
return;
}
if (start < 0 || start >= this._length) {
throw new Error('start argument out of range');
}
if (start + offset < 0) {
throw new Error('Cannot shift elements in list beyond index 0');
}
if (offset > 0) {
for (let i = count - 1; i >= 0; i--) {
const srcLine = this.get(start + i);
if (srcLine) {
this._setIndex(start + i + offset, srcLine);
}
}
const expandListBy = (start + count + offset) - this._length;
if (expandListBy > 0) {
this._length += expandListBy;
while (this._length > this._maxLength) {
this._length--;
this._startIndex = (this._startIndex + 1) % this._maxLength;
this.onTrimEmitter.fire(1);
}
}
} else if (offset < 0) {
for (let i = 0; i < count; i++) {
const srcLine = this.get(start + i);
if (srcLine) {
this._setIndex(start + i + offset, srcLine);
}
}
}
}
public normalize(): void {
if (this._startIndex === 0) {
return;
}
const snapshot = this._getLogicalLines(this._length).map(line => line.clone());
for (let i = 0; i < snapshot.length; i++) {
this._copyInto(this._lines[i].row, snapshot[i]);
}
this._startIndex = 0;
}
private _setIndex(index: number, value: IBufferLine): void {
const line = this._lines[this._getCyclicIndex(index)];
this._copyInto(line.row, value);
}
private _getCyclicIndex(index: number): number {
return (this._startIndex + index) % this._maxLength;
}
private _copyInto(rowIndex: number, value: IBufferLine): void {
const nullContent = 1 << Content.WIDTH_SHIFT;
if (value instanceof GhosttyBufferLine) {
this._buffer.copyRow(value.row, rowIndex);
return;
}
const colsToCopy = Math.min(this._buffer.cols, value.length);
for (let col = 0; col < colsToCopy; col++) {
const cell = value.loadCell(col, this._workCell);
this._buffer.setCell(rowIndex, col, cell.content, cell.fg, cell.bg);
if (cell.content & Content.IS_COMBINED_MASK) {
this._buffer.setCombined(rowIndex, col, cell.combinedData);
} else {
this._buffer.clearCombined(rowIndex, col);
}
if (cell.bg & BgFlags.HAS_EXTENDED) {
this._buffer.setExtended(rowIndex, col, cell.extended);
} else {
this._buffer.clearExtended(rowIndex, col);
}
}
for (let col = colsToCopy; col < this._buffer.cols; col++) {
this._buffer.setCell(rowIndex, col, nullContent, 0, 0);
this._buffer.clearCombined(rowIndex, col);
this._buffer.clearExtended(rowIndex, col);
}
this._buffer.setRowWrap(rowIndex, value.isWrapped);
}
private _getLogicalLines(count: number): GhosttyBufferLine[] {
const result: GhosttyBufferLine[] = [];
for (let i = 0; i < count; i++) {
result.push(this._lines[this._getCyclicIndex(i)]);
}
return result;
}
}
-198
View File
@@ -1,198 +0,0 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { GhosttyWasmRuntime, IGhosttyWasmExports } from 'common/parser/GhosttyWasmRuntime';
import { IExtendedAttrs } from 'common/Types';
const CELL_STRIDE = 3;
export class GhosttyWasmBuffer {
private readonly _wasm: IGhosttyWasmExports;
private _handle: number;
private _cols: number;
private _rows: number;
private _maxRows: number;
private _combined = new Map<number, Map<number, string>>();
private _extended = new Map<number, Map<number, IExtendedAttrs>>();
private _cellScratchPtr: number;
constructor(cols: number, rows: number, maxRows: number) {
this._wasm = GhosttyWasmRuntime.getInstanceSync();
this._cols = cols;
this._rows = rows;
this._maxRows = maxRows;
this._handle = this._wasm.ghostty_xterm_buffer_new(cols, rows, maxRows);
if (!this._handle) {
throw new Error('Failed to allocate Ghostty xterm buffer');
}
this._cellScratchPtr = this._wasm.ghostty_wasm_alloc_u8_array(CELL_STRIDE * 4);
if (!this._cellScratchPtr) {
this._wasm.ghostty_xterm_buffer_free(this._handle);
this._handle = 0;
throw new Error('Failed to allocate Ghostty cell scratch buffer');
}
}
public dispose(): void {
if (this._handle) {
this._wasm.ghostty_xterm_buffer_free(this._handle);
this._handle = 0;
}
if (this._cellScratchPtr) {
this._wasm.ghostty_wasm_free_u8_array(this._cellScratchPtr, CELL_STRIDE * 4);
this._cellScratchPtr = 0;
}
}
public get cols(): number {
return this._cols;
}
public get rows(): number {
return this._rows;
}
public get maxRows(): number {
return this._maxRows;
}
public resize(cols: number, rows: number, maxRows: number): void {
const oldCols = this._cols;
if (!this._wasm.ghostty_xterm_buffer_resize(this._handle, cols, rows, maxRows)) {
throw new Error('Failed to resize Ghostty xterm buffer');
}
this._cols = cols;
this._rows = rows;
this._maxRows = maxRows;
if (cols < oldCols) {
for (const [row, rowMap] of this._combined) {
for (const col of rowMap.keys()) {
if (col >= cols) {
rowMap.delete(col);
}
}
if (rowMap.size === 0) {
this._combined.delete(row);
}
}
for (const [row, rowMap] of this._extended) {
for (const col of rowMap.keys()) {
if (col >= cols) {
rowMap.delete(col);
}
}
if (rowMap.size === 0) {
this._extended.delete(row);
}
}
}
}
public clear(): void {
this._wasm.ghostty_xterm_buffer_clear(this._handle);
this._combined.clear();
this._extended.clear();
}
public getCell(row: number, col: number): [number, number, number] {
this._wasm.ghostty_xterm_buffer_get_cell(this._handle, row, col, this._cellScratchPtr);
const view = new DataView(this._wasm.memory.buffer, this._cellScratchPtr, CELL_STRIDE * 4);
const content = view.getUint32(0, true);
const fg = view.getUint32(4, true);
const bg = view.getUint32(8, true);
return [content, fg, bg];
}
public setCell(row: number, col: number, content: number, fg: number, bg: number): void {
this._wasm.ghostty_xterm_buffer_set_cell(this._handle, row, col, content, fg, bg);
}
public clearRow(row: number, content: number, fg: number, bg: number): void {
this._wasm.ghostty_xterm_buffer_clear_row(this._handle, row, content, fg, bg);
this._combined.delete(row);
this._extended.delete(row);
}
public copyRow(srcRow: number, dstRow: number): void {
this._wasm.ghostty_xterm_buffer_copy_row(this._handle, srcRow, dstRow);
const combined = this._combined.get(srcRow);
if (combined) {
this._combined.set(dstRow, new Map(combined));
} else {
this._combined.delete(dstRow);
}
const extended = this._extended.get(srcRow);
if (extended) {
this._extended.set(dstRow, new Map(extended));
} else {
this._extended.delete(dstRow);
}
}
public getRowWrap(row: number): boolean {
return this._wasm.ghostty_xterm_buffer_get_row_wrap(this._handle, row) !== 0;
}
public setRowWrap(row: number, wrap: boolean): void {
this._wasm.ghostty_xterm_buffer_set_row_wrap(this._handle, row, wrap ? 1 : 0);
}
public getCombined(row: number, col: number): string | undefined {
return this._combined.get(row)?.get(col);
}
public setCombined(row: number, col: number, data: string): void {
let rowMap = this._combined.get(row);
if (!rowMap) {
rowMap = new Map();
this._combined.set(row, rowMap);
}
rowMap.set(col, data);
}
public clearCombined(row: number, col: number): void {
const rowMap = this._combined.get(row);
if (!rowMap) {
return;
}
rowMap.delete(col);
if (rowMap.size === 0) {
this._combined.delete(row);
}
}
public getExtended(row: number, col: number): IExtendedAttrs | undefined {
return this._extended.get(row)?.get(col);
}
public getExtendedRow(row: number): Map<number, IExtendedAttrs> | undefined {
return this._extended.get(row);
}
public setExtended(row: number, col: number, data: IExtendedAttrs): void {
let rowMap = this._extended.get(row);
if (!rowMap) {
rowMap = new Map();
this._extended.set(row, rowMap);
}
rowMap.set(col, data);
}
public clearExtended(row: number, col: number): void {
const rowMap = this._extended.get(row);
if (!rowMap) {
return;
}
rowMap.delete(col);
if (rowMap.size === 0) {
this._extended.delete(row);
}
}
}
+15 -1
View File
@@ -474,11 +474,25 @@ describe('KittyKeyboard', () => {
});
it('modifier key release includes its own bit cleared', () => {
const result = kitty.evaluate(createEvent({ key: 'Shift', code: 'ShiftLeft', shiftKey: false }), flags, KittyKeyboardEventType.RELEASE);
const result = kitty.evaluate(createEvent({ key: 'Shift', code: 'ShiftLeft', shiftKey: false }), flags | KittyKeyboardFlags.REPORT_ALL_KEYS_AS_ESCAPE_CODES, KittyKeyboardEventType.RELEASE);
assert.strictEqual(result.key, '\x1b[57441;1:3u');
});
});
describe('modifier-only reporting', () => {
const flags = KittyKeyboardFlags.REPORT_EVENT_TYPES;
it('does not report modifier press without REPORT_ALL_KEYS_AS_ESCAPE_CODES', () => {
const result = kitty.evaluate(createEvent({ key: 'Shift', code: 'ShiftLeft', shiftKey: true }), flags);
assert.strictEqual(result.key, undefined);
});
it('does not report modifier release without REPORT_ALL_KEYS_AS_ESCAPE_CODES', () => {
const result = kitty.evaluate(createEvent({ key: 'Shift', code: 'ShiftLeft', shiftKey: false }), flags, KittyKeyboardEventType.RELEASE);
assert.strictEqual(result.key, undefined);
});
});
describe('REPORT_ALL_KEYS_AS_ESCAPE_CODES flag', () => {
const flags = KittyKeyboardFlags.REPORT_ALL_KEYS_AS_ESCAPE_CODES;
+1 -1
View File
@@ -418,7 +418,7 @@ export class KittyKeyboard {
return result;
}
if (isMod && !(flags & KittyKeyboardFlags.REPORT_ALL_KEYS_AS_ESCAPE_CODES) && !reportEventTypes) {
if (isMod && !(flags & KittyKeyboardFlags.REPORT_ALL_KEYS_AS_ESCAPE_CODES)) {
return result;
}
-831
View File
@@ -1,831 +0,0 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { Disposable, toDisposable } from 'common/Lifecycle';
import { IDisposable } from 'common/Types';
import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType, IParserStackState, ParserStackType, IApcHandler, IApcParser, ApcFallbackHandlerType } from 'common/parser/Types';
import { OscParser } from 'common/parser/OscParser';
import { DcsParser } from 'common/parser/DcsParser';
import { ApcParser } from 'common/parser/ApcParser';
import { Params } from 'common/parser/Params';
import { StringToUtf32 } from 'common/input/TextDecoder';
import { GhosttyWasmRuntime, IGhosttyWasmExports } from 'common/parser/GhosttyWasmRuntime';
const enum RawEventTag {
PRINT = 0,
EXECUTE = 1,
ESC = 2,
CSI = 3,
OSC = 4,
DCS_HOOK = 5,
DCS_PUT = 6,
DCS_UNHOOK = 7,
APC_START = 8,
APC_PUT = 9,
APC_END = 10
}
export class GhosttyWasmParser extends Disposable implements IEscapeSequenceParser {
public precedingJoinState = 0;
private _printHandler: PrintHandlerType;
private _executeHandlers: { [flag: number]: ExecuteHandlerType };
private _csiHandlers: IHandlerCollection<CsiHandlerType>;
private _escHandlers: IHandlerCollection<EscHandlerType>;
private readonly _oscParser: OscParser;
private readonly _dcsParser: IDcsParser;
private readonly _apcParser: IApcParser;
private _errorHandler: (state: IParsingState) => IParsingState;
private _printHandlerFb: PrintFallbackHandlerType;
private _executeHandlerFb: ExecuteFallbackHandlerType;
private _csiHandlerFb: CsiFallbackHandlerType;
private _escHandlerFb: EscFallbackHandlerType;
private _errorHandlerFb: (state: IParsingState) => IParsingState;
private _parseStack: IParserStackState = {
state: ParserStackType.NONE,
handlers: [],
handlerPos: 0,
transition: 0,
chunkPos: 0
};
private _wasm?: IGhosttyWasmExports;
private _parserHandle = 0;
private _wasmReady?: Promise<boolean>;
private _eventSize = 0;
private _eventMaxParams = 0;
private _eventMaxIntermediates = 0;
private readonly _ptrSize = 4;
private _eventIndex = 0;
private _pendingEvents: { ptr: number, len: number } | undefined;
private _resumeParams: IParams | undefined;
private _textEncoder = new TextEncoder();
private _textDecoder = new TextDecoder('utf-8');
private _utf32Scratch = new Uint32Array(4096);
private _oscBuffer = new StringToUtf32();
private _dcsPutBuffer = new Uint32Array(1);
private _apcPutBuffer = new Uint32Array(1);
constructor() {
super();
this._printHandlerFb = () => { };
this._executeHandlerFb = () => { };
this._csiHandlerFb = () => { };
this._escHandlerFb = () => { };
this._errorHandlerFb = (state: IParsingState): IParsingState => state;
this._printHandler = this._printHandlerFb;
this._executeHandlers = Object.create(null);
this._csiHandlers = Object.create(null);
this._escHandlers = Object.create(null);
this._oscParser = this._register(new OscParser());
this._dcsParser = this._register(new DcsParser());
this._apcParser = this._register(new ApcParser());
this._errorHandler = this._errorHandlerFb;
this._register(toDisposable(() => {
this._csiHandlers = Object.create(null);
this._executeHandlers = Object.create(null);
this._escHandlers = Object.create(null);
}));
this._register(toDisposable(() => {
if (this._wasm && this._parserHandle) {
this._wasm.ghostty_raw_parser_free(this._parserHandle);
}
this._parserHandle = 0;
}));
this.registerEscHandler({ final: '\\' }, () => true);
}
public identToString(ident: number): string {
const res: string[] = [];
while (ident) {
res.push(String.fromCharCode(ident & 0xFF));
ident >>= 8;
}
return res.reverse().join('');
}
public setPrintHandler(handler: PrintHandlerType): void {
this._printHandler = handler;
}
public clearPrintHandler(): void {
this._printHandler = this._printHandlerFb;
}
public registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable {
const ident = this._identifier(id, [0x30, 0x7e]);
this._escHandlers[ident] ??= [];
const handlerList = this._escHandlers[ident];
handlerList.push(handler);
return {
dispose: () => {
const handlerIndex = handlerList.indexOf(handler);
if (handlerIndex !== -1) {
handlerList.splice(handlerIndex, 1);
}
}
};
}
public clearEscHandler(id: IFunctionIdentifier): void {
if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])];
}
public setEscHandlerFallback(handler: EscFallbackHandlerType): void {
this._escHandlerFb = handler;
}
public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void {
this._executeHandlers[flag.charCodeAt(0)] = handler;
}
public clearExecuteHandler(flag: string): void {
if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)];
}
public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void {
this._executeHandlerFb = handler;
}
public registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable {
const ident = this._identifier(id);
this._csiHandlers[ident] ??= [];
const handlerList = this._csiHandlers[ident];
handlerList.push(handler);
return {
dispose: () => {
const handlerIndex = handlerList.indexOf(handler);
if (handlerIndex !== -1) {
handlerList.splice(handlerIndex, 1);
}
}
};
}
public clearCsiHandler(id: IFunctionIdentifier): void {
if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)];
}
public setCsiHandlerFallback(callback: CsiFallbackHandlerType): void {
this._csiHandlerFb = callback;
}
public registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable {
return this._dcsParser.registerHandler(this._identifier(id), handler);
}
public clearDcsHandler(id: IFunctionIdentifier): void {
this._dcsParser.clearHandler(this._identifier(id));
}
public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void {
this._dcsParser.setHandlerFallback(handler);
}
public registerOscHandler(ident: number, handler: IOscHandler): IDisposable {
return this._oscParser.registerHandler(ident, handler);
}
public clearOscHandler(ident: number): void {
this._oscParser.clearHandler(ident);
}
public setOscHandlerFallback(handler: OscFallbackHandlerType): void {
this._oscParser.setHandlerFallback(handler);
}
public registerApcHandler(ident: number, handler: IApcHandler): IDisposable {
return this._apcParser.registerHandler(ident, handler);
}
public clearApcHandler(ident: number): void {
this._apcParser.clearHandler(ident);
}
public setApcHandlerFallback(handler: ApcFallbackHandlerType): void {
this._apcParser.setHandlerFallback(handler);
}
public setErrorHandler(handler: (state: IParsingState) => IParsingState): void {
this._errorHandler = handler;
}
public clearErrorHandler(): void {
this._errorHandler = this._errorHandlerFb;
}
public reset(): void {
this._oscParser.reset();
this._dcsParser.reset();
this._apcParser.reset();
this.precedingJoinState = 0;
if (this._wasm && this._parserHandle) {
this._wasm.ghostty_raw_parser_reset(this._parserHandle);
}
if (this._parseStack.state !== ParserStackType.NONE) {
this._parseStack.state = ParserStackType.RESET;
this._parseStack.handlers = [];
}
}
public parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise<boolean> {
if (!this._wasm) {
this._wasmReady ??= this._initWasm();
return this._wasmReady;
}
if (this._parseStack.state !== ParserStackType.NONE) {
return this._resume(promiseResult);
}
const bytes = this._encodeUtf32(data, length);
const result = this._writeToWasm(bytes);
if (result) {
return result;
}
return this._drainEvents();
}
private _resume(promiseResult?: boolean): void | Promise<boolean> {
if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) {
this._parseStack.state = ParserStackType.FAIL;
throw new Error('improper continuation due to previous async handler, giving up parsing');
}
switch (this._parseStack.state) {
case ParserStackType.CSI:
case ParserStackType.ESC:
return this._resumeHandlerLoop(promiseResult);
case ParserStackType.OSC:
return this._resumeOsc(promiseResult);
case ParserStackType.DCS:
return this._resumeDcs(promiseResult);
case ParserStackType.APC:
return this._resumeApc(promiseResult);
case ParserStackType.RESET:
this._parseStack.state = ParserStackType.NONE;
return;
default:
this._parseStack.state = ParserStackType.NONE;
return;
}
}
private _resumeHandlerLoop(promiseResult: boolean): void | Promise<boolean> {
const handlers = this._parseStack.handlers as CsiHandlerType[] | EscHandlerType[];
let handlerPos = this._parseStack.handlerPos - 1;
if (promiseResult === false && handlerPos > -1) {
if (this._parseStack.state === ParserStackType.CSI) {
const params = this._resumeParams ?? new Params();
for (; handlerPos >= 0; handlerPos--) {
const handlerResult = (handlers as CsiHandlerType[])[handlerPos](params);
if (handlerResult === true) {
break;
} else if (handlerResult instanceof Promise) {
this._parseStack.handlerPos = handlerPos;
return handlerResult;
}
}
} else {
for (; handlerPos >= 0; handlerPos--) {
const handlerResult = (handlers as EscHandlerType[])[handlerPos]();
if (handlerResult === true) {
break;
} else if (handlerResult instanceof Promise) {
this._parseStack.handlerPos = handlerPos;
return handlerResult;
}
}
}
}
this._resumeParams = undefined;
this._parseStack.handlers = [];
this._parseStack.state = ParserStackType.NONE;
return this._continueAfterAsync();
}
private _resumeOsc(promiseResult: boolean): void | Promise<boolean> {
const handlerResult = this._oscParser.end(true, promiseResult);
if (handlerResult) {
return handlerResult as Promise<boolean>;
}
this._parseStack.state = ParserStackType.NONE;
return this._continueAfterAsync();
}
private _resumeDcs(promiseResult: boolean): void | Promise<boolean> {
const handlerResult = this._dcsParser.unhook(true, promiseResult);
if (handlerResult) {
return handlerResult as Promise<boolean>;
}
this._parseStack.state = ParserStackType.NONE;
return this._continueAfterAsync();
}
private _resumeApc(promiseResult: boolean): void | Promise<boolean> {
const handlerResult = this._apcParser.end(true, promiseResult);
if (handlerResult) {
return handlerResult as Promise<boolean>;
}
this._parseStack.state = ParserStackType.NONE;
return this._continueAfterAsync();
}
private _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number {
let res = 0;
if (id.prefix) {
if (id.prefix.length > 1) {
throw new Error('only one byte as prefix supported');
}
res = id.prefix.charCodeAt(0);
if (res && 0x3c > res || res > 0x3f) {
throw new Error('prefix must be in range 0x3c .. 0x3f');
}
}
if (id.intermediates) {
if (id.intermediates.length > 2) {
throw new Error('only two bytes as intermediates are supported');
}
for (let i = 0; i < id.intermediates.length; ++i) {
const intermediate = id.intermediates.charCodeAt(i);
if (0x20 > intermediate || intermediate > 0x2f) {
throw new Error('intermediate must be in range 0x20 .. 0x2f');
}
res <<= 8;
res |= intermediate;
}
}
if (id.final.length !== 1) {
throw new Error('final must be a single byte');
}
const finalCode = id.final.charCodeAt(0);
if (finalRange[0] > finalCode || finalCode > finalRange[1]) {
throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`);
}
res <<= 8;
res |= finalCode;
return res;
}
private async _initWasm(): Promise<boolean> {
this._wasm = await GhosttyWasmRuntime.getInstance();
this._parserHandle = this._wasm.ghostty_raw_parser_new(0);
this._eventSize = this._wasm.ghostty_raw_parser_event_size();
this._eventMaxParams = this._wasm.ghostty_raw_parser_max_params();
this._eventMaxIntermediates = this._wasm.ghostty_raw_parser_max_intermediates();
return true;
}
private _encodeUtf32(data: Uint32Array, length: number): Uint8Array {
if (length === 0) {
return new Uint8Array(0);
}
const bytes: number[] = [];
for (let i = 0; i < length; i++) {
const codePoint = data[i];
if (codePoint === 0x9c) {
bytes.push(0x1b, 0x5c);
continue;
}
if (codePoint <= 0x7f || (codePoint >= 0x80 && codePoint <= 0x9f)) {
bytes.push(codePoint);
} else if (codePoint <= 0x7ff) {
bytes.push(
0xc0 | (codePoint >> 6),
0x80 | (codePoint & 0x3f)
);
} else if (codePoint <= 0xffff) {
bytes.push(
0xe0 | (codePoint >> 12),
0x80 | ((codePoint >> 6) & 0x3f),
0x80 | (codePoint & 0x3f)
);
} else {
bytes.push(
0xf0 | (codePoint >> 18),
0x80 | ((codePoint >> 12) & 0x3f),
0x80 | ((codePoint >> 6) & 0x3f),
0x80 | (codePoint & 0x3f)
);
}
}
return new Uint8Array(bytes);
}
private _writeToWasm(bytes: Uint8Array): void | Promise<boolean> {
if (!this._wasm || !this._parserHandle) {
return;
}
if (!bytes.length) {
return;
}
const dataPtr = this._wasm.ghostty_wasm_alloc_u8_array(bytes.length);
if (!dataPtr) {
return;
}
const mem = new Uint8Array(this._wasm.memory.buffer, dataPtr, bytes.length);
mem.set(bytes);
this._wasm.ghostty_raw_parser_write(this._parserHandle, dataPtr, bytes.length);
this._wasm.ghostty_wasm_free_u8_array(dataPtr, bytes.length);
}
private _drainEvents(): void | Promise<boolean> {
if (!this._wasm || !this._parserHandle) {
return;
}
const eventsPtr = this._wasm.ghostty_raw_parser_events_ptr(this._parserHandle);
const eventsLen = this._wasm.ghostty_raw_parser_events_len(this._parserHandle);
if (!eventsPtr || !eventsLen) {
this._wasm.ghostty_raw_parser_events_clear(this._parserHandle);
return;
}
this._pendingEvents = { ptr: eventsPtr, len: eventsLen };
this._eventIndex = 0;
const result = this._processEvents();
if (result) {
return result;
}
this._wasm.ghostty_raw_parser_events_clear(this._parserHandle);
this._pendingEvents = undefined;
}
private _continueAfterAsync(): void | Promise<boolean> {
if (!this._wasm || !this._parserHandle || !this._pendingEvents) {
return;
}
this._eventIndex++;
const result = this._processEvents();
if (result) {
return result;
}
this._wasm.ghostty_raw_parser_events_clear(this._parserHandle);
this._pendingEvents = undefined;
}
private _processEvents(): void | Promise<boolean> {
if (!this._pendingEvents || !this._wasm) {
return;
}
const { ptr, len } = this._pendingEvents;
const mem = this._wasm.memory.buffer;
const view = new DataView(mem);
let textStart = 0;
let textLen = 0;
for (; this._eventIndex < len; this._eventIndex++) {
const base = ptr + this._eventIndex * this._eventSize;
const tag = view.getInt32(base, true);
if (tag !== RawEventTag.PRINT && textLen > 0) {
this._flushText(view, ptr, textStart, textLen);
textLen = 0;
}
switch (tag) {
case RawEventTag.PRINT: {
if (textLen === 0) {
textStart = this._eventIndex;
}
textLen++;
break;
}
case RawEventTag.EXECUTE: {
const code = view.getUint32(base + 4, true);
this._handleExecute(code);
break;
}
case RawEventTag.ESC: {
const event = this._readEvent(view, base);
const ident = this._buildIdent(event.intermediates, event.final, false, [0x30, 0x7e]);
const handlers = this._escHandlers[ident];
const handlerResult = this._callEscHandlers(handlers, ident);
if (handlerResult) {
return handlerResult;
}
break;
}
case RawEventTag.CSI: {
const event = this._readEvent(view, base);
const params = this._buildParams(event.params, event.paramsLen, event.paramsSep);
const ident = this._buildIdent(event.intermediates, event.final, true);
const handlers = this._csiHandlers[ident];
const handlerResult = this._callCsiHandlers(handlers, ident, params);
if (handlerResult) {
return handlerResult;
}
break;
}
case RawEventTag.OSC: {
const event = this._readEvent(view, base);
const oscResult = this._handleOsc(event.code, event.dataPtr, event.dataLen);
if (oscResult) {
return oscResult;
}
break;
}
case RawEventTag.DCS_HOOK: {
const event = this._readEvent(view, base);
const params = this._buildParams(event.params, event.paramsLen, event.paramsSep);
const ident = this._buildIdent(event.intermediates, event.final, true);
this._dcsParser.hook(ident, params);
this.precedingJoinState = 0;
break;
}
case RawEventTag.DCS_PUT: {
const code = view.getUint32(base + 4, true);
this._dcsPutBuffer[0] = code;
this._dcsParser.put(this._dcsPutBuffer, 0, 1);
break;
}
case RawEventTag.DCS_UNHOOK: {
const dcsResult = this._dcsParser.unhook(true);
if (dcsResult) {
this._parseStack.state = ParserStackType.DCS;
this.precedingJoinState = 0;
return dcsResult as Promise<boolean>;
}
this.precedingJoinState = 0;
break;
}
case RawEventTag.APC_START: {
this._apcParser.start();
this.precedingJoinState = 0;
break;
}
case RawEventTag.APC_PUT: {
const code = view.getUint32(base + 4, true);
this._apcPutBuffer[0] = code;
this._apcParser.put(this._apcPutBuffer, 0, 1);
break;
}
case RawEventTag.APC_END: {
const apcResult = this._apcParser.end(true);
if (apcResult) {
this._parseStack.state = ParserStackType.APC;
this.precedingJoinState = 0;
return apcResult as Promise<boolean>;
}
this.precedingJoinState = 0;
break;
}
}
}
if (textLen > 0) {
this._flushText(view, ptr, textStart, textLen);
}
return;
}
private _flushText(view: DataView, ptr: number, start: number, count: number): void {
let remaining = count;
let offset = 0;
while (remaining > 0) {
const chunk = Math.min(remaining, this._utf32Scratch.length);
for (let i = 0; i < chunk; i++) {
const base = ptr + (start + offset + i) * this._eventSize;
const code = view.getUint32(base + 4, true);
this._utf32Scratch[i] = code;
}
this._printHandler(this._utf32Scratch, 0, chunk);
remaining -= chunk;
offset += chunk;
}
}
private _handleExecute(code: number): void {
if (this._executeHandlers[code]) {
this._executeHandlers[code]();
} else {
this._executeHandlerFb(code);
}
this.precedingJoinState = 0;
}
private _callEscHandlers(handlers: EscHandlerType[] | undefined, ident: number): void | Promise<boolean> {
if (!handlers) {
this._escHandlerFb(ident);
this.precedingJoinState = 0;
return;
}
let j = handlers.length - 1;
for (; j >= 0; j--) {
const handlerResult = handlers[j]();
if (handlerResult === true) {
break;
} else if (handlerResult instanceof Promise) {
this._parseStack.state = ParserStackType.ESC;
this._parseStack.handlers = handlers;
this._parseStack.handlerPos = j;
this.precedingJoinState = 0;
return handlerResult;
}
}
if (j < 0) {
this._escHandlerFb(ident);
}
this.precedingJoinState = 0;
}
private _callCsiHandlers(handlers: CsiHandlerType[] | undefined, ident: number, params: IParams): void | Promise<boolean> {
if (!handlers) {
this._csiHandlerFb(ident, params);
this.precedingJoinState = 0;
return;
}
let j = handlers.length - 1;
for (; j >= 0; j--) {
const handlerResult = handlers[j](params);
if (handlerResult === true) {
break;
} else if (handlerResult instanceof Promise) {
this._parseStack.state = ParserStackType.CSI;
this._resumeParams = params;
this._parseStack.handlers = handlers;
this._parseStack.handlerPos = j;
this.precedingJoinState = 0;
return handlerResult;
}
}
if (j < 0) {
this._csiHandlerFb(ident, params);
}
this.precedingJoinState = 0;
}
private _handleOsc(oscId: number, dataPtr: number, dataLen: number): void | Promise<boolean> {
console.log('handle osc');
if (!this._wasm) {
return;
}
let payload = '';
if (dataLen > 0) {
if (!dataPtr || dataPtr + dataLen > this._wasm.memory.buffer.byteLength) {
return;
}
const bytes = new Uint8Array(this._wasm.memory.buffer, dataPtr, dataLen);
payload = this._textDecoder.decode(bytes);
}
if (payload.indexOf('\u0000') !== -1) {
if (oscId === 8) {
const parts = payload.split('\u0000').filter((part, index, all) => {
if (part.length > 0) {
return true;
}
return index < all.length - 1;
});
if (parts.length > 0) {
const uri = parts[parts.length - 1] ?? '';
const params = parts.slice(0, -1).join(':');
payload = `${params};${uri}`;
} else {
payload = '';
}
} else {
payload = payload.replace(/\u0000+/g, '');
}
}
const oscPrefix = `${oscId};`;
const rawPayload = payload.startsWith(oscPrefix)
? payload.slice(oscPrefix.length)
: payload;
let oscPayload = rawPayload;
if (oscId === 8 && oscPayload && !oscPayload.startsWith(';')) {
const sepIndex = oscPayload.indexOf(';');
const paramsPart = sepIndex === -1 ? oscPayload : oscPayload.slice(0, sepIndex);
if (!paramsPart.includes('=')) {
oscPayload = `;${oscPayload}`;
}
}
const oscString = `${oscPrefix}${oscPayload}`;
this._oscParser.start();
const length = this._decodeToScratch(oscString);
this._oscParser.put(this._utf32Scratch, 0, length);
const handlerResult = this._oscParser.end(true);
if (handlerResult) {
this._parseStack.state = ParserStackType.OSC;
this.precedingJoinState = 0;
return handlerResult as Promise<boolean>;
}
this.precedingJoinState = 0;
}
private _buildParams(params: Uint16Array, length: number, sepBits: number): Params {
const result = new Params(this._eventMaxParams, 256);
if (length === 0) {
result.addParam(0);
return result;
}
let i = 0;
while (i < length) {
result.addParam(params[i]);
if (sepBits & (1 << i)) {
i++;
while (i < length) {
result.addSubParam(params[i]);
if ((sepBits & (1 << i)) === 0) {
break;
}
i++;
}
}
i++;
}
return result;
}
private _buildIdent(intermediates: string, final: string, allowPrefix: boolean, finalRange: number[] = [0x40, 0x7e]): number {
let prefix: string | undefined;
let inters = intermediates;
if (allowPrefix && intermediates.length) {
const first = intermediates.charCodeAt(0);
if (first >= 0x3c && first <= 0x3f) {
prefix = intermediates.charAt(0);
inters = intermediates.substring(1);
}
}
return this._identifier({ prefix, intermediates: inters || undefined, final }, finalRange);
}
private _readEvent(view: DataView, base: number): {
final: string;
intermediates: string;
params: Uint16Array;
paramsLen: number;
paramsSep: number;
code: number;
dataPtr: number;
dataLen: number;
} {
const code = view.getUint32(base + 4, true);
const final = String.fromCharCode(view.getUint8(base + 8));
const intermediatesLen = Math.min(view.getUint8(base + 9), this._eventMaxIntermediates);
const paramsLen = Math.min(view.getUint8(base + 10), this._eventMaxParams);
const paramsSep = view.getUint32(base + 12, true);
let intermediates = '';
const interOffset = base + 16;
for (let i = 0; i < intermediatesLen; i++) {
intermediates += String.fromCharCode(view.getUint8(interOffset + i));
}
const paramsOffset = base + 16 + this._eventMaxIntermediates;
const params = new Uint16Array(paramsLen);
for (let i = 0; i < paramsLen; i++) {
params[i] = view.getUint16(paramsOffset + i * 2, true);
}
const rawDataPtrOffset = paramsOffset + this._eventMaxParams * 2;
const dataPtrOffset = (rawDataPtrOffset + (this._ptrSize - 1)) & ~(this._ptrSize - 1);
const dataPtr = view.getUint32(dataPtrOffset, true);
const dataLen = view.getUint32(dataPtrOffset + this._ptrSize, true);
return {
final,
intermediates,
params,
paramsLen,
paramsSep,
code,
dataPtr,
dataLen
};
}
private _decodeToScratch(text: string): number {
if (this._utf32Scratch.length < text.length * 2) {
this._utf32Scratch = new Uint32Array(text.length * 2);
}
return this._oscBuffer.decode(text, this._utf32Scratch);
}
}
-133
View File
@@ -1,133 +0,0 @@
/**
* Copyright (c) 2026 The xterm.js authors. All rights reserved.
* @license MIT
*/
/* eslint-disable @typescript-eslint/naming-convention */
export interface IGhosttyWasmExports {
memory: WebAssembly.Memory;
ghostty_raw_parser_new(allocPtr: number): number;
ghostty_raw_parser_free(parser: number): void;
ghostty_raw_parser_reset(parser: number): void;
ghostty_raw_parser_write(parser: number, dataPtr: number, len: number): void;
ghostty_raw_parser_events_ptr(parser: number): number;
ghostty_raw_parser_events_len(parser: number): number;
ghostty_raw_parser_events_clear(parser: number): void;
ghostty_raw_parser_event_size(): number;
ghostty_raw_parser_max_params(): number;
ghostty_raw_parser_max_intermediates(): number;
ghostty_wasm_alloc_u8_array(len: number): number;
ghostty_wasm_free_u8_array(ptr: number, len: number): void;
ghostty_xterm_buffer_new(cols: number, rows: number, maxRows: number): number;
ghostty_xterm_buffer_free(buffer: number): void;
ghostty_xterm_buffer_resize(buffer: number, cols: number, rows: number, maxRows: number): number;
ghostty_xterm_buffer_clear(buffer: number): void;
ghostty_xterm_buffer_get_cols(buffer: number): number;
ghostty_xterm_buffer_get_rows(buffer: number): number;
ghostty_xterm_buffer_get_max_rows(buffer: number): number;
ghostty_xterm_buffer_get_cell(buffer: number, row: number, col: number, outPtr: number): void;
ghostty_xterm_buffer_set_cell(buffer: number, row: number, col: number, content: number, fg: number, bg: number): void;
ghostty_xterm_buffer_clear_row(buffer: number, row: number, content: number, fg: number, bg: number): void;
ghostty_xterm_buffer_copy_row(buffer: number, srcRow: number, dstRow: number): void;
ghostty_xterm_buffer_get_row_wrap(buffer: number, row: number): number;
ghostty_xterm_buffer_set_row_wrap(buffer: number, row: number, wrap: number): void;
}
/* eslint-enable @typescript-eslint/naming-convention */
export class GhosttyWasmRuntime {
private static _instancePromise: Promise<IGhosttyWasmExports> | undefined;
private static _instanceSync: IGhosttyWasmExports | undefined;
public static getInstance(): Promise<IGhosttyWasmExports> {
this._instancePromise ??= this._loadAsync();
return this._instancePromise;
}
public static getInstanceSync(): IGhosttyWasmExports {
this._instanceSync ??= this._loadSync();
return this._instanceSync;
}
private static async _loadAsync(): Promise<IGhosttyWasmExports> {
const wasmUrl = GhosttyWasmRuntime._getWasmUrl();
const isNode = typeof globalThis !== 'undefined' && !!(globalThis as any).process?.versions?.node;
if (isNode) {
const requireFn = (globalThis as any).require
?? (globalThis as any).process?.mainModule?.require
?? (globalThis as any).__xtermRequire;
const fs = requireFn?.('fs') as { readFile(path: string, cb: (err: Error | null, data?: Uint8Array) => void): void } | undefined;
if (!fs) {
throw new Error('Node.js async WASM loading requires require("fs")');
}
const wasmBytes = await new Promise<Uint8Array>((resolve, reject) => {
fs.readFile(wasmUrl, (err, data) => {
if (err || !data) {
reject(err ?? new Error(`Failed to load Ghostty WASM from ${wasmUrl}`));
return;
}
resolve(data);
});
});
const env = { log: () => {} };
const { instance } = await WebAssembly.instantiate(wasmBytes, { env });
return instance.exports as unknown as IGhosttyWasmExports;
}
const response = await fetch(wasmUrl);
if (!response.ok) {
throw new Error(`Failed to load Ghostty WASM from ${wasmUrl}`);
}
const wasmBytes = await response.arrayBuffer();
const env = { log: () => {} };
const { instance } = await WebAssembly.instantiate(wasmBytes, { env });
return instance.exports as unknown as IGhosttyWasmExports;
}
private static _loadSync(): IGhosttyWasmExports {
const wasmUrl = GhosttyWasmRuntime._getWasmUrl();
const isNode = typeof globalThis !== 'undefined' && !!(globalThis as any).process?.versions?.node;
if (!isNode && typeof document !== 'undefined') {
const request = new XMLHttpRequest();
request.open('GET', wasmUrl, false);
request.overrideMimeType('text/plain; charset=x-user-defined');
request.send(null);
if (request.status !== 200 || !request.responseText) {
throw new Error(`Failed to load Ghostty WASM from ${wasmUrl}`);
}
const binary = request.responseText;
const wasmBytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
wasmBytes[i] = binary.charCodeAt(i) & 0xFF;
}
const module = new WebAssembly.Module(wasmBytes);
const env = { log: () => {} };
const instance = new WebAssembly.Instance(module, { env });
return instance.exports as unknown as IGhosttyWasmExports;
}
// Node.js sync load for tests and headless usage.
const requireFn = (globalThis as any).require
?? (globalThis as any).process?.mainModule?.require
?? (globalThis as any).__xtermRequire;
const fs = requireFn?.('fs') as { readFileSync(path: string): Uint8Array } | undefined;
if (!fs) {
throw new Error('Node.js sync WASM loading requires require("fs")');
}
const wasmBytes = fs.readFileSync(wasmUrl);
const module = new WebAssembly.Module(wasmBytes);
const env = { log: () => {} };
const instance = new WebAssembly.Instance(module, { env });
return instance.exports as unknown as IGhosttyWasmExports;
}
private static _getWasmUrl(): string {
const override = (globalThis as any).XTERM_GHOSTTY_WASM_URL as string | undefined;
if (override) {
return override;
}
if (typeof document !== 'undefined') {
return 'vendor/ghostty-wasm/ghostty-vt.wasm';
}
return 'vendor/ghostty-wasm/ghostty-vt.wasm';
}
}
-1
Submodule vendor/ghostty deleted from 64f78b7063
Binary file not shown.