@gkoreli/ghostty-vt-js 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -0
- package/THIRD_PARTY_NOTICES.md +45 -0
- package/dist/browser-terminal/buffer.d.ts +93 -0
- package/dist/browser-terminal/buffer.d.ts.map +1 -0
- package/dist/browser-terminal/buffer.js +337 -0
- package/dist/browser-terminal/buffer.js.map +1 -0
- package/dist/browser-terminal/encoding.d.ts +17 -0
- package/dist/browser-terminal/encoding.d.ts.map +1 -0
- package/dist/browser-terminal/encoding.js +22 -0
- package/dist/browser-terminal/encoding.js.map +1 -0
- package/dist/browser-terminal/event-emitter.d.ts +8 -0
- package/dist/browser-terminal/event-emitter.d.ts.map +1 -0
- package/dist/browser-terminal/event-emitter.js +27 -0
- package/dist/browser-terminal/event-emitter.js.map +1 -0
- package/dist/browser-terminal/frame-hold.d.ts +13 -0
- package/dist/browser-terminal/frame-hold.d.ts.map +1 -0
- package/dist/browser-terminal/frame-hold.js +17 -0
- package/dist/browser-terminal/frame-hold.js.map +1 -0
- package/dist/browser-terminal/geometry.d.ts +229 -0
- package/dist/browser-terminal/geometry.d.ts.map +1 -0
- package/dist/browser-terminal/geometry.js +299 -0
- package/dist/browser-terminal/geometry.js.map +1 -0
- package/dist/browser-terminal/ghostty.d.ts +478 -0
- package/dist/browser-terminal/ghostty.d.ts.map +1 -0
- package/dist/browser-terminal/ghostty.js +1212 -0
- package/dist/browser-terminal/ghostty.js.map +1 -0
- package/dist/browser-terminal/gpu/adapter.d.ts +70 -0
- package/dist/browser-terminal/gpu/adapter.d.ts.map +1 -0
- package/dist/browser-terminal/gpu/adapter.js +260 -0
- package/dist/browser-terminal/gpu/adapter.js.map +1 -0
- package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.d.ts +33 -0
- package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.d.ts.map +1 -0
- package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.js +159 -0
- package/dist/browser-terminal/gpu/core/canvas-glyph-rasterizer.js.map +1 -0
- package/dist/browser-terminal/gpu/core/context-loss-watchdog.d.ts +35 -0
- package/dist/browser-terminal/gpu/core/context-loss-watchdog.d.ts.map +1 -0
- package/dist/browser-terminal/gpu/core/context-loss-watchdog.js +73 -0
- package/dist/browser-terminal/gpu/core/context-loss-watchdog.js.map +1 -0
- package/dist/browser-terminal/gpu/core/frame.d.ts +68 -0
- package/dist/browser-terminal/gpu/core/frame.d.ts.map +1 -0
- package/dist/browser-terminal/gpu/core/frame.js +167 -0
- package/dist/browser-terminal/gpu/core/frame.js.map +1 -0
- package/dist/browser-terminal/gpu/core/glyph-atlas.d.ts +136 -0
- package/dist/browser-terminal/gpu/core/glyph-atlas.d.ts.map +1 -0
- package/dist/browser-terminal/gpu/core/glyph-atlas.js +281 -0
- package/dist/browser-terminal/gpu/core/glyph-atlas.js.map +1 -0
- package/dist/browser-terminal/gpu/core/procedural-shapes.d.ts +24 -0
- package/dist/browser-terminal/gpu/core/procedural-shapes.d.ts.map +1 -0
- package/dist/browser-terminal/gpu/core/procedural-shapes.js +316 -0
- package/dist/browser-terminal/gpu/core/procedural-shapes.js.map +1 -0
- package/dist/browser-terminal/gpu/core/webgl2-renderer.d.ts +107 -0
- package/dist/browser-terminal/gpu/core/webgl2-renderer.d.ts.map +1 -0
- package/dist/browser-terminal/gpu/core/webgl2-renderer.js +698 -0
- package/dist/browser-terminal/gpu/core/webgl2-renderer.js.map +1 -0
- package/dist/browser-terminal/gpu/create-renderer.d.ts +15 -0
- package/dist/browser-terminal/gpu/create-renderer.d.ts.map +1 -0
- package/dist/browser-terminal/gpu/create-renderer.js +33 -0
- package/dist/browser-terminal/gpu/create-renderer.js.map +1 -0
- package/dist/browser-terminal/index.d.ts +47 -0
- package/dist/browser-terminal/index.d.ts.map +1 -0
- package/dist/browser-terminal/index.js +75 -0
- package/dist/browser-terminal/index.js.map +1 -0
- package/dist/browser-terminal/input-handler.d.ts +262 -0
- package/dist/browser-terminal/input-handler.d.ts.map +1 -0
- package/dist/browser-terminal/input-handler.js +978 -0
- package/dist/browser-terminal/input-handler.js.map +1 -0
- package/dist/browser-terminal/interfaces.d.ts +230 -0
- package/dist/browser-terminal/interfaces.d.ts.map +1 -0
- package/dist/browser-terminal/interfaces.js +5 -0
- package/dist/browser-terminal/interfaces.js.map +1 -0
- package/dist/browser-terminal/link-detector.d.ts +76 -0
- package/dist/browser-terminal/link-detector.d.ts.map +1 -0
- package/dist/browser-terminal/link-detector.js +165 -0
- package/dist/browser-terminal/link-detector.js.map +1 -0
- package/dist/browser-terminal/providers/osc8-link-provider.d.ts +56 -0
- package/dist/browser-terminal/providers/osc8-link-provider.d.ts.map +1 -0
- package/dist/browser-terminal/providers/osc8-link-provider.js +204 -0
- package/dist/browser-terminal/providers/osc8-link-provider.js.map +1 -0
- package/dist/browser-terminal/providers/url-regex-provider.d.ts +68 -0
- package/dist/browser-terminal/providers/url-regex-provider.d.ts.map +1 -0
- package/dist/browser-terminal/providers/url-regex-provider.js +107 -0
- package/dist/browser-terminal/providers/url-regex-provider.js.map +1 -0
- package/dist/browser-terminal/renderer-interface.d.ts +59 -0
- package/dist/browser-terminal/renderer-interface.d.ts.map +1 -0
- package/dist/browser-terminal/renderer-interface.js +2 -0
- package/dist/browser-terminal/renderer-interface.js.map +1 -0
- package/dist/browser-terminal/renderer.d.ts +254 -0
- package/dist/browser-terminal/renderer.d.ts.map +1 -0
- package/dist/browser-terminal/renderer.js +905 -0
- package/dist/browser-terminal/renderer.js.map +1 -0
- package/dist/browser-terminal/scrollbar-overlay.d.ts +45 -0
- package/dist/browser-terminal/scrollbar-overlay.d.ts.map +1 -0
- package/dist/browser-terminal/scrollbar-overlay.js +89 -0
- package/dist/browser-terminal/scrollbar-overlay.js.map +1 -0
- package/dist/browser-terminal/selection-manager.d.ts +180 -0
- package/dist/browser-terminal/selection-manager.d.ts.map +1 -0
- package/dist/browser-terminal/selection-manager.js +913 -0
- package/dist/browser-terminal/selection-manager.js.map +1 -0
- package/dist/browser-terminal/terminal.d.ts +423 -0
- package/dist/browser-terminal/terminal.d.ts.map +1 -0
- package/dist/browser-terminal/terminal.js +1754 -0
- package/dist/browser-terminal/terminal.js.map +1 -0
- package/dist/browser-terminal/types.d.ts +595 -0
- package/dist/browser-terminal/types.d.ts.map +1 -0
- package/dist/browser-terminal/types.js +467 -0
- package/dist/browser-terminal/types.js.map +1 -0
- package/dist/browser-terminal/viewport-scroller.d.ts +94 -0
- package/dist/browser-terminal/viewport-scroller.d.ts.map +1 -0
- package/dist/browser-terminal/viewport-scroller.js +159 -0
- package/dist/browser-terminal/viewport-scroller.js.map +1 -0
- package/dist/browser-terminal/vt/effects.d.ts +114 -0
- package/dist/browser-terminal/vt/effects.d.ts.map +1 -0
- package/dist/browser-terminal/vt/effects.js +143 -0
- package/dist/browser-terminal/vt/effects.js.map +1 -0
- package/dist/browser-terminal/vt/enums.d.ts +155 -0
- package/dist/browser-terminal/vt/enums.d.ts.map +1 -0
- package/dist/browser-terminal/vt/enums.js +161 -0
- package/dist/browser-terminal/vt/enums.js.map +1 -0
- package/dist/browser-terminal/vt/mouse.d.ts +166 -0
- package/dist/browser-terminal/vt/mouse.d.ts.map +1 -0
- package/dist/browser-terminal/vt/mouse.js +259 -0
- package/dist/browser-terminal/vt/mouse.js.map +1 -0
- package/dist/browser-terminal/vt/paste.d.ts +53 -0
- package/dist/browser-terminal/vt/paste.d.ts.map +1 -0
- package/dist/browser-terminal/vt/paste.js +89 -0
- package/dist/browser-terminal/vt/paste.js.map +1 -0
- package/dist/browser-terminal/vt/render-state.d.ts +208 -0
- package/dist/browser-terminal/vt/render-state.d.ts.map +1 -0
- package/dist/browser-terminal/vt/render-state.js +776 -0
- package/dist/browser-terminal/vt/render-state.js.map +1 -0
- package/dist/browser-terminal/vt/style.d.ts +54 -0
- package/dist/browser-terminal/vt/style.d.ts.map +1 -0
- package/dist/browser-terminal/vt/style.js +92 -0
- package/dist/browser-terminal/vt/style.js.map +1 -0
- package/dist/browser-terminal/wasm-loader.d.ts +39 -0
- package/dist/browser-terminal/wasm-loader.d.ts.map +1 -0
- package/dist/browser-terminal/wasm-loader.js +73 -0
- package/dist/browser-terminal/wasm-loader.js.map +1 -0
- package/dist/browser-terminal/write-buffer.d.ts +40 -0
- package/dist/browser-terminal/write-buffer.d.ts.map +1 -0
- package/dist/browser-terminal/write-buffer.js +144 -0
- package/dist/browser-terminal/write-buffer.js.map +1 -0
- package/dist/protocol/index.d.ts +135 -0
- package/dist/protocol/index.d.ts.map +1 -0
- package/dist/protocol/index.js +76 -0
- package/dist/protocol/index.js.map +1 -0
- package/dist/react/index.d.ts +59 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +146 -0
- package/dist/react/index.js.map +1 -0
- package/dist/server/index.d.ts +130 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +191 -0
- package/dist/server/index.js.map +1 -0
- package/dist/terminal-screen-emulator/emulator.d.ts +66 -0
- package/dist/terminal-screen-emulator/emulator.d.ts.map +1 -0
- package/dist/terminal-screen-emulator/emulator.js +286 -0
- package/dist/terminal-screen-emulator/emulator.js.map +1 -0
- package/dist/terminal-screen-emulator/index.d.ts +82 -0
- package/dist/terminal-screen-emulator/index.d.ts.map +1 -0
- package/dist/terminal-screen-emulator/index.js +92 -0
- package/dist/terminal-screen-emulator/index.js.map +1 -0
- package/dist/terminal-screen-emulator/types.d.ts +382 -0
- package/dist/terminal-screen-emulator/types.d.ts.map +1 -0
- package/dist/terminal-screen-emulator/types.js +91 -0
- package/dist/terminal-screen-emulator/types.js.map +1 -0
- package/dist/terminal-screen-emulator/wasm-loader.d.ts +71 -0
- package/dist/terminal-screen-emulator/wasm-loader.d.ts.map +1 -0
- package/dist/terminal-screen-emulator/wasm-loader.js +162 -0
- package/dist/terminal-screen-emulator/wasm-loader.js.map +1 -0
- package/dist/themes/index.d.ts +6 -0
- package/dist/themes/index.d.ts.map +1 -0
- package/dist/themes/index.js +51 -0
- package/dist/themes/index.js.map +1 -0
- package/dist/wasm/alloc.d.ts +170 -0
- package/dist/wasm/alloc.d.ts.map +1 -0
- package/dist/wasm/alloc.js +307 -0
- package/dist/wasm/alloc.js.map +1 -0
- package/dist/wasm/compile.d.ts +73 -0
- package/dist/wasm/compile.d.ts.map +1 -0
- package/dist/wasm/compile.js +82 -0
- package/dist/wasm/compile.js.map +1 -0
- package/dist/wasm/exports.d.ts +234 -0
- package/dist/wasm/exports.d.ts.map +1 -0
- package/dist/wasm/exports.js +15 -0
- package/dist/wasm/exports.js.map +1 -0
- package/dist/wasm/fn-table.d.ts +119 -0
- package/dist/wasm/fn-table.d.ts.map +1 -0
- package/dist/wasm/fn-table.js +168 -0
- package/dist/wasm/fn-table.js.map +1 -0
- package/dist/wasm/memory.d.ts +59 -0
- package/dist/wasm/memory.d.ts.map +1 -0
- package/dist/wasm/memory.js +89 -0
- package/dist/wasm/memory.js.map +1 -0
- package/dist/wasm/type-layouts.d.ts +61 -0
- package/dist/wasm/type-layouts.d.ts.map +1 -0
- package/dist/wasm/type-layouts.js +32 -0
- package/dist/wasm/type-layouts.js.map +1 -0
- package/package.json +94 -0
- package/wasm/ghostty-vt.wasm +0 -0
|
@@ -0,0 +1,1754 @@
|
|
|
1
|
+
// Portions originally derived from coder/ghostty-web (MIT — see ./LICENSE):
|
|
2
|
+
// https://github.com/coder/ghostty-web/blob/6a1a50df5b4f6b34d1b1de10fad3a0fc811bfbc0/lib/terminal.ts
|
|
3
|
+
// Substantially rewritten since; this file is ours and does not track that project.
|
|
4
|
+
// Modified: consumer call sites kept upstream-shaped (Terminal.getCursor/getLine/etc.) wired to new API; typed implicit-any link/err callbacks.
|
|
5
|
+
/**
|
|
6
|
+
* Terminal - Main terminal emulator class
|
|
7
|
+
*
|
|
8
|
+
* Provides an xterm.js-compatible API wrapping Ghostty's WASM terminal emulator.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* ```typescript
|
|
12
|
+
* import { init, Terminal } from '@gkoreli/ghostty-vt-js/browser-terminal';
|
|
13
|
+
*
|
|
14
|
+
* await init();
|
|
15
|
+
* const term = new Terminal();
|
|
16
|
+
* term.open(document.getElementById('container'));
|
|
17
|
+
* term.write('Hello, World!\n');
|
|
18
|
+
* term.onData(data => console.log('User typed:', data));
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
import { BufferNamespace } from './buffer.js';
|
|
22
|
+
import { EventEmitter } from './event-emitter.js';
|
|
23
|
+
import { decideSynchronizedOutputFrameHold, } from './frame-hold.js';
|
|
24
|
+
import { VtModes } from './types.js';
|
|
25
|
+
import { getGhostty } from './index.js';
|
|
26
|
+
import { InputHandler } from './input-handler.js';
|
|
27
|
+
import { DEFAULT_RENDERER_PREFERENCE } from './interfaces.js';
|
|
28
|
+
import { LinkDetector } from './link-detector.js';
|
|
29
|
+
import { OSC8LinkProvider } from './providers/osc8-link-provider.js';
|
|
30
|
+
import { UrlRegexProvider } from './providers/url-regex-provider.js';
|
|
31
|
+
import { DEFAULT_THEME, DEFAULT_FONT_FAMILY } from './renderer.js';
|
|
32
|
+
import { createTerminalRenderer } from './gpu/create-renderer.js';
|
|
33
|
+
import { SelectionManager } from './selection-manager.js';
|
|
34
|
+
import { decodeLatin1 } from './encoding.js';
|
|
35
|
+
import { measureCellWithCanvas, readHostContentBox, TerminalGeometry, } from './geometry.js';
|
|
36
|
+
import { installEffects } from './vt/effects.js';
|
|
37
|
+
import { pasteEncode, pasteIsSafe } from './vt/paste.js';
|
|
38
|
+
import { ScrollbarOverlay } from './scrollbar-overlay.js';
|
|
39
|
+
import { ViewportScroller } from './viewport-scroller.js';
|
|
40
|
+
import { WriteBuffer } from './write-buffer.js';
|
|
41
|
+
// ============================================================================
|
|
42
|
+
// Terminal Class
|
|
43
|
+
// ============================================================================
|
|
44
|
+
export class Terminal {
|
|
45
|
+
// Public properties (xterm.js compatibility)
|
|
46
|
+
cols;
|
|
47
|
+
rows;
|
|
48
|
+
element;
|
|
49
|
+
textarea;
|
|
50
|
+
// Buffer API (xterm.js compatibility)
|
|
51
|
+
buffer;
|
|
52
|
+
// Unicode API (xterm.js compatibility)
|
|
53
|
+
unicode = {
|
|
54
|
+
get activeVersion() {
|
|
55
|
+
return '15.1'; // Ghostty supports Unicode 15.1
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
// Options (public for xterm.js compatibility)
|
|
59
|
+
options;
|
|
60
|
+
// Components (created on open())
|
|
61
|
+
ghostty;
|
|
62
|
+
wasmTerm; // Made public for link providers
|
|
63
|
+
/**
|
|
64
|
+
* The paint backend, behind the {@link ITerminalRenderer} seam. Constructed
|
|
65
|
+
* from the requested preference; `auto` is GPU-first with Canvas fallback.
|
|
66
|
+
*/
|
|
67
|
+
renderer;
|
|
68
|
+
inputHandler;
|
|
69
|
+
selectionManager;
|
|
70
|
+
canvas;
|
|
71
|
+
/** Library-owned root inside the consumer's host; the only element we style. */
|
|
72
|
+
root;
|
|
73
|
+
// Link detection system
|
|
74
|
+
linkDetector;
|
|
75
|
+
currentHoveredLink;
|
|
76
|
+
mouseMoveThrottleTimeout;
|
|
77
|
+
pendingMouseMove;
|
|
78
|
+
// Event emitters
|
|
79
|
+
dataEmitter = new EventEmitter();
|
|
80
|
+
resizeEmitter = new EventEmitter();
|
|
81
|
+
/** Fires when the measured host box yields a new grid PROPOSAL (not a decision). */
|
|
82
|
+
proposalEmitter = new EventEmitter();
|
|
83
|
+
bellEmitter = new EventEmitter();
|
|
84
|
+
selectionChangeEmitter = new EventEmitter();
|
|
85
|
+
keyEmitter = new EventEmitter();
|
|
86
|
+
titleChangeEmitter = new EventEmitter();
|
|
87
|
+
pwdChangeEmitter = new EventEmitter();
|
|
88
|
+
scrollEmitter = new EventEmitter();
|
|
89
|
+
renderEmitter = new EventEmitter();
|
|
90
|
+
cursorMoveEmitter = new EventEmitter();
|
|
91
|
+
rendererFailureEmitter = new EventEmitter();
|
|
92
|
+
// Public event accessors (xterm.js compatibility)
|
|
93
|
+
onData = this.dataEmitter.event;
|
|
94
|
+
onResize = this.resizeEmitter.event;
|
|
95
|
+
/**
|
|
96
|
+
* A new grid PROPOSAL from measuring the host box (host resized, font
|
|
97
|
+
* changed). Send it to whoever owns geometry; do NOT apply it locally — the
|
|
98
|
+
* authority answers with a decision (the geometry-authority design).
|
|
99
|
+
*/
|
|
100
|
+
onProposal = this.proposalEmitter.event;
|
|
101
|
+
onBell = this.bellEmitter.event;
|
|
102
|
+
onSelectionChange = this.selectionChangeEmitter.event;
|
|
103
|
+
onKey = this.keyEmitter.event;
|
|
104
|
+
onTitleChange = this.titleChangeEmitter.event;
|
|
105
|
+
onPwdChange = this.pwdChangeEmitter.event;
|
|
106
|
+
onScroll = this.scrollEmitter.event;
|
|
107
|
+
onRender = this.renderEmitter.event;
|
|
108
|
+
onCursorMove = this.cursorMoveEmitter.event;
|
|
109
|
+
/** Fires when the active backend cannot recover and the host should remount. */
|
|
110
|
+
onRendererFailure = this.rendererFailureEmitter.event;
|
|
111
|
+
// Lifecycle state
|
|
112
|
+
isOpen = false;
|
|
113
|
+
isDisposed = false;
|
|
114
|
+
animationFrameId;
|
|
115
|
+
synchronizedOutputHoldStartMs;
|
|
116
|
+
// Addons
|
|
117
|
+
addons = [];
|
|
118
|
+
// Phase 1: Custom event handlers
|
|
119
|
+
customKeyEventHandler;
|
|
120
|
+
// Title and pwd arrive via TITLE_CHANGED / PWD_CHANGED effect callbacks
|
|
121
|
+
// (vt/effects.ts); these fields cache the last seen value so we emit only
|
|
122
|
+
// on actual change.
|
|
123
|
+
currentTitle = '';
|
|
124
|
+
currentPwd = '';
|
|
125
|
+
// Inbound write queue — ALL data entering the parser goes through this.
|
|
126
|
+
// Owns the re-entrancy invariant: effect callbacks fire synchronously
|
|
127
|
+
// inside `vt_write`, so a `write()` from any event handler must append,
|
|
128
|
+
// never recurse into the parser. See write-buffer.ts for the full contract.
|
|
129
|
+
writeBuffer = new WriteBuffer((data) => this.writeInternal(data));
|
|
130
|
+
/**
|
|
131
|
+
* The geometry owner (the geometry-authority design) — sole source of cell metrics, the grid, and
|
|
132
|
+
* the canvas box. Created in open(), once the host element exists.
|
|
133
|
+
*/
|
|
134
|
+
geometry;
|
|
135
|
+
/** Observes the host box and emits geometry PROPOSALS (never decisions). */
|
|
136
|
+
hostObserver;
|
|
137
|
+
// Installed VT effect callbacks (WRITE_PTY/BELL/TITLE_CHANGED).
|
|
138
|
+
// Set in open(), disposed in cleanupComponents() BEFORE wasmTerm.free()
|
|
139
|
+
// — clearing registrations before the handle dies (vt/effects.ts contract).
|
|
140
|
+
effects;
|
|
141
|
+
// Phase 2: Viewport scrolling + scrollbar overlay (extracted modules —
|
|
142
|
+
// see viewport-scroller.ts and scrollbar-overlay.ts for the semantics)
|
|
143
|
+
scroller = new ViewportScroller({
|
|
144
|
+
getScrollbackLength: () => this.getScrollbackLength(),
|
|
145
|
+
getRows: () => this.rows,
|
|
146
|
+
getSmoothScrollDuration: () => this.options.smoothScrollDuration ?? 100,
|
|
147
|
+
onScroll: (y) => this.scrollEmitter.fire(y),
|
|
148
|
+
showScrollbar: () => this.scrollbar.show(),
|
|
149
|
+
});
|
|
150
|
+
scrollbar = new ScrollbarOverlay({
|
|
151
|
+
requestRender: (opacity) => {
|
|
152
|
+
if (this.renderer && this.wasmTerm) {
|
|
153
|
+
this.renderer.render(this.wasmTerm, false, this.viewportY, this, opacity);
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
customWheelEventHandler;
|
|
158
|
+
lastCursorY = 0; // Track cursor position for onCursorMove
|
|
159
|
+
// Scrollbar drag geometry (hit-testing needs canvas metrics, so it stays here)
|
|
160
|
+
scrollbarDragStart = null;
|
|
161
|
+
scrollbarDragStartViewportY = 0;
|
|
162
|
+
constructor(options = {}) {
|
|
163
|
+
// Use provided Ghostty instance (for test isolation) or get module-level instance
|
|
164
|
+
this.ghostty = options.ghostty ?? getGhostty();
|
|
165
|
+
// Create base options object with all defaults (excluding ghostty)
|
|
166
|
+
const baseOptions = {
|
|
167
|
+
cols: options.cols ?? 80,
|
|
168
|
+
rows: options.rows ?? 24,
|
|
169
|
+
cursorBlink: options.cursorBlink ?? false,
|
|
170
|
+
cursorStyle: options.cursorStyle ?? 'block',
|
|
171
|
+
theme: options.theme ?? {},
|
|
172
|
+
scrollback: options.scrollback ?? 10000,
|
|
173
|
+
fontSize: options.fontSize ?? 15,
|
|
174
|
+
fontFamily: options.fontFamily ?? DEFAULT_FONT_FAMILY,
|
|
175
|
+
allowTransparency: options.allowTransparency ?? false,
|
|
176
|
+
renderer: options.renderer ?? DEFAULT_RENDERER_PREFERENCE,
|
|
177
|
+
rendererTiming: options.rendererTiming,
|
|
178
|
+
convertEol: options.convertEol ?? false,
|
|
179
|
+
disableStdin: options.disableStdin ?? false,
|
|
180
|
+
smoothScrollDuration: options.smoothScrollDuration ?? 100, // Default: 100ms smooth scroll
|
|
181
|
+
};
|
|
182
|
+
// Wrap in Proxy to intercept runtime changes (xterm.js compatibility)
|
|
183
|
+
this.options = new Proxy(baseOptions, {
|
|
184
|
+
set: (target, prop, value) => {
|
|
185
|
+
const oldValue = target[prop];
|
|
186
|
+
target[prop] = value;
|
|
187
|
+
// Apply runtime changes if terminal is open
|
|
188
|
+
if (this.isOpen) {
|
|
189
|
+
this.handleOptionChange(prop, value, oldValue);
|
|
190
|
+
}
|
|
191
|
+
return true;
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
this.cols = this.options.cols;
|
|
195
|
+
this.rows = this.options.rows;
|
|
196
|
+
// Initialize buffer API
|
|
197
|
+
this.buffer = new BufferNamespace(this);
|
|
198
|
+
}
|
|
199
|
+
// ==========================================================================
|
|
200
|
+
// Option Change Handling (for mutable options)
|
|
201
|
+
// ==========================================================================
|
|
202
|
+
/**
|
|
203
|
+
* Handle runtime option changes (called when options are modified after terminal is open)
|
|
204
|
+
* This enables xterm.js compatibility where options can be changed at runtime
|
|
205
|
+
*/
|
|
206
|
+
handleOptionChange(key, newValue, oldValue) {
|
|
207
|
+
if (newValue === oldValue)
|
|
208
|
+
return;
|
|
209
|
+
switch (key) {
|
|
210
|
+
case 'disableStdin':
|
|
211
|
+
// Input handler already checks this.options.disableStdin dynamically
|
|
212
|
+
// No action needed
|
|
213
|
+
break;
|
|
214
|
+
case 'cursorBlink':
|
|
215
|
+
case 'cursorStyle':
|
|
216
|
+
if (this.renderer) {
|
|
217
|
+
this.renderer.setCursorStyle(this.options.cursorStyle);
|
|
218
|
+
this.renderer.setCursorBlink(this.options.cursorBlink);
|
|
219
|
+
}
|
|
220
|
+
break;
|
|
221
|
+
case 'theme':
|
|
222
|
+
if (this.renderer) {
|
|
223
|
+
console.warn('browser-terminal: theme changes after open() are not yet fully supported');
|
|
224
|
+
}
|
|
225
|
+
break;
|
|
226
|
+
case 'fontSize':
|
|
227
|
+
if (this.renderer) {
|
|
228
|
+
this.renderer.setFontSize(this.options.fontSize);
|
|
229
|
+
this.handleFontChange();
|
|
230
|
+
}
|
|
231
|
+
break;
|
|
232
|
+
case 'fontFamily':
|
|
233
|
+
if (this.renderer) {
|
|
234
|
+
this.renderer.setFontFamily(this.options.fontFamily);
|
|
235
|
+
this.handleFontChange();
|
|
236
|
+
}
|
|
237
|
+
break;
|
|
238
|
+
case 'cols':
|
|
239
|
+
case 'rows':
|
|
240
|
+
// Redirect to resize method
|
|
241
|
+
this.resize(this.options.cols, this.options.rows);
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Handle font changes (fontSize or fontFamily)
|
|
247
|
+
* Updates canvas size to match new font metrics and forces a full re-render
|
|
248
|
+
*/
|
|
249
|
+
handleFontChange() {
|
|
250
|
+
// Metrics are owned by geometry; re-measure there and re-propose.
|
|
251
|
+
if (this.geometry?.remeasure()) {
|
|
252
|
+
this.proposalEmitter.fire(this.geometry.proposal);
|
|
253
|
+
}
|
|
254
|
+
if (!this.renderer || !this.wasmTerm || !this.canvas)
|
|
255
|
+
return;
|
|
256
|
+
// Clear any active selection since pixel positions have changed
|
|
257
|
+
if (this.selectionManager) {
|
|
258
|
+
this.selectionManager.clearSelection();
|
|
259
|
+
}
|
|
260
|
+
// Resize the surface via the geometry owner. NOTHING else may touch
|
|
261
|
+
// canvas.width/height: the grid×cell sizing that used to follow here was a
|
|
262
|
+
// second authority — no dpr, no gutter fill — that overwrote the surface
|
|
263
|
+
// with a blurry, grid-sized canvas whenever the font changed.
|
|
264
|
+
this.renderer.resize(this.cols, this.rows);
|
|
265
|
+
// Force full re-render with new font
|
|
266
|
+
this.renderer.render(this.wasmTerm, true, this.viewportY, this);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Parse a CSS color string to 0xRRGGBB format.
|
|
270
|
+
* Returns 0 if the color is undefined or invalid.
|
|
271
|
+
*/
|
|
272
|
+
parseColorToHex(color) {
|
|
273
|
+
if (!color)
|
|
274
|
+
return 0;
|
|
275
|
+
// Handle hex colors (#RGB, #RRGGBB)
|
|
276
|
+
if (color.startsWith('#')) {
|
|
277
|
+
let hex = color.slice(1);
|
|
278
|
+
if (hex.length === 3) {
|
|
279
|
+
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
|
|
280
|
+
}
|
|
281
|
+
const value = Number.parseInt(hex, 16);
|
|
282
|
+
return Number.isNaN(value) ? 0 : value;
|
|
283
|
+
}
|
|
284
|
+
// Handle rgb(r, g, b) format
|
|
285
|
+
const match = color.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
|
|
286
|
+
if (match) {
|
|
287
|
+
const r = Number.parseInt(match[1], 10);
|
|
288
|
+
const g = Number.parseInt(match[2], 10);
|
|
289
|
+
const b = Number.parseInt(match[3], 10);
|
|
290
|
+
return (r << 16) | (g << 8) | b;
|
|
291
|
+
}
|
|
292
|
+
return 0;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Apply this.options.theme to a freshly-created `wasmTerm`.
|
|
296
|
+
*
|
|
297
|
+
* In the upstream wrapper (ghostty-web) palette + default colors went into a
|
|
298
|
+
* `GhosttyTerminalConfig` passed at construction. Our local ABI splits that
|
|
299
|
+
* into separate setter calls (`setForegroundColor`, `setBackgroundColor`,
|
|
300
|
+
* `setCursorColor`, `setPalette`) that map 1:1 to
|
|
301
|
+
* `ghostty_terminal_set(term, GHOSTTY_TERMINAL_OPT_*, ...)` from `terminal.h`.
|
|
302
|
+
* This helper bridges the gap.
|
|
303
|
+
*/
|
|
304
|
+
applyThemeToWasm() {
|
|
305
|
+
if (!this.wasmTerm)
|
|
306
|
+
return;
|
|
307
|
+
// The RESOLVED theme (user theme over DEFAULT_THEME), never the raw
|
|
308
|
+
// option. The renderer resolves the same way, and both sides must hold the
|
|
309
|
+
// same answer: the wasm terminal's built-in default background is black,
|
|
310
|
+
// so skipping this push when no theme was passed left cells reporting
|
|
311
|
+
// black while the renderer filled lines and gutter with the default
|
|
312
|
+
// theme's #1e1e1e — a two-tone terminal (gray gutter, black grid).
|
|
313
|
+
const theme = { ...DEFAULT_THEME, ...this.options.theme };
|
|
314
|
+
this.wasmTerm.setForegroundColor(this.parseColorToRgb(theme.foreground));
|
|
315
|
+
this.wasmTerm.setBackgroundColor(this.parseColorToRgb(theme.background));
|
|
316
|
+
this.wasmTerm.setCursorColor(this.parseColorToRgb(theme.cursor));
|
|
317
|
+
// Build palette array — only set if at least one entry is defined.
|
|
318
|
+
const themeKeys = [
|
|
319
|
+
theme.black, theme.red, theme.green, theme.yellow,
|
|
320
|
+
theme.blue, theme.magenta, theme.cyan, theme.white,
|
|
321
|
+
theme.brightBlack, theme.brightRed, theme.brightGreen, theme.brightYellow,
|
|
322
|
+
theme.brightBlue, theme.brightMagenta, theme.brightCyan, theme.brightWhite,
|
|
323
|
+
];
|
|
324
|
+
if (themeKeys.some((c) => c !== undefined)) {
|
|
325
|
+
const palette = new Array(256);
|
|
326
|
+
for (let i = 0; i < 256; i++) {
|
|
327
|
+
const themeColor = i < 16 ? this.parseColorToRgb(themeKeys[i]) : null;
|
|
328
|
+
palette[i] = themeColor ?? defaultIndexedColor(i);
|
|
329
|
+
}
|
|
330
|
+
this.wasmTerm.setPalette(palette);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Parse a CSS color string to `{r, g, b}` (0–255 channels). Returns `null` for
|
|
335
|
+
* invalid input so callers can skip the corresponding setter.
|
|
336
|
+
*/
|
|
337
|
+
parseColorToRgb(color) {
|
|
338
|
+
if (!color)
|
|
339
|
+
return null;
|
|
340
|
+
const hex = this.parseColorToHex(color);
|
|
341
|
+
if (hex === 0 && !color.match(/^#0{3,6}$|^rgb\(0,\s*0,\s*0\)$/))
|
|
342
|
+
return null;
|
|
343
|
+
return { r: (hex >> 16) & 0xff, g: (hex >> 8) & 0xff, b: hex & 0xff };
|
|
344
|
+
}
|
|
345
|
+
// ==========================================================================
|
|
346
|
+
// Lifecycle Methods
|
|
347
|
+
// ==========================================================================
|
|
348
|
+
/**
|
|
349
|
+
* Open terminal in a parent element
|
|
350
|
+
*
|
|
351
|
+
* Initializes all components and starts rendering.
|
|
352
|
+
* Requires a pre-loaded Ghostty instance passed to the constructor.
|
|
353
|
+
*/
|
|
354
|
+
open(parent) {
|
|
355
|
+
if (this.isOpen) {
|
|
356
|
+
throw new Error('Terminal is already open');
|
|
357
|
+
}
|
|
358
|
+
if (this.isDisposed) {
|
|
359
|
+
throw new Error('Terminal has been disposed');
|
|
360
|
+
}
|
|
361
|
+
// Store parent element
|
|
362
|
+
this.element = parent;
|
|
363
|
+
this.isOpen = true;
|
|
364
|
+
try {
|
|
365
|
+
// Make parent focusable if it isn't already
|
|
366
|
+
if (!parent.hasAttribute('tabindex')) {
|
|
367
|
+
parent.setAttribute('tabindex', '0');
|
|
368
|
+
}
|
|
369
|
+
// Mark as contenteditable so browser extensions (Vimium, etc.) recognize
|
|
370
|
+
// this as an input element and don't intercept keyboard events.
|
|
371
|
+
parent.setAttribute('contenteditable', 'true');
|
|
372
|
+
// Suppress the browser's native caret. `contenteditable` + focusable
|
|
373
|
+
// makes engines paint a blinking caret inside the container — visible
|
|
374
|
+
// noise, since the real cursor is drawn on the canvas by renderer.ts.
|
|
375
|
+
// `caret-color` is the targeted fix: it kills the caret without
|
|
376
|
+
// touching selection highlighting or extension compatibility.
|
|
377
|
+
parent.style.caretColor = 'transparent';
|
|
378
|
+
// Prevent actual content editing - we handle input ourselves
|
|
379
|
+
parent.addEventListener('beforeinput', (e) => {
|
|
380
|
+
if (e.target === parent) {
|
|
381
|
+
e.preventDefault();
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
// Add accessibility attributes for screen readers and extensions
|
|
385
|
+
parent.setAttribute('role', 'textbox');
|
|
386
|
+
parent.setAttribute('aria-label', 'Terminal input');
|
|
387
|
+
parent.setAttribute('aria-multiline', 'true');
|
|
388
|
+
// Create WASM terminal with current dimensions, then apply theme via setters.
|
|
389
|
+
this.wasmTerm = this.ghostty.createTerminal({
|
|
390
|
+
cols: this.cols,
|
|
391
|
+
rows: this.rows,
|
|
392
|
+
maxScrollback: this.options.scrollback,
|
|
393
|
+
});
|
|
394
|
+
this.applyThemeToWasm();
|
|
395
|
+
this.installTerminalEffects();
|
|
396
|
+
// Build OUR subtree instead of styling the consumer's element (the
|
|
397
|
+
// xterm.js pattern: the host is a read-only boundary; everything the
|
|
398
|
+
// terminal needs styled is inside a root we create and own).
|
|
399
|
+
//
|
|
400
|
+
// INVARIANT (the layout-isolation design): the canvas is absolutely positioned inside the
|
|
401
|
+
// root, OUT of the layout flow that the ResizeObserver measures. The
|
|
402
|
+
// observer drives canvas sizing, so the canvas must never be able to
|
|
403
|
+
// influence the measured size — an in-flow canvas turns any measurement
|
|
404
|
+
// error (border arithmetic, stale styles, engine rounding) into a
|
|
405
|
+
// self-sustaining feedback loop. Out of flow — and clipped by the
|
|
406
|
+
// root's overflow — a mismeasured canvas is a one-frame cosmetic glitch
|
|
407
|
+
// that cannot escape the host's bounds.
|
|
408
|
+
//
|
|
409
|
+
// The root fills the host's CONTENT box (in-flow, 100%×100%), has no
|
|
410
|
+
// border or padding of its own, and is what the observer measures: the
|
|
411
|
+
// border-vs-content arithmetic that plagued host measurement simply has
|
|
412
|
+
// no inputs anymore.
|
|
413
|
+
this.root = document.createElement('div');
|
|
414
|
+
this.root.style.display = 'block';
|
|
415
|
+
this.root.style.position = 'relative';
|
|
416
|
+
this.root.style.width = '100%';
|
|
417
|
+
this.root.style.height = '100%';
|
|
418
|
+
this.root.style.overflow = 'hidden';
|
|
419
|
+
parent.appendChild(this.root);
|
|
420
|
+
this.canvas = document.createElement('canvas');
|
|
421
|
+
this.canvas.style.display = 'block';
|
|
422
|
+
this.canvas.style.position = 'absolute';
|
|
423
|
+
this.canvas.style.left = '0';
|
|
424
|
+
this.canvas.style.top = '0';
|
|
425
|
+
this.canvas.style.cursor = 'text';
|
|
426
|
+
this.root.appendChild(this.canvas);
|
|
427
|
+
// Create hidden textarea for keyboard input (must be inside parent for event bubbling)
|
|
428
|
+
this.textarea = document.createElement('textarea');
|
|
429
|
+
this.textarea.setAttribute('autocorrect', 'off');
|
|
430
|
+
this.textarea.setAttribute('autocapitalize', 'off');
|
|
431
|
+
this.textarea.setAttribute('spellcheck', 'false');
|
|
432
|
+
this.textarea.setAttribute('tabindex', '0'); // Allow focus for mobile keyboard
|
|
433
|
+
this.textarea.setAttribute('aria-label', 'Terminal input');
|
|
434
|
+
// Use clip-path to completely hide the textarea and its caret
|
|
435
|
+
this.textarea.style.position = 'absolute';
|
|
436
|
+
this.textarea.style.left = '0';
|
|
437
|
+
this.textarea.style.top = '0';
|
|
438
|
+
this.textarea.style.width = '1px';
|
|
439
|
+
this.textarea.style.height = '1px';
|
|
440
|
+
this.textarea.style.padding = '0';
|
|
441
|
+
this.textarea.style.border = 'none';
|
|
442
|
+
this.textarea.style.margin = '0';
|
|
443
|
+
this.textarea.style.opacity = '0';
|
|
444
|
+
this.textarea.style.clipPath = 'inset(50%)'; // Clip everything including caret
|
|
445
|
+
this.textarea.style.overflow = 'hidden';
|
|
446
|
+
this.textarea.style.whiteSpace = 'nowrap';
|
|
447
|
+
this.textarea.style.resize = 'none';
|
|
448
|
+
// Belt-and-braces: the clip-path above hides the textarea's caret in
|
|
449
|
+
// Chromium, but some engines still paint a caret for a focused input
|
|
450
|
+
// regardless of clipping.
|
|
451
|
+
this.textarea.style.caretColor = 'transparent';
|
|
452
|
+
this.root.appendChild(this.textarea);
|
|
453
|
+
// Focus textarea on interaction - preventDefault before focus
|
|
454
|
+
const textarea = this.textarea;
|
|
455
|
+
// Desktop: mousedown
|
|
456
|
+
this.canvas.addEventListener('mousedown', (ev) => {
|
|
457
|
+
ev.preventDefault();
|
|
458
|
+
textarea.focus();
|
|
459
|
+
});
|
|
460
|
+
// Mobile: touchend with preventDefault to suppress iOS caret
|
|
461
|
+
this.canvas.addEventListener('touchend', (ev) => {
|
|
462
|
+
ev.preventDefault();
|
|
463
|
+
textarea.focus();
|
|
464
|
+
});
|
|
465
|
+
// The geometry owner: measures the font, proposes a grid from the host
|
|
466
|
+
// box, and computes the canvas box. Nothing else does any of the three.
|
|
467
|
+
//
|
|
468
|
+
// The measured element is OUR root (borderless, padding-free, fills the
|
|
469
|
+
// host content box), and the value is a cached box PUSHED by the
|
|
470
|
+
// ResizeObserver below — the observer's entry IS the content box, so
|
|
471
|
+
// nothing re-derives it from getBoundingClientRect() arithmetic.
|
|
472
|
+
// readHostContentBox() is used exactly once, for the initial
|
|
473
|
+
// pre-observation read.
|
|
474
|
+
const root = this.root;
|
|
475
|
+
let hostBox = readHostContentBox(root)();
|
|
476
|
+
if (hostBox.width === 0 || hostBox.height === 0) {
|
|
477
|
+
// Not fatal — the ResizeObserver below will recover when the host
|
|
478
|
+
// gains a size (dialog opening, tab becoming visible) — but a host
|
|
479
|
+
// that STAYS 0×0 renders nothing, and the cause is always the same:
|
|
480
|
+
// the consumer didn't size the element it handed to open().
|
|
481
|
+
console.warn('[ghostty-vt] Terminal host measures 0×0 — give the host element a size '
|
|
482
|
+
+ '(CSS height/width, flex, or grid track). The terminal fills its host; '
|
|
483
|
+
+ 'it does not invent a size.', { host: parent });
|
|
484
|
+
}
|
|
485
|
+
this.geometry = new TerminalGeometry({
|
|
486
|
+
measureCell: measureCellWithCanvas({
|
|
487
|
+
fontSize: this.options.fontSize,
|
|
488
|
+
fontFamily: this.options.fontFamily,
|
|
489
|
+
lineHeight: this.options.lineHeight,
|
|
490
|
+
}),
|
|
491
|
+
readHostBox: () => hostBox,
|
|
492
|
+
padding: this.options.padding,
|
|
493
|
+
});
|
|
494
|
+
// A standalone terminal is its own authority: adopt our proposal
|
|
495
|
+
// explicitly. Hosted terminals (see ./react) overwrite this the moment
|
|
496
|
+
// the server's decision arrives — `applyGeometry`.
|
|
497
|
+
this.geometry.applyDecision({ cols: this.cols, rows: this.rows });
|
|
498
|
+
// Create the requested backend behind the renderer seam. Auto is
|
|
499
|
+
// GPU-first with synchronous Canvas fallback before the canvas is
|
|
500
|
+
// claimed by WebGL2.
|
|
501
|
+
this.renderer = createTerminalRenderer(this.canvas, {
|
|
502
|
+
geometry: this.geometry,
|
|
503
|
+
fontSize: this.options.fontSize,
|
|
504
|
+
fontFamily: this.options.fontFamily,
|
|
505
|
+
cursorStyle: this.options.cursorStyle,
|
|
506
|
+
cursorBlink: this.options.cursorBlink,
|
|
507
|
+
theme: this.options.theme,
|
|
508
|
+
onBackendFailure: (failure) => this.rendererFailureEmitter.fire(failure),
|
|
509
|
+
}, this.options.renderer);
|
|
510
|
+
this.renderer.resize(this.cols, this.rows);
|
|
511
|
+
// Observe the host and emit PROPOSALS. The terminal never resizes itself
|
|
512
|
+
// from an observation — that is the authority's call (the geometry-authority design).
|
|
513
|
+
//
|
|
514
|
+
// Measurement source: the observer ENTRY. `contentBoxSize` is the exact
|
|
515
|
+
// quantity the geometry needs (borders and padding excluded by the
|
|
516
|
+
// browser), delivered with the notification — no getBoundingClientRect /
|
|
517
|
+
// getComputedStyle re-derivation, so there is no arithmetic to get wrong.
|
|
518
|
+
//
|
|
519
|
+
// Scheduling: the reaction is deferred one animation frame. An observer
|
|
520
|
+
// callback runs mid layout pass; writing canvas styles during delivery
|
|
521
|
+
// makes the browser report "ResizeObserver loop completed with
|
|
522
|
+
// undelivered notifications" even for converging one-shot changes (a
|
|
523
|
+
// dialog animating open). Deferred, layout settles cleanly within each
|
|
524
|
+
// observation cycle, and multiple observations per frame coalesce.
|
|
525
|
+
//
|
|
526
|
+
// Defense-in-depth: the canvas is out of the layout flow (see above), so
|
|
527
|
+
// no reaction here can change the host's size. If a future regression
|
|
528
|
+
// reintroduces a feedback path, the breaker below turns "the terminal
|
|
529
|
+
// grows forever" into a loud one-time diagnostic.
|
|
530
|
+
let hostResizeFrame;
|
|
531
|
+
let growthStreak = 0;
|
|
532
|
+
let breakerTripped = false;
|
|
533
|
+
this.hostObserver = new ResizeObserver((entries) => {
|
|
534
|
+
const box = entries[entries.length - 1]?.contentBoxSize?.[0];
|
|
535
|
+
const next = box
|
|
536
|
+
? { width: box.inlineSize, height: box.blockSize }
|
|
537
|
+
: readHostContentBox(root)(); // older-engine fallback
|
|
538
|
+
// Divergence breaker: sustained monotonic growth across many
|
|
539
|
+
// consecutive observations is the signature of a layout feedback
|
|
540
|
+
// loop, not of a user resize (which settles). Should be dead code —
|
|
541
|
+
// report it, stop reacting, keep the terminal usable at its size.
|
|
542
|
+
growthStreak = next.height > hostBox.height ? growthStreak + 1 : 0;
|
|
543
|
+
hostBox = next;
|
|
544
|
+
if (growthStreak >= 20) {
|
|
545
|
+
if (!breakerTripped) {
|
|
546
|
+
breakerTripped = true;
|
|
547
|
+
console.error('[ghostty-vt] host resize feedback loop detected — suspending resize reactions.', { host: next, canvas: { w: this.canvas?.style.width, h: this.canvas?.style.height } });
|
|
548
|
+
}
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
breakerTripped = false;
|
|
552
|
+
if (hostResizeFrame !== undefined)
|
|
553
|
+
return;
|
|
554
|
+
hostResizeFrame = requestAnimationFrame(() => {
|
|
555
|
+
hostResizeFrame = undefined;
|
|
556
|
+
if (!this.geometry || this.isDisposed)
|
|
557
|
+
return;
|
|
558
|
+
// The paint surface follows every host-box change even when the same
|
|
559
|
+
// decided grid still fits. This does not adopt a local grid proposal;
|
|
560
|
+
// it only lets the renderer reread canvasBox() from the authority.
|
|
561
|
+
this.renderer?.resize(this.cols, this.rows);
|
|
562
|
+
if (this.geometry.reproposal()) {
|
|
563
|
+
this.proposalEmitter.fire(this.geometry.proposal);
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
});
|
|
567
|
+
this.hostObserver.observe(root);
|
|
568
|
+
// Create mouse tracking configuration
|
|
569
|
+
const canvas = this.canvas;
|
|
570
|
+
const renderer = this.renderer;
|
|
571
|
+
const mouseConfig = {
|
|
572
|
+
hasMouseTracking: () => this.wasmTerm?.hasMouseTracking() ?? false,
|
|
573
|
+
// Live handle getter (not a captured reference): reset() recreates
|
|
574
|
+
// the wasm terminal, and the encoder must sync against the current one.
|
|
575
|
+
getTerminalHandle: () => this.wasmTerm?.handle,
|
|
576
|
+
getCellDimensions: () => ({
|
|
577
|
+
width: renderer.charWidth,
|
|
578
|
+
height: renderer.charHeight,
|
|
579
|
+
}),
|
|
580
|
+
// The VT mouse protocol wants coordinates in GRID space (pixel
|
|
581
|
+
// reporting is relative to cell (0,0), and screen size is the grid's
|
|
582
|
+
// size). The canvas surface is larger than the grid — it covers the
|
|
583
|
+
// whole pane with the grid inset within it — so both closures answer
|
|
584
|
+
// from the geometry authority rather than the canvas rect alone. The
|
|
585
|
+
// input handler stays a pipe: it never learns where the grid sits.
|
|
586
|
+
getCanvasOffset: () => {
|
|
587
|
+
const rect = canvas.getBoundingClientRect();
|
|
588
|
+
const box = this.geometry.canvasBox();
|
|
589
|
+
return { left: rect.left + box.gridOriginX, top: rect.top + box.gridOriginY };
|
|
590
|
+
},
|
|
591
|
+
getScreenSize: () => {
|
|
592
|
+
const box = this.geometry.canvasBox();
|
|
593
|
+
return { width: box.gridCssWidth, height: box.gridCssHeight };
|
|
594
|
+
},
|
|
595
|
+
};
|
|
596
|
+
// Create input handler
|
|
597
|
+
this.inputHandler = new InputHandler(this.ghostty, parent, (data) => {
|
|
598
|
+
// Check if stdin is disabled
|
|
599
|
+
if (this.options.disableStdin) {
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
// Clear selection when user types
|
|
603
|
+
this.selectionManager?.clearSelection();
|
|
604
|
+
// Input handler fires data events
|
|
605
|
+
this.dataEmitter.fire(data);
|
|
606
|
+
}, () => {
|
|
607
|
+
// Input handler can also fire bell
|
|
608
|
+
this.bellEmitter.fire();
|
|
609
|
+
}, (keyEvent) => {
|
|
610
|
+
// Forward key events
|
|
611
|
+
this.keyEmitter.fire(keyEvent);
|
|
612
|
+
}, this.customKeyEventHandler, (mode) => {
|
|
613
|
+
// Query terminal mode state (e.g., mode 1 for application cursor mode)
|
|
614
|
+
return this.wasmTerm?.getMode(mode, false) ?? false;
|
|
615
|
+
}, () => {
|
|
616
|
+
// Handle Cmd+C copy - returns true if there was a selection to copy
|
|
617
|
+
return this.copySelection();
|
|
618
|
+
}, this.textarea, mouseConfig);
|
|
619
|
+
// Create selection manager (pass textarea for context menu positioning)
|
|
620
|
+
this.selectionManager = new SelectionManager(this, this.renderer, this.wasmTerm, this.textarea);
|
|
621
|
+
// Connect selection manager to renderer
|
|
622
|
+
this.renderer.setSelectionManager(this.selectionManager);
|
|
623
|
+
// Forward selection change events
|
|
624
|
+
this.selectionManager.onSelectionChange(() => {
|
|
625
|
+
this.selectionChangeEmitter.fire();
|
|
626
|
+
});
|
|
627
|
+
// Initialize link detection system
|
|
628
|
+
this.linkDetector = new LinkDetector(this);
|
|
629
|
+
// Register link providers
|
|
630
|
+
// OSC8 first (explicit hyperlinks take precedence)
|
|
631
|
+
this.linkDetector.registerProvider(new OSC8LinkProvider(this));
|
|
632
|
+
// URL regex second (fallback for plain text URLs)
|
|
633
|
+
this.linkDetector.registerProvider(new UrlRegexProvider(this));
|
|
634
|
+
// Setup mouse event handling for links and scrollbar
|
|
635
|
+
// Use capture phase to intercept scrollbar clicks before SelectionManager
|
|
636
|
+
parent.addEventListener('mousedown', this.handleMouseDown, { capture: true });
|
|
637
|
+
parent.addEventListener('mousemove', this.handleMouseMove);
|
|
638
|
+
parent.addEventListener('mouseleave', this.handleMouseLeave);
|
|
639
|
+
parent.addEventListener('click', this.handleClick);
|
|
640
|
+
// Setup document-level mouseup for scrollbar drag (so drag works even outside canvas)
|
|
641
|
+
document.addEventListener('mouseup', this.handleMouseUp);
|
|
642
|
+
// Setup wheel event handling for scrolling (Phase 2)
|
|
643
|
+
// Use capture phase to ensure we get the event before browser scrolling
|
|
644
|
+
parent.addEventListener('wheel', this.handleWheel, { passive: false, capture: true });
|
|
645
|
+
// Render initial blank screen (force full redraw)
|
|
646
|
+
this.renderer.render(this.wasmTerm, true, this.viewportY, this, this.scrollbar.opacity);
|
|
647
|
+
// Start render loop
|
|
648
|
+
this.startRenderLoop();
|
|
649
|
+
// Focus input (auto-focus so user can start typing immediately)
|
|
650
|
+
this.focus();
|
|
651
|
+
}
|
|
652
|
+
catch (error) {
|
|
653
|
+
// Clean up on error
|
|
654
|
+
this.isOpen = false;
|
|
655
|
+
this.cleanupComponents();
|
|
656
|
+
throw new Error(`Failed to open terminal: ${error}`);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* Write data to terminal.
|
|
661
|
+
*
|
|
662
|
+
* Asynchronous by contract (xterm.js-compatible): the data is enqueued and
|
|
663
|
+
* parsed from a scheduled task, and `callback` fires once *this chunk* has
|
|
664
|
+
* been parsed. This queue is what makes calling `write()` from inside an
|
|
665
|
+
* event handler (`onData`, `onBell`, ...) safe — handlers can fire while
|
|
666
|
+
* the parser is mid-write (see vt/effects.ts), and a direct write would
|
|
667
|
+
* re-enter it. Never bypass the buffer with `wasmTerm.write()` outside
|
|
668
|
+
* `writeInternal`.
|
|
669
|
+
*/
|
|
670
|
+
write(data, callback) {
|
|
671
|
+
this.assertOpen();
|
|
672
|
+
// Handle convertEol option
|
|
673
|
+
if (this.options.convertEol && typeof data === 'string') {
|
|
674
|
+
data = data.replace(/\n/g, '\r\n');
|
|
675
|
+
}
|
|
676
|
+
this.writeBuffer.write(data, callback);
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* The geometry owner, for collaborators that need pixel→cell mapping
|
|
680
|
+
* (selection, link hover). ONE authority for where cells sit on the surface;
|
|
681
|
+
* nobody else may divide pixels by cell size.
|
|
682
|
+
*/
|
|
683
|
+
get geometryAuthority() {
|
|
684
|
+
if (!this.geometry) {
|
|
685
|
+
throw new Error('Terminal.geometryAuthority before open() — no geometry exists yet');
|
|
686
|
+
}
|
|
687
|
+
return this.geometry;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Install VT effect callbacks on the current `wasmTerm` handle.
|
|
691
|
+
*
|
|
692
|
+
* Called from `open()` and re-called from `reset()` (which recreates the
|
|
693
|
+
* WASM terminal — effects are bound to the handle, not the JS object).
|
|
694
|
+
* Full callback contract: vt/effects.ts. The handlers below respect it:
|
|
695
|
+
* each only fires an emitter or does a cheap getter read, and none can
|
|
696
|
+
* re-enter the parser — writes issued by listeners land in the
|
|
697
|
+
* WriteBuffer, not on this stack.
|
|
698
|
+
*/
|
|
699
|
+
installTerminalEffects() {
|
|
700
|
+
this.effects = installEffects(this.ghostty.exports, this.wasmTerm.handle, {
|
|
701
|
+
// Query responses (DSR / DA / ...) → the PTY, through the same channel
|
|
702
|
+
// as keystrokes. Mirrors xterm.js (`CoreService.triggerDataEvent`) and
|
|
703
|
+
// Ghostty's own reference embedder (`example/c-vt-effects` forwards to
|
|
704
|
+
// the pty fd). The consumer ships this to the process; whatever the
|
|
705
|
+
// process prints returns later as ordinary input — the loop never
|
|
706
|
+
// closes synchronously. Bytes are decoded latin1 (byte == charCode),
|
|
707
|
+
// matching how xterm.js represents PTY-bound bytes in `onData` strings.
|
|
708
|
+
onWritePty: (bytes) => {
|
|
709
|
+
this.dataEmitter.fire(decodeLatin1(bytes));
|
|
710
|
+
},
|
|
711
|
+
// Real BEL from the parser — replaces the old input byte-sniff, which
|
|
712
|
+
// false-positived on 0x07 inside OSC payloads (BEL doubles as an OSC
|
|
713
|
+
// terminator) and missed nothing else of value.
|
|
714
|
+
onBell: () => {
|
|
715
|
+
this.bellEmitter.fire();
|
|
716
|
+
},
|
|
717
|
+
// The engine doesn't pass the new title — read it via the official
|
|
718
|
+
// getter (a read, not a parse: safe inside the callback; Ghostty's own
|
|
719
|
+
// example does the same). The string is borrowed; getTitle() copies.
|
|
720
|
+
onTitleChanged: () => {
|
|
721
|
+
const title = this.wasmTerm.getTitle();
|
|
722
|
+
if (title !== this.currentTitle) {
|
|
723
|
+
this.currentTitle = title;
|
|
724
|
+
this.titleChangeEmitter.fire(title);
|
|
725
|
+
}
|
|
726
|
+
},
|
|
727
|
+
// OSC 7 / 9;9 / 1337 pwd reports — same read-on-signal shape as title.
|
|
728
|
+
// Fires with "" when the shell clears the pwd. Raw file:// URI.
|
|
729
|
+
onPwdChanged: () => {
|
|
730
|
+
const pwd = this.wasmTerm.getPwd();
|
|
731
|
+
if (pwd !== this.currentPwd) {
|
|
732
|
+
this.currentPwd = pwd;
|
|
733
|
+
this.pwdChangeEmitter.fire(pwd);
|
|
734
|
+
}
|
|
735
|
+
},
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Parse one chunk. Runs only from the WriteBuffer drain loop — never on a
|
|
740
|
+
* caller's stack. Effect callbacks (onData for query responses, onBell,
|
|
741
|
+
* onTitleChange) fire synchronously from inside `wasmTerm.write()` below.
|
|
742
|
+
*/
|
|
743
|
+
writeInternal(data) {
|
|
744
|
+
// Note: We intentionally do NOT clear selection on write - most modern terminals
|
|
745
|
+
// preserve selection when new data arrives. Selection is cleared by user actions
|
|
746
|
+
// like clicking or typing, not by incoming data.
|
|
747
|
+
// Capture scrollback length before the write so we can preserve the user's
|
|
748
|
+
// viewport position if they're reading history. See coder/ghostty-web#150 —
|
|
749
|
+
// the upstream code unconditionally called `scrollToBottom()` on every write,
|
|
750
|
+
// which yanked the viewport away from whatever the user was reading.
|
|
751
|
+
const scrolledUp = this.scroller.scrolledUp;
|
|
752
|
+
const savedScrollback = scrolledUp ? this.getScrollbackLength() : 0;
|
|
753
|
+
// Write directly to WASM terminal (handles VT parsing internally).
|
|
754
|
+
// Title, pwd, and bell all arrive as effect callbacks fired synchronously
|
|
755
|
+
// from inside this call — see the installEffects() wiring in
|
|
756
|
+
// installTerminalEffects(). Nothing is polled here anymore.
|
|
757
|
+
this.wasmTerm.write(data);
|
|
758
|
+
// Invalidate link cache (content changed)
|
|
759
|
+
this.linkDetector?.invalidateCache();
|
|
760
|
+
// Anchor viewport to whatever the user is reading. If new lines pushed into
|
|
761
|
+
// scrollback while we were scrolled up, shift `viewportY` by the same delta
|
|
762
|
+
// so the on-screen content stays visually stable. If a smooth-scroll
|
|
763
|
+
// animation is in flight, shift its target/start anchor too — otherwise the
|
|
764
|
+
// animation would unwind the correction and snap back to the bottom.
|
|
765
|
+
if (scrolledUp) {
|
|
766
|
+
const delta = this.getScrollbackLength() - savedScrollback;
|
|
767
|
+
this.scroller.shiftAnchor(delta);
|
|
768
|
+
}
|
|
769
|
+
// Per-chunk callbacks are fired by the WriteBuffer after this returns —
|
|
770
|
+
// "parsed" is the contract (xterm.js semantics), not "painted". Rendering
|
|
771
|
+
// happens on the next animation frame via the render loop's dirty tracking.
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Write data with newline
|
|
775
|
+
*/
|
|
776
|
+
writeln(data, callback) {
|
|
777
|
+
if (typeof data === 'string') {
|
|
778
|
+
this.write(data + '\r\n', callback);
|
|
779
|
+
}
|
|
780
|
+
else {
|
|
781
|
+
// Append \r\n to Uint8Array
|
|
782
|
+
const newData = new Uint8Array(data.length + 2);
|
|
783
|
+
newData.set(data);
|
|
784
|
+
newData[data.length] = 0x0d; // \r
|
|
785
|
+
newData[data.length + 1] = 0x0a; // \n
|
|
786
|
+
this.write(newData, callback);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* Paste text into terminal (triggers bracketed paste if supported)
|
|
791
|
+
*/
|
|
792
|
+
/**
|
|
793
|
+
* Paste text into terminal.
|
|
794
|
+
*
|
|
795
|
+
* Encoded through the engine's paste utilities (`paste.h` via
|
|
796
|
+
* `vt/paste.ts`), not naive string concatenation: unsafe control bytes are
|
|
797
|
+
* stripped (including an embedded `ESC[201~` — the bracket-escape paste
|
|
798
|
+
* injection our old hand-rolled wrap let straight through), the payload is
|
|
799
|
+
* bracket-wrapped when DEC mode 2004 is active, and newlines become
|
|
800
|
+
* carriage returns when it isn't.
|
|
801
|
+
*
|
|
802
|
+
* For a UI-level warning *before* pasting (e.g. "this paste contains a
|
|
803
|
+
* newline and will execute"), use {@link isPasteSafe} first — this method
|
|
804
|
+
* sanitizes but doesn't ask.
|
|
805
|
+
*/
|
|
806
|
+
paste(data) {
|
|
807
|
+
this.assertOpen();
|
|
808
|
+
// Don't paste if stdin is disabled
|
|
809
|
+
if (this.options.disableStdin) {
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
const encoded = pasteEncode(this.ghostty.exports, data, this.wasmTerm.hasBracketedPaste());
|
|
813
|
+
this.dataEmitter.fire(encoded);
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Conservative pre-check for paste data (`ghostty_paste_is_safe`,
|
|
817
|
+
* `paste.h`): `false` if the data contains newlines or the bracketed-paste
|
|
818
|
+
* end sequence, regardless of terminal state. Lets embedders implement a
|
|
819
|
+
* confirmation prompt before calling {@link paste}.
|
|
820
|
+
*/
|
|
821
|
+
isPasteSafe(data) {
|
|
822
|
+
return pasteIsSafe(this.ghostty.exports, data);
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Input data into terminal (as if typed by user)
|
|
826
|
+
*
|
|
827
|
+
* @param data - Data to input
|
|
828
|
+
* @param wasUserInput - If true, triggers onData event (default: false for compat with some apps)
|
|
829
|
+
*/
|
|
830
|
+
input(data, wasUserInput = false) {
|
|
831
|
+
this.assertOpen();
|
|
832
|
+
// Don't input if stdin is disabled
|
|
833
|
+
if (this.options.disableStdin) {
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
if (wasUserInput) {
|
|
837
|
+
// Trigger onData event as if user typed it
|
|
838
|
+
this.dataEmitter.fire(data);
|
|
839
|
+
}
|
|
840
|
+
else {
|
|
841
|
+
// Just write to terminal without triggering onData
|
|
842
|
+
this.write(data);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Resize terminal
|
|
847
|
+
*/
|
|
848
|
+
/**
|
|
849
|
+
* Adopt an authoritative grid decided elsewhere (the session host). This is
|
|
850
|
+
* the ONLY correct way for a hosted terminal to change size: it applies the
|
|
851
|
+
* decision to the geometry owner, the WASM terminal, and the canvas in one
|
|
852
|
+
* step. Local measurements are proposals and never take this path.
|
|
853
|
+
*/
|
|
854
|
+
applyGeometry(decided) {
|
|
855
|
+
this.resize(decided.cols, decided.rows);
|
|
856
|
+
}
|
|
857
|
+
/** The grid the measured host box can hold — a proposal, not the truth. */
|
|
858
|
+
get proposal() {
|
|
859
|
+
if (!this.geometry)
|
|
860
|
+
return { cols: this.cols, rows: this.rows };
|
|
861
|
+
return this.geometry.proposal;
|
|
862
|
+
}
|
|
863
|
+
/** Unused host space (CSS px) below/right of the grid. Always sub-cell. */
|
|
864
|
+
get remainder() {
|
|
865
|
+
return this.geometry?.remainder() ?? { width: 0, height: 0 };
|
|
866
|
+
}
|
|
867
|
+
resize(cols, rows) {
|
|
868
|
+
this.assertOpen();
|
|
869
|
+
if (cols === this.cols && rows === this.rows) {
|
|
870
|
+
return; // No change
|
|
871
|
+
}
|
|
872
|
+
// Cancel render loop before resize to prevent accessing detached TypedArray
|
|
873
|
+
// views while WASM reallocates buffers. We restart it after resize completes.
|
|
874
|
+
// This avoids the background-tab regression of using an isResizing flag
|
|
875
|
+
// cleared via requestAnimationFrame (rAF is throttled/paused in background tabs).
|
|
876
|
+
this.cancelRenderLoop();
|
|
877
|
+
try {
|
|
878
|
+
// Update dimensions
|
|
879
|
+
this.cols = cols;
|
|
880
|
+
this.rows = rows;
|
|
881
|
+
// Resize WASM terminal (may reallocate buffers, invalidating TypedArray views)
|
|
882
|
+
this.wasmTerm.resize(cols, rows);
|
|
883
|
+
// Adopt the new grid in the geometry owner FIRST — the renderer reads the
|
|
884
|
+
// canvas box from it. (Previously this method re-derived canvas.width
|
|
885
|
+
// itself, without devicePixelRatio, fighting the renderer for ownership.)
|
|
886
|
+
this.geometry.applyDecision({ cols, rows });
|
|
887
|
+
this.renderer.resize(cols, rows);
|
|
888
|
+
// Fire resize event
|
|
889
|
+
this.resizeEmitter.fire({ cols, rows });
|
|
890
|
+
// Force full render
|
|
891
|
+
this.renderer.render(this.wasmTerm, true, this.viewportY, this);
|
|
892
|
+
}
|
|
893
|
+
catch (e) {
|
|
894
|
+
console.error('Terminal resize failed:', e);
|
|
895
|
+
}
|
|
896
|
+
// Restart render loop (writes issued during resize sat in the WriteBuffer
|
|
897
|
+
// and drain on their own schedule)
|
|
898
|
+
this.startRenderLoop();
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* Clear terminal screen
|
|
902
|
+
*/
|
|
903
|
+
clear() {
|
|
904
|
+
this.assertOpen();
|
|
905
|
+
// Send ANSI clear screen and cursor home sequences
|
|
906
|
+
this.wasmTerm.write('\x1b[2J\x1b[H');
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Reset terminal state
|
|
910
|
+
*/
|
|
911
|
+
reset() {
|
|
912
|
+
this.assertOpen();
|
|
913
|
+
// Free old WASM terminal and create new one. Effects are bound to the
|
|
914
|
+
// handle: dispose FIRST (clears registrations + recycles table slots —
|
|
915
|
+
// vt/effects.ts contract), then re-install on the new handle below.
|
|
916
|
+
this.effects?.dispose();
|
|
917
|
+
this.effects = undefined;
|
|
918
|
+
if (this.wasmTerm) {
|
|
919
|
+
this.wasmTerm.free();
|
|
920
|
+
}
|
|
921
|
+
this.wasmTerm = this.ghostty.createTerminal({
|
|
922
|
+
cols: this.cols,
|
|
923
|
+
rows: this.rows,
|
|
924
|
+
maxScrollback: this.options.scrollback,
|
|
925
|
+
});
|
|
926
|
+
this.applyThemeToWasm();
|
|
927
|
+
this.installTerminalEffects();
|
|
928
|
+
// Clear renderer
|
|
929
|
+
this.renderer.clear();
|
|
930
|
+
// Reset title
|
|
931
|
+
this.currentTitle = '';
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Focus terminal input
|
|
935
|
+
*/
|
|
936
|
+
focus() {
|
|
937
|
+
if (this.isOpen && this.element) {
|
|
938
|
+
// Focus immediately for immediate keyboard/wheel event handling
|
|
939
|
+
this.element.focus();
|
|
940
|
+
// Also schedule a delayed focus as backup to ensure it sticks
|
|
941
|
+
// (some browsers may need this if DOM isn't fully settled)
|
|
942
|
+
setTimeout(() => {
|
|
943
|
+
this.element?.focus();
|
|
944
|
+
}, 0);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* Blur terminal (remove focus)
|
|
949
|
+
*/
|
|
950
|
+
blur() {
|
|
951
|
+
if (this.isOpen && this.element) {
|
|
952
|
+
this.element.blur();
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Load an addon
|
|
957
|
+
*/
|
|
958
|
+
loadAddon(addon) {
|
|
959
|
+
addon.activate(this);
|
|
960
|
+
this.addons.push(addon);
|
|
961
|
+
}
|
|
962
|
+
// ==========================================================================
|
|
963
|
+
// Selection API (xterm.js compatible)
|
|
964
|
+
// ==========================================================================
|
|
965
|
+
/**
|
|
966
|
+
* Get the selected text as a string
|
|
967
|
+
*/
|
|
968
|
+
getSelection() {
|
|
969
|
+
return this.selectionManager?.getSelection() || '';
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Check if there's an active selection
|
|
973
|
+
*/
|
|
974
|
+
hasSelection() {
|
|
975
|
+
return this.selectionManager?.hasSelection() || false;
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Clear the current selection
|
|
979
|
+
*/
|
|
980
|
+
clearSelection() {
|
|
981
|
+
this.selectionManager?.clearSelection();
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Copy the current selection to clipboard
|
|
985
|
+
* @returns true if there was text to copy, false otherwise
|
|
986
|
+
*/
|
|
987
|
+
copySelection() {
|
|
988
|
+
return this.selectionManager?.copySelection() || false;
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Select all text in the terminal
|
|
992
|
+
*/
|
|
993
|
+
selectAll() {
|
|
994
|
+
this.selectionManager?.selectAll();
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Select text at specific column and row with length
|
|
998
|
+
*/
|
|
999
|
+
select(column, row, length) {
|
|
1000
|
+
this.selectionManager?.select(column, row, length);
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Select entire lines from start to end
|
|
1004
|
+
*/
|
|
1005
|
+
selectLines(start, end) {
|
|
1006
|
+
this.selectionManager?.selectLines(start, end);
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Get selection position as buffer range
|
|
1010
|
+
*/
|
|
1011
|
+
/**
|
|
1012
|
+
* Get the current viewport Y position.
|
|
1013
|
+
*
|
|
1014
|
+
* This is the number of lines scrolled back from the bottom of the
|
|
1015
|
+
* scrollback buffer. It may be fractional during smooth scrolling.
|
|
1016
|
+
*/
|
|
1017
|
+
getViewportY() {
|
|
1018
|
+
return this.viewportY;
|
|
1019
|
+
}
|
|
1020
|
+
getSelectionPosition() {
|
|
1021
|
+
return this.selectionManager?.getSelectionPosition();
|
|
1022
|
+
}
|
|
1023
|
+
// ==========================================================================
|
|
1024
|
+
// Phase 1: Custom Event Handlers
|
|
1025
|
+
// ==========================================================================
|
|
1026
|
+
/**
|
|
1027
|
+
* Attach a custom keyboard event handler
|
|
1028
|
+
* Returns true to prevent default handling
|
|
1029
|
+
*/
|
|
1030
|
+
attachCustomKeyEventHandler(customKeyEventHandler) {
|
|
1031
|
+
this.customKeyEventHandler = customKeyEventHandler;
|
|
1032
|
+
// Update input handler if already created
|
|
1033
|
+
if (this.inputHandler) {
|
|
1034
|
+
this.inputHandler.setCustomKeyEventHandler(customKeyEventHandler);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Attach a custom wheel event handler (Phase 2)
|
|
1039
|
+
* Returns true to prevent default handling
|
|
1040
|
+
*/
|
|
1041
|
+
attachCustomWheelEventHandler(customWheelEventHandler) {
|
|
1042
|
+
this.customWheelEventHandler = customWheelEventHandler;
|
|
1043
|
+
}
|
|
1044
|
+
// ==========================================================================
|
|
1045
|
+
// Link Detection Methods
|
|
1046
|
+
// ==========================================================================
|
|
1047
|
+
/**
|
|
1048
|
+
* Register a custom link provider
|
|
1049
|
+
* Multiple providers can be registered to detect different types of links
|
|
1050
|
+
*
|
|
1051
|
+
* @example
|
|
1052
|
+
* ```typescript
|
|
1053
|
+
* term.registerLinkProvider({
|
|
1054
|
+
* provideLinks(y, callback) {
|
|
1055
|
+
* // Detect URLs, file paths, etc.
|
|
1056
|
+
* callback(detectedLinks);
|
|
1057
|
+
* }
|
|
1058
|
+
* });
|
|
1059
|
+
* ```
|
|
1060
|
+
*/
|
|
1061
|
+
registerLinkProvider(provider) {
|
|
1062
|
+
if (!this.linkDetector) {
|
|
1063
|
+
throw new Error('Terminal must be opened before registering link providers');
|
|
1064
|
+
}
|
|
1065
|
+
this.linkDetector.registerProvider(provider);
|
|
1066
|
+
}
|
|
1067
|
+
// ==========================================================================
|
|
1068
|
+
// Phase 2: Scrolling Methods
|
|
1069
|
+
// ==========================================================================
|
|
1070
|
+
/**
|
|
1071
|
+
* Top line of viewport in scrollback buffer (0 = at bottom, can be
|
|
1072
|
+
* fractional during smooth scroll). Owned by {@link ViewportScroller};
|
|
1073
|
+
* exposed as a readonly accessor for xterm.js API compatibility
|
|
1074
|
+
* (`ITerminalCore.viewportY`) — mutate via the scroll methods.
|
|
1075
|
+
*/
|
|
1076
|
+
get viewportY() {
|
|
1077
|
+
return this.scroller.y;
|
|
1078
|
+
}
|
|
1079
|
+
/**
|
|
1080
|
+
* Scroll viewport by a number of lines
|
|
1081
|
+
* @param amount Number of lines to scroll (positive = down, negative = up)
|
|
1082
|
+
*/
|
|
1083
|
+
scrollLines(amount) {
|
|
1084
|
+
if (!this.wasmTerm) {
|
|
1085
|
+
throw new Error('Terminal not open');
|
|
1086
|
+
}
|
|
1087
|
+
this.scroller.scrollLines(amount);
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Scroll viewport by a number of pages
|
|
1091
|
+
* @param amount Number of pages to scroll (positive = down, negative = up)
|
|
1092
|
+
*/
|
|
1093
|
+
scrollPages(amount) {
|
|
1094
|
+
this.scroller.scrollPages(amount);
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Scroll viewport to the top of the scrollback buffer
|
|
1098
|
+
*/
|
|
1099
|
+
scrollToTop() {
|
|
1100
|
+
this.scroller.scrollToTop();
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Scroll viewport to the bottom (current output)
|
|
1104
|
+
*/
|
|
1105
|
+
scrollToBottom() {
|
|
1106
|
+
this.scroller.scrollToBottom();
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Scroll viewport to a specific line in the buffer
|
|
1110
|
+
* @param line Line number (0 = top of scrollback, scrollbackLength = bottom)
|
|
1111
|
+
*/
|
|
1112
|
+
scrollToLine(line) {
|
|
1113
|
+
this.scroller.scrollToLine(line);
|
|
1114
|
+
}
|
|
1115
|
+
// ==========================================================================
|
|
1116
|
+
// Lifecycle
|
|
1117
|
+
// ==========================================================================
|
|
1118
|
+
/**
|
|
1119
|
+
* Dispose terminal and clean up resources
|
|
1120
|
+
*/
|
|
1121
|
+
dispose() {
|
|
1122
|
+
if (this.isDisposed) {
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
this.isDisposed = true;
|
|
1126
|
+
this.isOpen = false;
|
|
1127
|
+
// Stop render loop and drop unparsed writes
|
|
1128
|
+
this.cancelRenderLoop();
|
|
1129
|
+
this.writeBuffer.dispose();
|
|
1130
|
+
// Stop smooth scroll animation + scrollbar timers/fades
|
|
1131
|
+
this.scroller.cancelAnimation();
|
|
1132
|
+
this.scrollbar.dispose();
|
|
1133
|
+
// Clear mouse move throttle timeout
|
|
1134
|
+
if (this.mouseMoveThrottleTimeout) {
|
|
1135
|
+
clearTimeout(this.mouseMoveThrottleTimeout);
|
|
1136
|
+
this.mouseMoveThrottleTimeout = undefined;
|
|
1137
|
+
}
|
|
1138
|
+
this.pendingMouseMove = undefined;
|
|
1139
|
+
// Dispose addons
|
|
1140
|
+
for (const addon of this.addons) {
|
|
1141
|
+
addon.dispose();
|
|
1142
|
+
}
|
|
1143
|
+
this.addons = [];
|
|
1144
|
+
// Clean up components
|
|
1145
|
+
this.cleanupComponents();
|
|
1146
|
+
// Dispose event emitters
|
|
1147
|
+
this.hostObserver?.disconnect();
|
|
1148
|
+
this.hostObserver = undefined;
|
|
1149
|
+
this.dataEmitter.dispose();
|
|
1150
|
+
this.resizeEmitter.dispose();
|
|
1151
|
+
this.proposalEmitter.dispose();
|
|
1152
|
+
this.bellEmitter.dispose();
|
|
1153
|
+
this.selectionChangeEmitter.dispose();
|
|
1154
|
+
this.keyEmitter.dispose();
|
|
1155
|
+
this.titleChangeEmitter.dispose();
|
|
1156
|
+
this.scrollEmitter.dispose();
|
|
1157
|
+
this.renderEmitter.dispose();
|
|
1158
|
+
this.cursorMoveEmitter.dispose();
|
|
1159
|
+
this.rendererFailureEmitter.dispose();
|
|
1160
|
+
}
|
|
1161
|
+
// ==========================================================================
|
|
1162
|
+
// Private Methods
|
|
1163
|
+
// ==========================================================================
|
|
1164
|
+
/**
|
|
1165
|
+
* Cancel the render loop
|
|
1166
|
+
*/
|
|
1167
|
+
cancelRenderLoop() {
|
|
1168
|
+
if (this.animationFrameId) {
|
|
1169
|
+
cancelAnimationFrame(this.animationFrameId);
|
|
1170
|
+
this.animationFrameId = undefined;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* Start the render loop
|
|
1175
|
+
*/
|
|
1176
|
+
startRenderLoop() {
|
|
1177
|
+
if (this.animationFrameId)
|
|
1178
|
+
return; // already running
|
|
1179
|
+
const loop = (nowMs = performance.now()) => {
|
|
1180
|
+
if (!this.isDisposed && this.isOpen) {
|
|
1181
|
+
const hold = decideSynchronizedOutputFrameHold(this.wasmTerm.getMode(VtModes.SYNC_OUTPUT), this.synchronizedOutputHoldStartMs, nowMs);
|
|
1182
|
+
this.synchronizedOutputHoldStartMs = hold.holdStartMs;
|
|
1183
|
+
// Holding is a scheduler decision: return before render() calls
|
|
1184
|
+
// beginFrame() or consumes dirty state. The eventual paint therefore
|
|
1185
|
+
// sees every row dirtied during the synchronized update.
|
|
1186
|
+
if (hold.action === 'skip') {
|
|
1187
|
+
this.animationFrameId = requestAnimationFrame(loop);
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
// Render using WASM's native dirty tracking. render() snapshots the
|
|
1191
|
+
// state with beginFrame() and consumes dirty flags with endFrame().
|
|
1192
|
+
// Timing belongs here in the scheduler so every backend is measured
|
|
1193
|
+
// uniformly and reporting overhead stays outside the sample.
|
|
1194
|
+
const renderStartMs = performance.now();
|
|
1195
|
+
this.options.rendererTiming?.beforeRender?.();
|
|
1196
|
+
this.renderer.render(this.wasmTerm, false, this.viewportY, this, this.scrollbar.opacity);
|
|
1197
|
+
const cpuMs = performance.now() - renderStartMs;
|
|
1198
|
+
this.options.rendererTiming?.onFrame({ backend: this.renderer.backend, cpuMs });
|
|
1199
|
+
// Check for cursor movement (Phase 2: onCursorMove event)
|
|
1200
|
+
// Note: getCursor() reads from already-updated render state (from render() above)
|
|
1201
|
+
const cursor = this.wasmTerm.getCursor();
|
|
1202
|
+
if (cursor.y !== this.lastCursorY) {
|
|
1203
|
+
this.lastCursorY = cursor.y;
|
|
1204
|
+
this.cursorMoveEmitter.fire();
|
|
1205
|
+
}
|
|
1206
|
+
// Note: onRender event is intentionally not fired in the render loop
|
|
1207
|
+
// to avoid performance issues. For now, consumers can use requestAnimationFrame
|
|
1208
|
+
// if they need frame-by-frame updates.
|
|
1209
|
+
this.animationFrameId = requestAnimationFrame(loop);
|
|
1210
|
+
}
|
|
1211
|
+
};
|
|
1212
|
+
loop();
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Get a line from native WASM scrollback buffer
|
|
1216
|
+
* Implements IScrollbackProvider
|
|
1217
|
+
*/
|
|
1218
|
+
getScrollbackLine(offset) {
|
|
1219
|
+
if (!this.wasmTerm)
|
|
1220
|
+
return null;
|
|
1221
|
+
return this.wasmTerm.getScrollbackLine(offset);
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Get scrollback length from native WASM
|
|
1225
|
+
* Implements IScrollbackProvider
|
|
1226
|
+
*/
|
|
1227
|
+
getScrollbackLength() {
|
|
1228
|
+
if (!this.wasmTerm)
|
|
1229
|
+
return 0;
|
|
1230
|
+
return this.wasmTerm.getScrollbackLength();
|
|
1231
|
+
}
|
|
1232
|
+
/**
|
|
1233
|
+
* Clean up components (called on dispose or error)
|
|
1234
|
+
*/
|
|
1235
|
+
cleanupComponents() {
|
|
1236
|
+
// Dispose selection manager
|
|
1237
|
+
if (this.selectionManager) {
|
|
1238
|
+
this.selectionManager.dispose();
|
|
1239
|
+
this.selectionManager = undefined;
|
|
1240
|
+
}
|
|
1241
|
+
// Dispose input handler
|
|
1242
|
+
if (this.inputHandler) {
|
|
1243
|
+
this.inputHandler.dispose();
|
|
1244
|
+
this.inputHandler = undefined;
|
|
1245
|
+
}
|
|
1246
|
+
// Dispose renderer
|
|
1247
|
+
if (this.renderer) {
|
|
1248
|
+
this.renderer.dispose();
|
|
1249
|
+
this.renderer = undefined;
|
|
1250
|
+
}
|
|
1251
|
+
// Remove canvas from DOM
|
|
1252
|
+
if (this.canvas && this.canvas.parentNode) {
|
|
1253
|
+
this.canvas.parentNode.removeChild(this.canvas);
|
|
1254
|
+
this.canvas = undefined;
|
|
1255
|
+
}
|
|
1256
|
+
// Remove textarea from DOM
|
|
1257
|
+
if (this.textarea && this.textarea.parentNode) {
|
|
1258
|
+
this.textarea.parentNode.removeChild(this.textarea);
|
|
1259
|
+
this.textarea = undefined;
|
|
1260
|
+
}
|
|
1261
|
+
// Remove our root subtree — leaves the consumer's host exactly as found.
|
|
1262
|
+
if (this.root && this.root.parentNode) {
|
|
1263
|
+
this.root.parentNode.removeChild(this.root);
|
|
1264
|
+
this.root = undefined;
|
|
1265
|
+
}
|
|
1266
|
+
// Remove event listeners
|
|
1267
|
+
if (this.element) {
|
|
1268
|
+
this.element.removeEventListener('wheel', this.handleWheel);
|
|
1269
|
+
this.element.removeEventListener('mousedown', this.handleMouseDown, { capture: true });
|
|
1270
|
+
this.element.removeEventListener('mousemove', this.handleMouseMove);
|
|
1271
|
+
this.element.removeEventListener('mouseleave', this.handleMouseLeave);
|
|
1272
|
+
this.element.removeEventListener('click', this.handleClick);
|
|
1273
|
+
// Remove contenteditable and accessibility attributes added in open()
|
|
1274
|
+
this.element.removeAttribute('contenteditable');
|
|
1275
|
+
this.element.removeAttribute('role');
|
|
1276
|
+
this.element.removeAttribute('aria-label');
|
|
1277
|
+
this.element.removeAttribute('aria-multiline');
|
|
1278
|
+
// Restore the native caret we suppressed in open()
|
|
1279
|
+
this.element.style.caretColor = '';
|
|
1280
|
+
}
|
|
1281
|
+
// Remove document-level listeners (only if opened)
|
|
1282
|
+
if (this.isOpen && typeof document !== 'undefined') {
|
|
1283
|
+
document.removeEventListener('mouseup', this.handleMouseUp);
|
|
1284
|
+
}
|
|
1285
|
+
// Dispose link detector
|
|
1286
|
+
if (this.linkDetector) {
|
|
1287
|
+
this.linkDetector.dispose();
|
|
1288
|
+
this.linkDetector = undefined;
|
|
1289
|
+
}
|
|
1290
|
+
// Free WASM terminal — effects first: registrations must be cleared and
|
|
1291
|
+
// table slots recycled while the handle is still alive (vt/effects.ts).
|
|
1292
|
+
if (this.effects) {
|
|
1293
|
+
this.effects.dispose();
|
|
1294
|
+
this.effects = undefined;
|
|
1295
|
+
}
|
|
1296
|
+
if (this.wasmTerm) {
|
|
1297
|
+
this.wasmTerm.free();
|
|
1298
|
+
this.wasmTerm = undefined;
|
|
1299
|
+
}
|
|
1300
|
+
// Clear references
|
|
1301
|
+
this.ghostty = undefined;
|
|
1302
|
+
this.element = undefined;
|
|
1303
|
+
this.textarea = undefined;
|
|
1304
|
+
}
|
|
1305
|
+
/**
|
|
1306
|
+
* Assert terminal is open (throw if not)
|
|
1307
|
+
*/
|
|
1308
|
+
assertOpen() {
|
|
1309
|
+
if (this.isDisposed) {
|
|
1310
|
+
throw new Error('Terminal has been disposed');
|
|
1311
|
+
}
|
|
1312
|
+
if (!this.isOpen) {
|
|
1313
|
+
throw new Error('Terminal must be opened before use. Call terminal.open(parent) first.');
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* Handle mouse move for link hover detection and scrollbar dragging
|
|
1318
|
+
* Throttled to avoid blocking scroll events (except when dragging scrollbar)
|
|
1319
|
+
*/
|
|
1320
|
+
handleMouseMove = (e) => {
|
|
1321
|
+
if (!this.canvas || !this.renderer || !this.wasmTerm)
|
|
1322
|
+
return;
|
|
1323
|
+
// If dragging scrollbar, handle immediately without throttling
|
|
1324
|
+
if (this.scrollbar.dragging) {
|
|
1325
|
+
this.processScrollbarDrag(e);
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
if (!this.linkDetector)
|
|
1329
|
+
return;
|
|
1330
|
+
// Throttle to ~60fps (16ms) to avoid blocking scroll/other events
|
|
1331
|
+
if (this.mouseMoveThrottleTimeout) {
|
|
1332
|
+
this.pendingMouseMove = e;
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
this.processMouseMove(e);
|
|
1336
|
+
this.mouseMoveThrottleTimeout = window.setTimeout(() => {
|
|
1337
|
+
this.mouseMoveThrottleTimeout = undefined;
|
|
1338
|
+
if (this.pendingMouseMove) {
|
|
1339
|
+
const pending = this.pendingMouseMove;
|
|
1340
|
+
this.pendingMouseMove = undefined;
|
|
1341
|
+
this.processMouseMove(pending);
|
|
1342
|
+
}
|
|
1343
|
+
}, 16);
|
|
1344
|
+
};
|
|
1345
|
+
/**
|
|
1346
|
+
* Process mouse move for link detection (internal, called by throttled handler)
|
|
1347
|
+
*/
|
|
1348
|
+
processMouseMove(e) {
|
|
1349
|
+
if (!this.canvas || !this.renderer || !this.linkDetector || !this.wasmTerm)
|
|
1350
|
+
return;
|
|
1351
|
+
// Convert mouse coordinates to terminal cell position
|
|
1352
|
+
// Pixel→cell goes through the geometry authority: the mouse has event
|
|
1353
|
+
// coordinates and needs a cell — where the grid sits on the surface
|
|
1354
|
+
// (padding, coalesced slack) is the grid model's business, nobody else's.
|
|
1355
|
+
const rect = this.canvas.getBoundingClientRect();
|
|
1356
|
+
const { col: x, row: y } = this.geometry.cellAt(e.clientX - rect.left, e.clientY - rect.top);
|
|
1357
|
+
// Get hyperlink_id directly from the cell at this position
|
|
1358
|
+
// Must account for viewportY (scrollback position)
|
|
1359
|
+
const viewportRow = y; // Row in the viewport (0 to rows-1)
|
|
1360
|
+
let hyperlinkId = 0;
|
|
1361
|
+
// When scrolled, fetch from scrollback or screen based on position
|
|
1362
|
+
// NOTE: viewportY may be fractional during smooth scrolling. The renderer
|
|
1363
|
+
// uses Math.floor(viewportY) when mapping viewport rows to scrollback vs
|
|
1364
|
+
// screen; we mirror that logic here so link hit-testing matches what the
|
|
1365
|
+
// user sees on screen.
|
|
1366
|
+
let line = null;
|
|
1367
|
+
const rawViewportY = this.getViewportY();
|
|
1368
|
+
const viewportY = Math.max(0, Math.floor(rawViewportY));
|
|
1369
|
+
if (viewportY > 0) {
|
|
1370
|
+
const scrollbackLength = this.wasmTerm.getScrollbackLength();
|
|
1371
|
+
if (viewportRow < viewportY) {
|
|
1372
|
+
// Mouse is over scrollback content
|
|
1373
|
+
const scrollbackOffset = scrollbackLength - viewportY + viewportRow;
|
|
1374
|
+
line = this.wasmTerm.getScrollbackLine(scrollbackOffset);
|
|
1375
|
+
}
|
|
1376
|
+
else {
|
|
1377
|
+
// Mouse is over screen content (bottom part of viewport)
|
|
1378
|
+
const screenRow = viewportRow - viewportY;
|
|
1379
|
+
line = this.wasmTerm.getLine(screenRow);
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
else {
|
|
1383
|
+
// At bottom - just use screen buffer
|
|
1384
|
+
line = this.wasmTerm.getLine(viewportRow);
|
|
1385
|
+
}
|
|
1386
|
+
if (line && x >= 0 && x < line.length) {
|
|
1387
|
+
hyperlinkId = line[x].hyperlink_id;
|
|
1388
|
+
}
|
|
1389
|
+
// Update renderer for underline rendering
|
|
1390
|
+
const previousHyperlinkId = this.renderer.hoveredHyperlinkId || 0;
|
|
1391
|
+
if (hyperlinkId !== previousHyperlinkId) {
|
|
1392
|
+
this.renderer.setHoveredHyperlinkId(hyperlinkId);
|
|
1393
|
+
// The 60fps render loop will pick up the change automatically
|
|
1394
|
+
// No need to force a render - this keeps performance smooth
|
|
1395
|
+
}
|
|
1396
|
+
// Check if there's a link at this position (for click handling and cursor)
|
|
1397
|
+
// Buffer API expects absolute buffer coordinates (including scrollback)
|
|
1398
|
+
// When scrolled, we need to adjust the buffer row based on viewportY
|
|
1399
|
+
const scrollbackLength = this.wasmTerm.getScrollbackLength();
|
|
1400
|
+
let bufferRow;
|
|
1401
|
+
// Use floored viewportY for buffer mapping (must match renderer & selection)
|
|
1402
|
+
const rawViewportYForBuffer = this.getViewportY();
|
|
1403
|
+
const viewportYForBuffer = Math.max(0, Math.floor(rawViewportYForBuffer));
|
|
1404
|
+
if (viewportYForBuffer > 0) {
|
|
1405
|
+
// When scrolled, the buffer row depends on where in the viewport we are
|
|
1406
|
+
if (viewportRow < viewportYForBuffer) {
|
|
1407
|
+
// Mouse is over scrollback content
|
|
1408
|
+
bufferRow = scrollbackLength - viewportYForBuffer + viewportRow;
|
|
1409
|
+
}
|
|
1410
|
+
else {
|
|
1411
|
+
// Mouse is over screen content (bottom part of viewport)
|
|
1412
|
+
const screenRow = viewportRow - viewportYForBuffer;
|
|
1413
|
+
bufferRow = scrollbackLength + screenRow;
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
else {
|
|
1417
|
+
// At bottom - buffer row is scrollback + screen row
|
|
1418
|
+
bufferRow = scrollbackLength + viewportRow;
|
|
1419
|
+
}
|
|
1420
|
+
// Make async call non-blocking - don't await
|
|
1421
|
+
this.linkDetector
|
|
1422
|
+
.getLinkAt(x, bufferRow)
|
|
1423
|
+
.then((link) => {
|
|
1424
|
+
// Update hover state for cursor changes and click handling
|
|
1425
|
+
if (link !== this.currentHoveredLink) {
|
|
1426
|
+
// Notify old link we're leaving
|
|
1427
|
+
this.currentHoveredLink?.hover?.(false);
|
|
1428
|
+
// Update current link
|
|
1429
|
+
this.currentHoveredLink = link;
|
|
1430
|
+
// Notify new link we're entering
|
|
1431
|
+
link?.hover?.(true);
|
|
1432
|
+
// Update cursor style on both container and canvas
|
|
1433
|
+
const cursorStyle = link ? 'pointer' : 'text';
|
|
1434
|
+
if (this.element) {
|
|
1435
|
+
this.element.style.cursor = cursorStyle;
|
|
1436
|
+
}
|
|
1437
|
+
if (this.canvas) {
|
|
1438
|
+
this.canvas.style.cursor = cursorStyle;
|
|
1439
|
+
}
|
|
1440
|
+
// Update renderer for underline (for regex URLs without hyperlink_id)
|
|
1441
|
+
if (this.renderer) {
|
|
1442
|
+
if (link) {
|
|
1443
|
+
// Convert buffer coordinates to viewport coordinates
|
|
1444
|
+
const scrollbackLength = this.wasmTerm?.getScrollbackLength() || 0;
|
|
1445
|
+
// Calculate viewport Y for start and end positions
|
|
1446
|
+
// Use floored viewportY so overlay rows match renderer & selection
|
|
1447
|
+
const rawViewportYForLinks = this.getViewportY();
|
|
1448
|
+
const viewportYForLinks = Math.max(0, Math.floor(rawViewportYForLinks));
|
|
1449
|
+
const startViewportY = link.range.start.y - scrollbackLength + viewportYForLinks;
|
|
1450
|
+
const endViewportY = link.range.end.y - scrollbackLength + viewportYForLinks;
|
|
1451
|
+
// Only show underline if link is visible in viewport
|
|
1452
|
+
if (startViewportY < this.rows && endViewportY >= 0) {
|
|
1453
|
+
this.renderer.setHoveredLinkRange({
|
|
1454
|
+
startX: link.range.start.x,
|
|
1455
|
+
startY: Math.max(0, startViewportY),
|
|
1456
|
+
endX: link.range.end.x,
|
|
1457
|
+
endY: Math.min(this.rows - 1, endViewportY),
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
else {
|
|
1461
|
+
this.renderer.setHoveredLinkRange(null);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
else {
|
|
1465
|
+
this.renderer.setHoveredLinkRange(null);
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
})
|
|
1470
|
+
.catch((err) => {
|
|
1471
|
+
console.warn('Link detection error:', err);
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* Handle mouse leave to clear link hover
|
|
1476
|
+
*/
|
|
1477
|
+
handleMouseLeave = () => {
|
|
1478
|
+
// Clear hyperlink underline
|
|
1479
|
+
if (this.renderer && this.wasmTerm) {
|
|
1480
|
+
const previousHyperlinkId = this.renderer.hoveredHyperlinkId || 0;
|
|
1481
|
+
if (previousHyperlinkId > 0) {
|
|
1482
|
+
this.renderer.setHoveredHyperlinkId(0);
|
|
1483
|
+
// The 60fps render loop will pick up the change automatically
|
|
1484
|
+
}
|
|
1485
|
+
// Clear regex link underline
|
|
1486
|
+
this.renderer.setHoveredLinkRange(null);
|
|
1487
|
+
}
|
|
1488
|
+
if (this.currentHoveredLink) {
|
|
1489
|
+
// Notify link we're leaving
|
|
1490
|
+
this.currentHoveredLink.hover?.(false);
|
|
1491
|
+
// Clear hovered link
|
|
1492
|
+
this.currentHoveredLink = undefined;
|
|
1493
|
+
// Reset cursor
|
|
1494
|
+
if (this.element) {
|
|
1495
|
+
this.element.style.cursor = 'text';
|
|
1496
|
+
if (this.canvas) {
|
|
1497
|
+
this.canvas.style.cursor = 'text';
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
};
|
|
1502
|
+
/**
|
|
1503
|
+
* Handle mouse click for link activation
|
|
1504
|
+
*/
|
|
1505
|
+
handleClick = async (e) => {
|
|
1506
|
+
// For more reliable clicking, detect the link at click time
|
|
1507
|
+
// rather than relying on cached hover state (avoids async races)
|
|
1508
|
+
if (!this.canvas || !this.renderer || !this.linkDetector || !this.wasmTerm)
|
|
1509
|
+
return;
|
|
1510
|
+
// Get click position
|
|
1511
|
+
const rect = this.canvas.getBoundingClientRect();
|
|
1512
|
+
const { col: x, row: y } = this.geometry.cellAt(e.clientX - rect.left, e.clientY - rect.top);
|
|
1513
|
+
// Calculate buffer row (same logic as processMouseMove)
|
|
1514
|
+
const viewportRow = y;
|
|
1515
|
+
const scrollbackLength = this.wasmTerm.getScrollbackLength();
|
|
1516
|
+
let bufferRow;
|
|
1517
|
+
// Use floored viewportY for buffer mapping (must match renderer & selection)
|
|
1518
|
+
const rawViewportYForClick = this.getViewportY();
|
|
1519
|
+
const viewportYForClick = Math.max(0, Math.floor(rawViewportYForClick));
|
|
1520
|
+
if (viewportYForClick > 0) {
|
|
1521
|
+
if (viewportRow < viewportYForClick) {
|
|
1522
|
+
bufferRow = scrollbackLength - viewportYForClick + viewportRow;
|
|
1523
|
+
}
|
|
1524
|
+
else {
|
|
1525
|
+
const screenRow = viewportRow - viewportYForClick;
|
|
1526
|
+
bufferRow = scrollbackLength + screenRow;
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
else {
|
|
1530
|
+
bufferRow = scrollbackLength + viewportRow;
|
|
1531
|
+
}
|
|
1532
|
+
// Get the link at this position
|
|
1533
|
+
const link = await this.linkDetector.getLinkAt(x, bufferRow);
|
|
1534
|
+
if (link) {
|
|
1535
|
+
// Activate link
|
|
1536
|
+
link.activate(e);
|
|
1537
|
+
// Prevent default action if modifier key held
|
|
1538
|
+
if (e.ctrlKey || e.metaKey) {
|
|
1539
|
+
e.preventDefault();
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
};
|
|
1543
|
+
/**
|
|
1544
|
+
* Handle wheel events for scrolling (Phase 2)
|
|
1545
|
+
*/
|
|
1546
|
+
handleWheel = (e) => {
|
|
1547
|
+
// Always prevent default browser scrolling
|
|
1548
|
+
e.preventDefault();
|
|
1549
|
+
e.stopPropagation();
|
|
1550
|
+
// Allow custom handler to override
|
|
1551
|
+
if (this.customWheelEventHandler && this.customWheelEventHandler(e)) {
|
|
1552
|
+
return;
|
|
1553
|
+
}
|
|
1554
|
+
// Check if in alternate screen mode (vim, less, htop, etc.)
|
|
1555
|
+
const isAltScreen = this.wasmTerm?.isAlternateScreen() ?? false;
|
|
1556
|
+
if (isAltScreen) {
|
|
1557
|
+
// Alternate screen: send arrow keys to the application
|
|
1558
|
+
// Applications like vim handle scrolling internally
|
|
1559
|
+
// Standard: ~3 arrow presses per wheel "click"
|
|
1560
|
+
const direction = e.deltaY > 0 ? 'down' : 'up';
|
|
1561
|
+
const count = Math.min(Math.abs(Math.round(e.deltaY / 33)), 5); // Cap at 5
|
|
1562
|
+
for (let i = 0; i < count; i++) {
|
|
1563
|
+
if (direction === 'up') {
|
|
1564
|
+
this.dataEmitter.fire('\x1B[A'); // Up arrow
|
|
1565
|
+
}
|
|
1566
|
+
else {
|
|
1567
|
+
this.dataEmitter.fire('\x1B[B'); // Down arrow
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
else {
|
|
1572
|
+
// Normal screen: scroll viewport through history with smooth scrolling
|
|
1573
|
+
// Handle different deltaMode values for better trackpad/mouse support
|
|
1574
|
+
let deltaLines;
|
|
1575
|
+
if (e.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {
|
|
1576
|
+
// Pixel mode (trackpads): convert pixels to lines
|
|
1577
|
+
// Use actual line height from renderer for accurate conversion
|
|
1578
|
+
const lineHeight = this.renderer?.getMetrics()?.height ?? 20;
|
|
1579
|
+
deltaLines = e.deltaY / lineHeight;
|
|
1580
|
+
}
|
|
1581
|
+
else if (e.deltaMode === WheelEvent.DOM_DELTA_LINE) {
|
|
1582
|
+
// Line mode (some mice): use directly
|
|
1583
|
+
deltaLines = e.deltaY;
|
|
1584
|
+
}
|
|
1585
|
+
else if (e.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
|
|
1586
|
+
// Page mode (rare): convert pages to lines
|
|
1587
|
+
deltaLines = e.deltaY * this.rows;
|
|
1588
|
+
}
|
|
1589
|
+
else {
|
|
1590
|
+
// Fallback: assume pixel mode with legacy divisor
|
|
1591
|
+
deltaLines = e.deltaY / 33;
|
|
1592
|
+
}
|
|
1593
|
+
// Use smooth scrolling for any amount (no rounding needed)
|
|
1594
|
+
if (deltaLines !== 0) {
|
|
1595
|
+
// Calculate target position
|
|
1596
|
+
// deltaY > 0 = scroll down (decrease viewportY)
|
|
1597
|
+
// deltaY < 0 = scroll up (increase viewportY)
|
|
1598
|
+
const targetY = this.scroller.currentTarget - deltaLines;
|
|
1599
|
+
this.scroller.smoothScrollTo(targetY);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
};
|
|
1603
|
+
/**
|
|
1604
|
+
* Handle mouse down for scrollbar interaction
|
|
1605
|
+
*/
|
|
1606
|
+
handleMouseDown = (e) => {
|
|
1607
|
+
if (!this.canvas || !this.renderer || !this.wasmTerm)
|
|
1608
|
+
return;
|
|
1609
|
+
const scrollbackLength = this.wasmTerm.getScrollbackLength();
|
|
1610
|
+
if (scrollbackLength === 0)
|
|
1611
|
+
return; // No scrollbar if no scrollback
|
|
1612
|
+
const rect = this.canvas.getBoundingClientRect();
|
|
1613
|
+
const mouseX = e.clientX - rect.left;
|
|
1614
|
+
const mouseY = e.clientY - rect.top;
|
|
1615
|
+
// Calculate scrollbar dimensions (match renderer's logic)
|
|
1616
|
+
// Use rect dimensions which are already in CSS pixels
|
|
1617
|
+
const canvasWidth = rect.width;
|
|
1618
|
+
const canvasHeight = rect.height;
|
|
1619
|
+
const scrollbarWidth = 8;
|
|
1620
|
+
const scrollbarX = canvasWidth - scrollbarWidth - 4;
|
|
1621
|
+
const scrollbarPadding = 4;
|
|
1622
|
+
// Check if click is in scrollbar area
|
|
1623
|
+
if (mouseX >= scrollbarX && mouseX <= scrollbarX + scrollbarWidth) {
|
|
1624
|
+
// Prevent default and stop propagation to prevent text selection
|
|
1625
|
+
e.preventDefault();
|
|
1626
|
+
e.stopPropagation();
|
|
1627
|
+
e.stopImmediatePropagation(); // Stop SelectionManager from seeing this event
|
|
1628
|
+
// Calculate scrollbar thumb position and size
|
|
1629
|
+
const scrollbarTrackHeight = canvasHeight - scrollbarPadding * 2;
|
|
1630
|
+
const visibleRows = this.rows;
|
|
1631
|
+
const totalLines = scrollbackLength + visibleRows;
|
|
1632
|
+
const thumbHeight = Math.max(20, (visibleRows / totalLines) * scrollbarTrackHeight);
|
|
1633
|
+
const scrollPosition = this.viewportY / scrollbackLength;
|
|
1634
|
+
const thumbY = scrollbarPadding + (scrollbarTrackHeight - thumbHeight) * (1 - scrollPosition);
|
|
1635
|
+
// Check if click is on thumb
|
|
1636
|
+
if (mouseY >= thumbY && mouseY <= thumbY + thumbHeight) {
|
|
1637
|
+
// Start dragging thumb (suppresses scrollbar auto-hide)
|
|
1638
|
+
this.scrollbar.beginDrag();
|
|
1639
|
+
this.scrollbarDragStart = mouseY;
|
|
1640
|
+
this.scrollbarDragStartViewportY = this.viewportY;
|
|
1641
|
+
// Prevent text selection during drag
|
|
1642
|
+
if (this.canvas) {
|
|
1643
|
+
this.canvas.style.userSelect = 'none';
|
|
1644
|
+
this.canvas.style.webkitUserSelect = 'none';
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
else {
|
|
1648
|
+
// Click on track - jump to position
|
|
1649
|
+
const relativeY = mouseY - scrollbarPadding;
|
|
1650
|
+
const scrollFraction = 1 - relativeY / scrollbarTrackHeight; // Inverted: top = 1, bottom = 0
|
|
1651
|
+
const targetViewportY = Math.round(scrollFraction * scrollbackLength);
|
|
1652
|
+
this.scrollToLine(Math.max(0, Math.min(scrollbackLength, targetViewportY)));
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
};
|
|
1656
|
+
/**
|
|
1657
|
+
* Handle mouse up for scrollbar drag
|
|
1658
|
+
*/
|
|
1659
|
+
handleMouseUp = () => {
|
|
1660
|
+
if (this.scrollbar.dragging) {
|
|
1661
|
+
this.scrollbarDragStart = null;
|
|
1662
|
+
// Restore text selection
|
|
1663
|
+
if (this.canvas) {
|
|
1664
|
+
this.canvas.style.userSelect = '';
|
|
1665
|
+
this.canvas.style.webkitUserSelect = '';
|
|
1666
|
+
}
|
|
1667
|
+
// End drag: re-arms the scrollbar auto-hide timer
|
|
1668
|
+
this.scrollbar.endDrag();
|
|
1669
|
+
}
|
|
1670
|
+
};
|
|
1671
|
+
/**
|
|
1672
|
+
* Process scrollbar drag movement
|
|
1673
|
+
*/
|
|
1674
|
+
processScrollbarDrag(e) {
|
|
1675
|
+
if (!this.canvas || !this.renderer || !this.wasmTerm || this.scrollbarDragStart === null)
|
|
1676
|
+
return;
|
|
1677
|
+
const scrollbackLength = this.wasmTerm.getScrollbackLength();
|
|
1678
|
+
if (scrollbackLength === 0)
|
|
1679
|
+
return;
|
|
1680
|
+
const rect = this.canvas.getBoundingClientRect();
|
|
1681
|
+
const mouseY = e.clientY - rect.top;
|
|
1682
|
+
// Calculate how much the mouse moved
|
|
1683
|
+
const deltaY = mouseY - this.scrollbarDragStart;
|
|
1684
|
+
// Convert mouse delta to viewport delta
|
|
1685
|
+
// Use rect height which is already in CSS pixels
|
|
1686
|
+
const canvasHeight = rect.height;
|
|
1687
|
+
const scrollbarPadding = 4;
|
|
1688
|
+
const scrollbarTrackHeight = canvasHeight - scrollbarPadding * 2;
|
|
1689
|
+
const visibleRows = this.rows;
|
|
1690
|
+
const totalLines = scrollbackLength + visibleRows;
|
|
1691
|
+
const thumbHeight = Math.max(20, (visibleRows / totalLines) * scrollbarTrackHeight);
|
|
1692
|
+
// Calculate scroll fraction from thumb movement
|
|
1693
|
+
// Note: thumb moves in opposite direction to viewport (thumb down = scroll down = viewportY decreases)
|
|
1694
|
+
const scrollFraction = -deltaY / (scrollbarTrackHeight - thumbHeight);
|
|
1695
|
+
const viewportDelta = Math.round(scrollFraction * scrollbackLength);
|
|
1696
|
+
const newViewportY = this.scrollbarDragStartViewportY + viewportDelta;
|
|
1697
|
+
this.scrollToLine(Math.max(0, Math.min(scrollbackLength, newViewportY)));
|
|
1698
|
+
}
|
|
1699
|
+
// ============================================================================
|
|
1700
|
+
// Terminal Modes
|
|
1701
|
+
// ============================================================================
|
|
1702
|
+
/**
|
|
1703
|
+
* Query terminal mode state
|
|
1704
|
+
*
|
|
1705
|
+
* @param mode Mode number (e.g., 2004 for bracketed paste)
|
|
1706
|
+
* @param isAnsi True for ANSI modes, false for DEC modes (default: false)
|
|
1707
|
+
* @returns true if mode is enabled
|
|
1708
|
+
*/
|
|
1709
|
+
getMode(mode, isAnsi = false) {
|
|
1710
|
+
this.assertOpen();
|
|
1711
|
+
return this.wasmTerm.getMode(mode, isAnsi);
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Check if bracketed paste mode is enabled
|
|
1715
|
+
*/
|
|
1716
|
+
hasBracketedPaste() {
|
|
1717
|
+
this.assertOpen();
|
|
1718
|
+
return this.wasmTerm.hasBracketedPaste();
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* Check if focus event reporting is enabled
|
|
1722
|
+
*/
|
|
1723
|
+
hasFocusEvents() {
|
|
1724
|
+
this.assertOpen();
|
|
1725
|
+
return this.wasmTerm.hasFocusEvents();
|
|
1726
|
+
}
|
|
1727
|
+
/**
|
|
1728
|
+
* Check if mouse tracking is enabled
|
|
1729
|
+
*/
|
|
1730
|
+
hasMouseTracking() {
|
|
1731
|
+
this.assertOpen();
|
|
1732
|
+
return this.wasmTerm.hasMouseTracking();
|
|
1733
|
+
}
|
|
1734
|
+
}
|
|
1735
|
+
/**
|
|
1736
|
+
* Standard xterm 256-color fallback for palette slots not supplied by a theme.
|
|
1737
|
+
* Themes normally define only ANSI 0-15; indexed SGR still needs 16-255.
|
|
1738
|
+
*/
|
|
1739
|
+
export function defaultIndexedColor(index) {
|
|
1740
|
+
if (index < 16)
|
|
1741
|
+
return { r: 0, g: 0, b: 0 };
|
|
1742
|
+
if (index < 232) {
|
|
1743
|
+
const cube = [0, 95, 135, 175, 215, 255];
|
|
1744
|
+
const offset = index - 16;
|
|
1745
|
+
return {
|
|
1746
|
+
r: cube[Math.floor(offset / 36)],
|
|
1747
|
+
g: cube[Math.floor(offset / 6) % 6],
|
|
1748
|
+
b: cube[offset % 6],
|
|
1749
|
+
};
|
|
1750
|
+
}
|
|
1751
|
+
const channel = 8 + (index - 232) * 10;
|
|
1752
|
+
return { r: channel, g: channel, b: channel };
|
|
1753
|
+
}
|
|
1754
|
+
//# sourceMappingURL=terminal.js.map
|