@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 2,313 lines 82.7 KB
Raw
1 import { resolveEventKeys } from "@t3tools/shared/keybindingMatching";
2 import { isMacPlatform } from "../../lib/utils";
3 import { SELECTION_MULTI_CLICK_INTERVAL_MS } from "../../lib/selectionActions";
4 import { collectWrappedTerminalLinkLine, extractTerminalLinks } from "../../terminal-links";
5 import {
6 GHOSTTY_CELL_WIDE,
7 GhosttyTerminalCore,
8 ghosttyColorsEqual,
9 type GhosttyCell,
10 type GhosttyScrollbar,
11 type GhosttySnapshot,
12 type GhosttyTheme,
13 } from "./core";
14 import {
15 measureGhosttyCell,
16 renderGhosttySnapshot,
17 terminalGridSize,
18 type GhosttyCellRange,
19 type GhosttyCellMetrics,
20 } from "./renderer";
21 import symbolsFontUrl from "./fonts/SymbolsNerdFontMono-Regular.woff2?url";
22 import { isMonospaceFamily } from "../../appearanceFonts";
23 import { observeResize } from "../../lib/observeResize";
24 import { msg } from "gt-react";
25 import { m } from "../../i18n/messages";
26
27 const DEFAULT_TERMINAL_FONT_SIZE = 12;
28 const MIN_TERMINAL_FONT_SIZE = 6;
29 const MAX_TERMINAL_FONT_SIZE = 32;
30 const TERMINAL_GLYPH_FALLBACKS =
31 '"Symbols Nerd Font Mono", "Symbols Nerd Font", "JetBrainsMono Nerd Font", ' +
32 '"JetBrainsMono NF", "FiraCode Nerd Font", "Hack Nerd Font", "MesloLGS NF", ' +
33 '"CaskaydiaCove Nerd Font", "PowerlineSymbols", monospace';
34 // The platform's own monospace faces; concrete names only, because an
35 // unknown keyword (like ui-monospace) makes canvas font shorthand parsing
36 // reject the whole string.
37 const DEFAULT_TERMINAL_FONT_FAMILY =
38 '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", ' + TERMINAL_GLYPH_FALLBACKS;
39 const CONTENT_PADDING = 4;
40 const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
41 const CURSOR_BLINK_INTERVAL_MS = 500;
42 const TERMINAL_LINK_HOVER_DELAY_MS = 250;
43 /** End an unterminated synchronized update instead of freezing the last frame. */
44 const SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS = 500;
45 const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
46 const TERMINAL_FONT_LOAD_VARIANTS = [
47 "normal 400",
48 "normal 700",
49 "italic 400",
50 "italic 700",
51 ] as const;
52
53 export interface GhosttyTerminalFont {
54 readonly family?: string;
55 readonly size?: number;
56 }
57
58 let symbolsFontLoad: Promise<void> | null = null;
59
60 function ensureTerminalSymbolsFont(): Promise<void> {
61 if (symbolsFontLoad !== null) return symbolsFontLoad;
62 symbolsFontLoad = (async () => {
63 try {
64 const face = new FontFace("Symbols Nerd Font Mono", `url(${symbolsFontUrl})`);
65 document.fonts.add(await face.load());
66 } catch {}
67 })();
68 return symbolsFontLoad;
69 }
70
71 function quoteTerminalFontFamilies(list: string): string {
72 return list
73 .split(",")
74 .map((name) => {
75 const bare = name.trim();
76 if (bare.length === 0) return "";
77 if (/^(['"]).*\1$/.test(bare)) return bare;
78 if (/^[a-zA-Z][a-zA-Z0-9-]*$/.test(bare)) return bare;
79 return `"${bare.replaceAll('"', "")}"`;
80 })
81 .filter((name) => name.length > 0)
82 .join(", ");
83 }
84
85 function uncheckedTerminalFontFamily(family?: string): string {
86 const custom = family === undefined ? "" : quoteTerminalFontFamilies(family);
87 return custom.length === 0
88 ? DEFAULT_TERMINAL_FONT_FAMILY
89 : `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
90 }
91
92 function terminalFontFamily(family?: string): string {
93 // Quote non-ident names ("3270 Nerd Font", "M+ 1m"): an unquoted one makes
94 // the whole canvas font string invalid and the assignment silently no-ops.
95 const custom = family === undefined ? "" : quoteTerminalFontFamilies(family);
96 if (custom.length === 0) return DEFAULT_TERMINAL_FONT_FAMILY;
97 if (!isMonospaceFamily(custom)) return DEFAULT_TERMINAL_FONT_FAMILY;
98 return uncheckedTerminalFontFamily(custom);
99 }
100
101 async function loadTerminalFontFamily(
102 family: string | undefined,
103 size: number,
104 environment?: {
105 readonly load: (font: string, text: string) => Promise<unknown>;
106 readonly resolve: (family: string | undefined) => string;
107 },
108 ): Promise<string> {
109 const candidate = uncheckedTerminalFontFamily(family);
110 const load =
111 environment?.load ?? ((font: string, text: string) => document.fonts.load(font, text));
112 try {
113 await Promise.all(
114 TERMINAL_FONT_LOAD_VARIANTS.map((variant) =>
115 load(`${variant} ${size}px ${candidate}`, TERMINAL_FONT_LOAD_TEXT),
116 ),
117 );
118 } catch {}
119 return (environment?.resolve ?? terminalFontFamily)(family);
120 }
121
122 function terminalFontSize(size?: number): number {
123 if (size === undefined || !Number.isFinite(size)) return DEFAULT_TERMINAL_FONT_SIZE;
124 return Math.max(MIN_TERMINAL_FONT_SIZE, Math.min(MAX_TERMINAL_FONT_SIZE, Math.round(size)));
125 }
126
127 function shouldBlinkTerminalCursor(state: {
128 readonly focused: boolean;
129 readonly cursorBlinking: boolean;
130 readonly cursorVisible: boolean;
131 readonly reducedMotion: boolean;
132 }): boolean {
133 return state.focused && state.cursorBlinking && state.cursorVisible && !state.reducedMotion;
134 }
135
136 export function terminalContentOriginY(
137 mountHeight: number,
138 padding: number,
139 rows: number,
140 cellHeight: number,
141 anchorBottom: boolean,
142 ): number {
143 if (!anchorBottom) return padding;
144 const slack = mountHeight - padding * 2 - rows * cellHeight;
145 return padding + Math.max(0, slack);
146 }
147
148 export interface TerminalScrollbarGeometry {
149 readonly thumbHeight: number;
150 readonly thumbTop: number;
151 readonly maxOffset: number;
152 }
153
154 function terminalScrollbarGeometry(
155 state: GhosttyScrollbar,
156 trackHeight: number,
157 ): TerminalScrollbarGeometry | null {
158 const total = Math.max(0, state.total);
159 const len = Math.max(0, Math.min(state.len, total));
160 const maxOffset = Math.max(0, total - len);
161 if (trackHeight <= 0 || len <= 0 || maxOffset === 0) return null;
162 const thumbHeight = Math.min(
163 trackHeight,
164 Math.max(MIN_SCROLLBAR_THUMB_HEIGHT, (trackHeight * len) / total),
165 );
166 const travel = Math.max(0, trackHeight - thumbHeight);
167 const offset = Math.max(0, Math.min(state.offset, maxOffset));
168 return {
169 thumbHeight,
170 thumbTop: travel * (offset / maxOffset),
171 maxOffset,
172 };
173 }
174
175 function terminalScrollbarOffsetAtPointer(
176 state: GhosttyScrollbar,
177 trackHeight: number,
178 pointerY: number,
179 pointerOffset: number,
180 ): number {
181 const geometry = terminalScrollbarGeometry(state, trackHeight);
182 if (geometry === null) return 0;
183 const travel = Math.max(0, trackHeight - geometry.thumbHeight);
184 if (travel === 0) return 0;
185 const thumbTop = Math.max(0, Math.min(pointerY - pointerOffset, travel));
186 return Math.round((thumbTop / travel) * geometry.maxOffset);
187 }
188
189 function terminalGridCellAt(options: {
190 bounds: { left: number; top: number };
191 clientX: number;
192 clientY: number;
193 cols: number;
194 rows: number;
195 metrics: Pick<GhosttyCellMetrics, "width" | "height">;
196 padding: number;
197 originY: number;
198 }): { x: number; y: number } | null {
199 const { bounds, clientX, clientY, cols, rows, metrics, padding, originY } = options;
200 const gridX = clientX - bounds.left - padding;
201 const gridY = clientY - bounds.top - originY;
202 if (gridX < 0 || gridY < 0 || gridX >= cols * metrics.width || gridY >= rows * metrics.height) {
203 return null;
204 }
205 return {
206 x: Math.floor(gridX / metrics.width),
207 y: Math.floor(gridY / metrics.height),
208 };
209 }
210
211 function terminalCellText(cell: GhosttyCell): string {
212 if (cell.wide === GHOSTTY_CELL_WIDE.spacerTail || cell.wide === GHOSTTY_CELL_WIDE.spacerHead) {
213 return "";
214 }
215 return cell.text || " ";
216 }
217
218 function terminalRowText(row: GhosttySnapshot["rowData"][number], trimRight: boolean): string {
219 const text = row.cells.map(terminalCellText).join("");
220 return trimRight ? text.trimEnd() : text;
221 }
222
223 function terminalColumnOffset(row: GhosttySnapshot["rowData"][number], column: number): number {
224 let offset = 0;
225 for (let cellIndex = 0; cellIndex < column; cellIndex += 1) {
226 const cell = row.cells[cellIndex];
227 offset += cell ? terminalCellText(cell).length : 1;
228 }
229 return offset;
230 }
231
232 export interface TerminalLinkWithRange {
233 readonly text: string;
234 readonly range: GhosttyCellRange;
235 }
236
237 function isSameTerminalLink(
238 left: TerminalLinkWithRange,
239 right: TerminalLinkWithRange | null,
240 ): boolean {
241 return (
242 right?.text === left.text &&
243 right.range.start.x === left.range.start.x &&
244 right.range.start.y === left.range.start.y &&
245 right.range.end.x === left.range.end.x &&
246 right.range.end.y === left.range.end.y
247 );
248 }
249
250 function terminalColumnAtOffset(row: GhosttySnapshot["rowData"][number], offset: number): number {
251 for (let column = 0; column < row.cells.length; column += 1) {
252 const nextOffset = terminalColumnOffset(row, column + 1);
253 if (offset < nextOffset) return column;
254 }
255 return Math.max(0, row.cells.length - 1);
256 }
257
258 export function terminalLinkAtPositionWithRange(
259 rows: GhosttySnapshot["rowData"],
260 rowIndex: number,
261 column: number,
262 ): TerminalLinkWithRange | null {
263 const wrappedLine = collectWrappedTerminalLinkLine(rowIndex + 1, (index) => {
264 const row = rows[index];
265 if (!row) return null;
266 return {
267 isWrapped: row.isWrapContinuation,
268 translateToString: (trimRight = false) => terminalRowText(row, trimRight),
269 };
270 });
271 if (!wrappedLine) return null;
272 // A wrapped line starting above the viewport would produce a truncated, incorrect link.
273 const firstSegment = wrappedLine.segments[0];
274 if (firstSegment && rows[firstSegment.bufferLineNumber - 1]?.isWrapContinuation) {
275 return null;
276 }
277 const segment = wrappedLine.segments.find((value) => value.bufferLineNumber === rowIndex + 1);
278 const row = rows[rowIndex];
279 if (!segment || !row) return null;
280 const lastSegment = wrappedLine.segments.at(-1);
281 const lastRow = lastSegment ? rows[lastSegment.bufferLineNumber - 1] : undefined;
282 const continuesBelowViewport = lastRow !== undefined && lastRow.wrapsToNext;
283 const hitColumn = row.cells[column]?.wide === GHOSTTY_CELL_WIDE.spacerTail ? column - 1 : column;
284 const offset = segment.startIndex + terminalColumnOffset(row, hitColumn);
285 for (const match of extractTerminalLinks(wrappedLine.text)) {
286 if (offset >= match.start && offset < match.end) {
287 if (match.end === wrappedLine.text.length && continuesBelowViewport) return null;
288 const startSegment = wrappedLine.segments.find(
289 (value) => match.start >= value.startIndex && match.start < value.endIndex,
290 );
291 const endSegment = wrappedLine.segments.find(
292 (value) => match.end - 1 >= value.startIndex && match.end - 1 < value.endIndex,
293 );
294 const startRow = startSegment ? rows[startSegment.bufferLineNumber - 1] : undefined;
295 const endRow = endSegment ? rows[endSegment.bufferLineNumber - 1] : undefined;
296 if (!startSegment || !endSegment || !startRow || !endRow) return null;
297 const endColumn = terminalColumnAtOffset(endRow, match.end - 1 - endSegment.startIndex);
298 return {
299 text: match.text,
300 range: {
301 start: {
302 x: terminalColumnAtOffset(startRow, match.start - startSegment.startIndex),
303 y: startSegment.bufferLineNumber - 1,
304 },
305 end: {
306 x:
307 endRow.cells[endColumn + 1]?.wide === GHOSTTY_CELL_WIDE.spacerTail
308 ? endColumn + 1
309 : endColumn,
310 y: endSegment.bufferLineNumber - 1,
311 },
312 },
313 };
314 }
315 }
316 return null;
317 }
318
319 export function isTerminalCopyShortcut(
320 event: Pick<KeyboardEvent, "altKey" | "code" | "ctrlKey" | "key" | "metaKey" | "shiftKey">,
321 platform = navigator.platform,
322 ) {
323 const keys = resolveEventKeys(event);
324 if (keys.has("insert") && !isMacPlatform(platform)) {
325 return event.ctrlKey && !event.shiftKey && !event.metaKey;
326 }
327 if (!keys.has("c")) return false;
328 return isMacPlatform(platform) ? event.metaKey : event.ctrlKey;
329 }
330
331 /** Primes native and Electron menu copy from the focused textarea; canvas has no DOM selection. */
332 export function primeTerminalCopyInput(
333 input: Pick<HTMLTextAreaElement, "value" | "select">,
334 selection: string,
335 ): void {
336 input.value = selection;
337 if (selection.length === 0) return;
338 input.select();
339 }
340
341 export function clearPrimedTerminalCopyInput(
342 input: Pick<HTMLTextAreaElement, "value">,
343 primedSelection: string,
344 ): void {
345 // Only clear the parked copy; other text may be an active CJK composition.
346 if (primedSelection.length === 0 || input.value !== primedSelection) return;
347 input.value = "";
348 }
349
350 export function applyTerminalCopyEvent(
351 selection: string,
352 clipboardData: { setData: (type: string, data: string) => void } | null | undefined,
353 ): { preventDefault: boolean; claimWriteFallback: boolean } {
354 if (selection.length === 0 || !clipboardData) {
355 return { preventDefault: false, claimWriteFallback: false };
356 }
357 clipboardData.setData("text/plain", selection);
358 return { preventDefault: true, claimWriteFallback: true };
359 }
360
361 function isTerminalPasteShortcut(
362 event: Pick<KeyboardEvent, "altKey" | "code" | "ctrlKey" | "key" | "metaKey" | "shiftKey">,
363 platform = navigator.platform,
364 ) {
365 const keys = resolveEventKeys(event);
366 if (keys.has("insert") && !isMacPlatform(platform)) {
367 return event.shiftKey && !event.ctrlKey && !event.metaKey;
368 }
369 if (!keys.has("v")) return false;
370 return isMacPlatform(platform) ? event.metaKey : event.ctrlKey && event.shiftKey;
371 }
372
373 // X11/Wayland expects middle-click paste; macOS and Windows use it for autoscroll.
374 function isMiddleClickPastePlatform(): boolean {
375 return /linux|bsd/i.test(navigator.platform);
376 }
377
378 function isTerminalCompositionCommitInput(event: Pick<InputEvent, "inputType">): boolean {
379 return (
380 event.inputType === "" ||
381 event.inputType === "insertCompositionText" ||
382 event.inputType === "insertFromComposition"
383 );
384 }
385
386 export function isTerminalCompositionKey(
387 event: Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">,
388 composing: boolean,
389 ): boolean {
390 return event.isComposing || composing || event.key === "Process" || event.keyCode === 229;
391 }
392
393 function isTerminalAltGraphText(event: Pick<KeyboardEvent, "getModifierState" | "key">): boolean {
394 return event.getModifierState("AltGraph") && [...event.key].length === 1;
395 }
396
397 function shouldReportTerminalMouse(
398 tracking: boolean,
399 event: Pick<MouseEvent, "ctrlKey" | "metaKey" | "shiftKey">,
400 ): boolean {
401 return tracking && !event.shiftKey && !event.ctrlKey && !event.metaKey;
402 }
403
404 type TerminalMouseAction = "press" | "release" | "motion";
405 type TerminalMouseReport = ReturnType<GhosttyTerminalCore["encodeMouse"]>;
406
407 export function resolveTerminalMouseData(
408 action: TerminalMouseAction,
409 report: TerminalMouseReport,
410 previousMotionData: TerminalMouseReport | null,
411 ): { readonly send: boolean; readonly nextMotionData: TerminalMouseReport | null } {
412 const nextMotionData = action === "motion" ? report : null;
413 return {
414 send:
415 report.data.length > 0 &&
416 (action !== "motion" ||
417 report.data !== previousMotionData?.data ||
418 report.binary !== previousMotionData?.binary),
419 nextMotionData,
420 };
421 }
422
423 function resolveTerminalMouseTrackingState(
424 previousTracking: boolean,
425 tracking: boolean,
426 motionData: TerminalMouseReport | null,
427 ): { readonly tracking: boolean; readonly motionData: TerminalMouseReport | null } {
428 return {
429 tracking,
430 motionData: previousTracking === tracking ? motionData : null,
431 };
432 }
433
434 export function terminalWheelDeltaRows(
435 event: Pick<WheelEvent, "deltaY" | "deltaMode">,
436 cellHeight: number,
437 viewportRows: number,
438 remainder: number,
439 ): { readonly rows: number; readonly remainder: number } {
440 const pixels =
441 event.deltaMode === 1
442 ? event.deltaY * cellHeight
443 : event.deltaMode === 2
444 ? event.deltaY * viewportRows * cellHeight
445 : event.deltaY;
446 const total = remainder + pixels / cellHeight;
447 const rows = Math.trunc(total);
448 return { rows, remainder: total - rows };
449 }
450
451 // Ramp from 1 to 15 rows per autoscroll tick over the first 50px past the edge, as xterm.js does.
452 const SELECTION_AUTOSCROLL_RAMP_PX = 50;
453 const SELECTION_AUTOSCROLL_MAX_ROWS = 15;
454
455 export function terminalSelectionAutoscrollRows(
456 clientY: number,
457 top: number,
458 bottom: number,
459 ): number {
460 const distance = clientY < top ? clientY - top : clientY > bottom ? clientY - bottom : 0;
461 if (distance === 0) return 0;
462 const ramp = Math.max(-1, Math.min(1, distance / SELECTION_AUTOSCROLL_RAMP_PX));
463 return Math.sign(ramp) + Math.round(ramp * (SELECTION_AUTOSCROLL_MAX_ROWS - 1));
464 }
465
466 function terminalWheelArrowData(rows: number, applicationCursorKeys: boolean): string {
467 if (rows === 0) return "";
468 const sequence =
469 rows < 0
470 ? applicationCursorKeys
471 ? "\u001bOA"
472 : "\u001b[A"
473 : applicationCursorKeys
474 ? "\u001bOB"
475 : "\u001b[B";
476 return sequence.repeat(Math.abs(rows));
477 }
478
479 function ghosttyMouseButton(button: number): number | null {
480 switch (button) {
481 case 0:
482 return 1;
483 case 1:
484 return 3;
485 case 2:
486 return 2;
487 case 3:
488 return 4;
489 case 4:
490 return 5;
491 default:
492 return null;
493 }
494 }
495
496 export interface TerminalSelectionClickSequence {
497 readonly count: number;
498 readonly time: number;
499 readonly x: number;
500 readonly y: number;
501 }
502
503 const TERMINAL_LINK_DRAG_THRESHOLD_PX = 4;
504
505 export function advanceTerminalSelectionClickSequence(
506 previous: TerminalSelectionClickSequence | null,
507 event: Pick<PointerEvent, "clientX" | "clientY" | "timeStamp">,
508 ): TerminalSelectionClickSequence {
509 const repeats =
510 previous !== null &&
511 event.timeStamp - previous.time <= SELECTION_MULTI_CLICK_INTERVAL_MS &&
512 Math.hypot(event.clientX - previous.x, event.clientY - previous.y) <=
513 TERMINAL_LINK_DRAG_THRESHOLD_PX;
514 return {
515 count: repeats ? (previous.count >= 3 ? 1 : previous.count + 1) : 1,
516 time: event.timeStamp,
517 x: event.clientX,
518 y: event.clientY,
519 };
520 }
521
522 export interface GhosttySelectionPosition {
523 readonly start: { readonly x: number; readonly y: number };
524 readonly end: { readonly x: number; readonly y: number };
525 }
526
527 export interface GhosttyTerminalSurfaceOptions {
528 readonly theme: GhosttyTheme;
529 readonly font?: GhosttyTerminalFont;
530 /** Read after font and WASM loading. */
531 readonly visible?: boolean;
532 readonly onData: (data: string) => void;
533 /** Input bytes that are not UTF-8, one UTF-16 code unit per byte. */
534 readonly onBinary: (data: string) => void;
535 /** The terminal's own answers to queries from the PTY (DA, DSR, DECRQM), never typed input. */
536 readonly onReply: (data: string) => void;
537 readonly onResize: (cols: number, rows: number) => void;
538 readonly onSelectionChange: () => void;
539 readonly beforeKey: (event: KeyboardEvent) => boolean;
540 readonly onLinkActivate: (text: string, event: MouseEvent) => void;
541 readonly canActivateLink?: (text: string) => boolean;
542 readonly validateLink?: (text: string) => Promise<boolean>;
543 /** Reports hovered candidates once their rendered text is stable for 250 ms; null cancels. */
544 readonly onLinkHover?: (text: string | null) => void;
545 /** The host must prevent the default menu; native Paste cannot reach a canvas terminal. */
546 readonly onContextMenu?: (event: MouseEvent) => void;
547 }
548
549 export class GhosttyTerminalSurface {
550 readonly canvas: HTMLCanvasElement;
551 readonly input: HTMLTextAreaElement;
552 readonly scrollbar: HTMLDivElement;
553 /** The drawn grid: the shared PTY grid, clamped per axis to the measured one. */
554 cols = 1;
555 rows = 1;
556
557 private readonly mount: HTMLElement;
558 private measuredCols = 1;
559 private measuredRows = 1;
560 private sharedGrid: { readonly cols: number; readonly rows: number } | null = null;
561 private readonly context: CanvasRenderingContext2D;
562 private readonly core: GhosttyTerminalCore;
563 private readonly options: GhosttyTerminalSurfaceOptions;
564 private visible: boolean;
565 private hasSize = false;
566 private metrics: GhosttyCellMetrics;
567 private fontFamily: string;
568 private requestedFontFamily: string | undefined;
569 private fontSize: number;
570 private fontEpoch = 0;
571 private pendingFontEpoch: number | null = null;
572 private readonly stopObservingResize: () => void;
573 private readonly scrollbarThumb: HTMLDivElement;
574 private snapshot: GhosttySnapshot | null = null;
575 private frame = 0;
576 private synchronizedRenderTimer: number | null = null;
577 private cursorTimer: number | null = null;
578 private compositionInputToSuppress: string | null = null;
579 private compositionSuppressionTimer: number | null = null;
580 private cursorOn = true;
581 private renderedCursorY: number | null = null;
582 private forceFullRender = true;
583 private scrollbarDirty = true;
584 private scrollbarState: GhosttyScrollbar | null = null;
585 private scrollbarPointerId: number | null = null;
586 private scrollbarPointerOffset = 0;
587 private disposed = false;
588 private resizeNotifyTimer: number | null = null;
589 private originY = CONTENT_PADDING;
590 private mountHeight = 0;
591 private selectionEnd: { x: number; y: number } | null = null;
592 private selectionAnchorScreen: { x: number; y: number } | null = null;
593 private selectionMode: "cell" | "word" | "line" = "cell";
594 private selectionBase: {
595 start: { x: number; y: number };
596 end: { x: number; y: number };
597 } | null = null;
598 private selectionScrollTimer: number | null = null;
599 private selectionScrollDelta = 0;
600 private selectionPointer: { x: number; y: number } | null = null;
601 private mouseReportingPointerId: number | null = null;
602 private mouseReportingButton: number | null = null;
603 private linkActivationPointerId: number | null = null;
604 private linkActivationLink: TerminalLinkWithRange | null = null;
605 private linkActivationValidation: Promise<boolean> | undefined;
606 private linkActivationRequestId = 0;
607 private linkActivationOrigin: {
608 x: number;
609 y: number;
610 clickCount: number;
611 } | null = null;
612 private hoveredLink: TerminalLinkWithRange | null = null;
613 private hoverPointer: { x: number; y: number } | null = null;
614 private linkHoverCandidate: TerminalLinkWithRange | null = null;
615 private linkHoverTimer: number | null = null;
616 private linkRowStability: Array<{
617 row: GhosttySnapshot["rowData"][number];
618 changedAt: number;
619 }> = [];
620 private selectionClickSequence: TerminalSelectionClickSequence | null = null;
621 private selectionMoved = false;
622 private composing = false;
623 private focused = false;
624 private resizeNotified = false;
625 private canvasConfigured = false;
626 private canvasDevicePixelRatio = 0;
627 private pendingCanvasConfiguration: {
628 readonly width: number;
629 readonly height: number;
630 readonly ratio: number;
631 } | null = null;
632 private theme: GhosttyTheme;
633 // App capture can hide keydowns, so only encoded presses qualify for Kitty releases.
634 private readonly encodedKeyCodes = new Set<string>();
635 private pasteShortcutToken = 0;
636 // Chromium can deliver native paste after the clipboard read resolves.
637 // Suppress its duplicate only for the current shortcut gesture.
638 private pasteShortcutGesture: { code: string; readText: string } | null = null;
639 private copyShortcutToken = 0;
640 private clearSelectionAfterCopy = false;
641 private primedCopySelection = "";
642 private wheelRemainder = 0;
643 private touchScroll: {
644 pointerId: number;
645 startX: number;
646 startY: number;
647 lastY: number;
648 remainder: number;
649 moved: boolean;
650 } | null = null;
651 private lastMouseMotionData: TerminalMouseReport | null = null;
652 private mouseAnyEventTracking = false;
653 private dprMedia: MediaQueryList | null = null;
654 // Watch reduced motion changes to restart blink cycles that have no remaining timer.
655 private readonly reducedMotionMedia = window.matchMedia?.("(prefers-reduced-motion: reduce)");
656 private inputLeft = -1;
657 private inputTop = -1;
658
659 private constructor(
660 mount: HTMLElement,
661 canvas: HTMLCanvasElement,
662 input: HTMLTextAreaElement,
663 scrollbar: HTMLDivElement,
664 scrollbarThumb: HTMLDivElement,
665 context: CanvasRenderingContext2D,
666 core: GhosttyTerminalCore,
667 metrics: GhosttyCellMetrics,
668 fontFamily: string,
669 options: GhosttyTerminalSurfaceOptions,
670 ) {
671 this.mount = mount;
672 this.canvas = canvas;
673 this.input = input;
674 this.scrollbar = scrollbar;
675 this.scrollbarThumb = scrollbarThumb;
676 this.context = context;
677 this.core = core;
678 this.mouseAnyEventTracking = core.isMouseAnyEventTracking();
679 this.metrics = metrics;
680 this.options = options;
681 this.visible = options.visible ?? true;
682 this.theme = options.theme;
683 this.fontFamily = fontFamily;
684 this.requestedFontFamily = options.font?.family;
685 this.fontSize = terminalFontSize(options.font?.size);
686 this.installEvents();
687 // The input is mounted before the core loads, so focus can land before the listeners.
688 this.focused = document.activeElement === input;
689 this.watchDevicePixelRatio();
690 this.reducedMotionMedia?.addEventListener("change", this.onReducedMotionChange);
691 document.fonts.addEventListener("loadingdone", this.onFontsLoaded);
692 this.stopObservingResize = observeResize(mount, () => this.fit());
693 }
694
695 static async create(
696 mount: HTMLElement,
697 options: GhosttyTerminalSurfaceOptions,
698 ): Promise<GhosttyTerminalSurface> {
699 const canvas = document.createElement("canvas");
700 canvas.className = "block size-full cursor-text";
701 canvas.style.touchAction = "pan-x pinch-zoom";
702 canvas.setAttribute("aria-hidden", "true");
703
704 const input = document.createElement("textarea");
705 input.className = "t3-ghostty-input";
706 input.setAttribute("aria-label", m(msg("Terminal input")));
707 input.autocapitalize = "off";
708 input.autocomplete = "off";
709 input.spellcheck = false;
710 input.style.cssText =
711 "position:absolute;left:4px;top:4px;width:1px;height:1px;opacity:0;padding:0;border:0;resize:none;pointer-events:none;";
712
713 const scrollbar = document.createElement("div");
714 scrollbar.className =
715 "group absolute top-1 right-px bottom-1 z-1 w-[var(--app-scrollbar-width)] cursor-default touch-none";
716 scrollbar.setAttribute("role", "scrollbar");
717 scrollbar.setAttribute("aria-label", m(msg("Terminal scrollback")));
718 scrollbar.setAttribute("aria-orientation", "vertical");
719 scrollbar.tabIndex = 0;
720 scrollbar.hidden = true;
721 const scrollbarThumb = document.createElement("div");
722 scrollbarThumb.className =
723 "absolute inset-x-px top-0 rounded-[3px] bg-[var(--app-scrollbar-thumb)] transition-[background-color] duration-[120ms] ease-[ease-out] group-hover:bg-[var(--app-scrollbar-thumb-hover)] group-focus-visible:bg-[var(--app-scrollbar-thumb-hover)]";
724 scrollbar.append(scrollbarThumb);
725 mount.replaceChildren(canvas, input, scrollbar);
726
727 const context = canvas.getContext("2d", { alpha: false });
728 if (!context) throw new Error("Canvas 2D is unavailable");
729 context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
730 context.fillRect(0, 0, canvas.width, canvas.height);
731 const fontSize = terminalFontSize(options.font?.size);
732 try {
733 // Load bundled fonts before measuring; fallback metrics would size the wrong grid.
734 await ensureTerminalSymbolsFont();
735 } catch {}
736 const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
737 const metrics = measureGhosttyCell(context, fontSize, fontFamily);
738 const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
739 const core = await GhosttyTerminalCore.create(
740 grid.cols,
741 grid.rows,
742 metrics.width,
743 metrics.height,
744 options.theme,
745 options.onReply,
746 );
747 const surface = new GhosttyTerminalSurface(
748 mount,
749 canvas,
750 input,
751 scrollbar,
752 scrollbarThumb,
753 context,
754 core,
755 metrics,
756 fontFamily,
757 options,
758 );
759 surface.fit();
760 return surface;
761 }
762
763 setVisible(visible: boolean): void {
764 if (this.disposed || this.visible === visible) return;
765 this.visible = visible;
766 this.cursorOn = true;
767 this.forceFullRender = true;
768 this.scrollbarDirty = true;
769 if (!visible) {
770 this.linkActivationRequestId += 1;
771 this.clearHoveredLink();
772 this.linkRowStability = [];
773 this.cancelRender();
774 this.setSelectionAutoscroll(0);
775 return;
776 }
777 this.fit();
778 }
779
780 write(data: string): void {
781 if (this.disposed) return;
782 this.core.write(
783 data,
784 this.synchronizedRenderTimer === null
785 ? undefined
786 : () => this.cancelSynchronizedRenderTimer(),
787 );
788 this.synchronizeMouseTrackingState();
789 this.cursorOn = true;
790 this.scrollbarDirty = true;
791 this.requestRender();
792 }
793
794 resetAndWrite(data: string): void {
795 if (this.disposed) return;
796 this.cancelSynchronizedRenderTimer();
797 this.lastMouseMotionData = null;
798 this.core.resetAndWrite(data);
799 this.synchronizeMouseTrackingState();
800 this.cursorOn = true;
801 this.forceFullRender = true;
802 this.scrollbarDirty = true;
803 this.requestRender();
804 }
805
806 setTheme(theme: GhosttyTheme): void {
807 if (this.disposed) return;
808 this.theme = theme;
809 this.core.setTheme(theme);
810 this.forceFullRender = true;
811 this.requestRender();
812 }
813
814 refreshLinkActivation(): void {
815 if (this.disposed) return;
816 this.refreshHoveredLink();
817 }
818
819 /** Mount height, in CSS pixels, that shows exactly `rows` rows at the current font. */
820 heightForRows(rows: number): number {
821 return Math.ceil(rows * this.metrics.height + CONTENT_PADDING * 2);
822 }
823
824 async setFont(font: GhosttyTerminalFont): Promise<void> {
825 if (this.disposed) return;
826 const fontSize = terminalFontSize(font.size);
827 // Commit fields with loaded metrics; the epoch makes the newest overlapping call win.
828 const epoch = ++this.fontEpoch;
829 this.pendingFontEpoch = epoch;
830 const fontFamily = await loadTerminalFontFamily(font.family, fontSize);
831 if (this.disposed || epoch !== this.fontEpoch) return;
832 this.pendingFontEpoch = null;
833 this.fontFamily = fontFamily;
834 this.requestedFontFamily = font.family;
835 this.fontSize = fontSize;
836 this.applyFontMetrics();
837 }
838
839 private applyFontMetrics(): void {
840 this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
841 this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
842 this.inputLeft = -1;
843 this.inputTop = -1;
844 this.forceFullRender = true;
845 this.scrollbarDirty = true;
846 this.fit();
847 this.requestRender();
848 }
849
850 private readonly onReducedMotionChange = () => {
851 if (this.disposed) return;
852 // Restart from render; reduced motion left the steady cursor with no blink timer.
853 this.cursorOn = true;
854 this.requestRender();
855 };
856
857 private readonly onFontsLoaded = () => {
858 if (this.disposed) return;
859 // Explicit loads validate and apply the newest request; ignore their events for the old face.
860 if (this.pendingFontEpoch !== null) return;
861 const fontFamily = terminalFontFamily(this.requestedFontFamily);
862 if (fontFamily !== this.fontFamily) {
863 this.fontFamily = fontFamily;
864 this.applyFontMetrics();
865 return;
866 }
867 const metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
868 if (
869 metrics.width === this.metrics.width &&
870 metrics.height === this.metrics.height &&
871 metrics.baseline === this.metrics.baseline
872 ) {
873 return;
874 }
875 this.applyFontMetrics();
876 };
877
878 resendSize(): void {
879 this.resizeNotified = false;
880 this.fit();
881 }
882
883 fit(): boolean {
884 if (this.disposed || !this.visible) return false;
885 const width = this.mount.clientWidth;
886 const height = this.mount.clientHeight;
887 if (width <= 0 || height <= 0) {
888 this.hasSize = false;
889 this.forceFullRender = true;
890 this.cancelRender();
891 return false;
892 }
893 this.hasSize = true;
894 const ratio = window.devicePixelRatio || 1;
895 const pixelWidth = Math.max(1, Math.round(width * ratio));
896 const pixelHeight = Math.max(1, Math.round(height * ratio));
897 let shouldRender = false;
898 // First fit must install DPR even if backing size matches the canvas default.
899 if (
900 this.canvas.width !== pixelWidth ||
901 this.canvas.height !== pixelHeight ||
902 !this.canvasConfigured ||
903 this.canvasDevicePixelRatio !== ratio
904 ) {
905 // A backing-size change clears the canvas. Apply it with the gated paint
906 // so a DPR change cannot erase a frame while synchronized output is open.
907 this.pendingCanvasConfiguration = { width: pixelWidth, height: pixelHeight, ratio };
908 this.forceFullRender = true;
909 this.scrollbarDirty = true;
910 shouldRender = true;
911 } else {
912 // A resize can return to the painted size before its queued frame runs.
913 this.pendingCanvasConfiguration = null;
914 }
915 const grid = terminalGridSize(width, height, this.metrics, CONTENT_PADDING);
916 this.mountHeight = height;
917 // onResize is the only PTY resize channel, so the first successful fit must
918 // notify even when the measured grid equals the 1x1 construction sentinel.
919 if (
920 grid.cols !== this.measuredCols ||
921 grid.rows !== this.measuredRows ||
922 !this.resizeNotified
923 ) {
924 this.measuredCols = grid.cols;
925 this.measuredRows = grid.rows;
926 this.notifyResize();
927 }
928 if (this.applyGrid()) shouldRender = true;
929 // Repaint synchronously before paint so resize never stretches the old backing store.
930 if (shouldRender || this.forceFullRender) this.renderFrame();
931 return true;
932 }
933
934 /**
935 * Other clients can share this PTY, so the server owns its grid. Drawing that grid
936 * keeps wrapping and cursor positions in step with the PTY. Each axis is clamped to
937 * this surface's own fit: the server's grid lags a local resize, and read-only
938 * observers never constrain it.
939 */
940 setSharedGrid(grid: { readonly cols: number; readonly rows: number } | null): void {
941 if (this.disposed) return;
942 if (this.sharedGrid?.cols === grid?.cols && this.sharedGrid?.rows === grid?.rows) return;
943 this.sharedGrid = grid;
944 if (this.hasSize && this.applyGrid()) this.requestRender();
945 }
946
947 private applyGrid(): boolean {
948 const cols = Math.min(this.sharedGrid?.cols ?? this.measuredCols, this.measuredCols);
949 const rows = Math.min(this.sharedGrid?.rows ?? this.measuredRows, this.measuredRows);
950 if (cols === this.cols && rows === this.rows) return false;
951 this.cols = cols;
952 this.rows = rows;
953 this.core.resize(cols, rows, this.metrics.width, this.metrics.height);
954 this.forceFullRender = true;
955 this.scrollbarDirty = true;
956 return true;
957 }
958
959 /**
960 * The local grid reflows immediately, but the PTY only hears about settled
961 * dimensions: notifying on every drag step makes the shell reprint its
962 * prompt mid-drag, which reads as jitter.
963 */
964 private notifyResize(): void {
965 this.resizeNotified = true;
966 if (this.resizeNotifyTimer !== null) window.clearTimeout(this.resizeNotifyTimer);
967 this.resizeNotifyTimer = window.setTimeout(() => {
968 this.resizeNotifyTimer = null;
969 if (!this.disposed) this.options.onResize(this.measuredCols, this.measuredRows);
970 }, 150);
971 }
972
973 // Flush on release so immediate typing reaches a shell with the settled width.
974 private readonly onWindowPointerRelease = () => {
975 if (this.disposed || this.resizeNotifyTimer === null) return;
976 this.fit();
977 if (this.resizeNotifyTimer === null) return;
978 window.clearTimeout(this.resizeNotifyTimer);
979 this.resizeNotifyTimer = null;
980 this.options.onResize(this.measuredCols, this.measuredRows);
981 };
982
983 focus(): void {
984 if (this.disposed || !this.visible) return;
985 this.input.focus({ preventScroll: true });
986 }
987
988 /** Claims before reading; later shortcut or native pastes supersede the pending read. */
989 async pasteFromClipboard(
990 readText: () => Promise<string>,
991 isCurrent: () => boolean = () => true,
992 ): Promise<void> {
993 const token = ++this.pasteShortcutToken;
994 const text = await readText();
995 if (this.disposed || this.pasteShortcutToken !== token || !isCurrent()) return;
996 this.pasteShortcutToken += 1;
997 if (text.length === 0) return;
998 const encoded = this.core.encodePaste(text);
999 if (encoded.length > 0) this.options.onData(encoded);
1000 }
1001
1002 // The terminal selection is the only browser-readable PRIMARY-like buffer.
1003 private pasteTerminalSelection(): void {
1004 const selection = this.getSelection();
1005 if (selection.length === 0) return;
1006 void this.pasteFromClipboard(() => Promise.resolve(selection));
1007 }
1008
1009 hasSelection(): boolean {
1010 return this.core.selectionText().length > 0;
1011 }
1012
1013 getSelection(): string {
1014 return this.core.selectionText();
1015 }
1016
1017 /** An upper bound on the selection's size, read without formatting its text. */
1018 getSelectionCellCount(): number {
1019 const range = this.core.selectionRange();
1020 return range ? (Math.abs(range.end.y - range.start.y) + 1) * this.cols : 0;
1021 }
1022
1023 selectAll(): void {
1024 this.linkActivationRequestId += 1;
1025 this.clearPrimedCopy();
1026 const range = this.core.selectAll();
1027 this.selectionAnchorScreen = range?.start ?? null;
1028 this.selectionEnd = range ? this.core.screenPointToViewport(range.end.x, range.end.y) : null;
1029 this.selectionMode = "cell";
1030 this.selectionBase = null;
1031 this.setSelectionAutoscroll(0);
1032 this.options.onSelectionChange();
1033 this.forceFullRender = true;
1034 this.requestRender();
1035 }
1036
1037 getSelectionPosition(): GhosttySelectionPosition | null {
1038 // Ask Ghostty rather than the gesture's coordinates, which go stale once
1039 // output scrolls the selected rows (alternate screen, scrollback pruning).
1040 const range = this.hasSelection() ? this.core.selectionRange() : null;
1041 if (!range) return null;
1042 const { start, end } = range;
1043 const before = start.y < end.y || (start.y === end.y && start.x <= end.x);
1044 return before ? { start, end } : { start: end, end: start };
1045 }
1046
1047 clearSelection({ source = "user" }: { source?: "user" | "output" } = {}): void {
1048 if (source === "user") this.linkActivationRequestId += 1;
1049 this.clearPrimedCopy();
1050 this.core.clearSelection();
1051 this.selectionEnd = null;
1052 this.selectionAnchorScreen = null;
1053 this.selectionMode = "cell";
1054 this.selectionBase = null;
1055 this.setSelectionAutoscroll(0);
1056 this.options.onSelectionChange();
1057 // Selection highlights span rows Ghostty may not mark dirty for this change.
1058 this.forceFullRender = true;
1059 this.requestRender();
1060 }
1061
1062 scrollToBottom(): void {
1063 this.core.scrollToBottom();
1064 this.forceFullRender = true;
1065 this.scrollbarDirty = true;
1066 this.requestRender();
1067 }
1068
1069 isAtBottom(): boolean {
1070 return this.core.isViewportActive();
1071 }
1072
1073 dispose(): void {
1074 if (this.disposed) return;
1075 this.disposed = true;
1076 this.clearHoveredLink();
1077 this.stopObservingResize();
1078 document.fonts.removeEventListener("loadingdone", this.onFontsLoaded);
1079 this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
1080 this.dprMedia = null;
1081 this.reducedMotionMedia?.removeEventListener("change", this.onReducedMotionChange);
1082 if (this.selectionScrollTimer !== null) window.clearInterval(this.selectionScrollTimer);
1083 if (this.resizeNotifyTimer !== null) {
1084 window.clearTimeout(this.resizeNotifyTimer);
1085 this.resizeNotifyTimer = null;
1086 this.options.onResize(this.measuredCols, this.measuredRows);
1087 }
1088 this.cancelRender();
1089 if (this.compositionSuppressionTimer !== null) {
1090 window.clearTimeout(this.compositionSuppressionTimer);
1091 }
1092 this.removeEvents();
1093 this.core.dispose();
1094 if (
1095 this.canvas.parentElement === this.mount ||
1096 this.input.parentElement === this.mount ||
1097 this.scrollbar.parentElement === this.mount
1098 ) {
1099 this.canvas.remove();
1100 this.input.remove();
1101 this.scrollbar.remove();
1102 }
1103 }
1104
1105 private readonly onKeyDown = (event: KeyboardEvent) => {
1106 // A consumed repeat still owes the original encoded press a release.
1107 if (!event.repeat) this.encodedKeyCodes.delete(event.code);
1108 if (isTerminalAltGraphText(event) || !this.options.beforeKey(event)) return;
1109 // IME candidates belong to the textarea, even if the key also resembles
1110 // a local shortcut. Safari signals the initial composition with code 229.
1111 if (isTerminalCompositionKey(event, this.composing)) {
1112 return;
1113 }
1114 const mac = isMacPlatform(navigator.platform);
1115 const primaryModifier = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
1116 const selectAllShortcut =
1117 resolveEventKeys(event).has("a") &&
1118 primaryModifier &&
1119 !event.altKey &&
1120 (mac ? !event.shiftKey : event.shiftKey);
1121 if (selectAllShortcut) {
1122 event.preventDefault();
1123 event.stopPropagation();
1124 this.selectAll();
1125 return;
1126 }
1127 const pageHistory =
1128 event.shiftKey &&
1129 !event.altKey &&
1130 !event.ctrlKey &&
1131 !event.metaKey &&
1132 (event.key === "PageUp" || event.key === "PageDown");
1133 const jumpHistory =
1134 event.shiftKey &&
1135 !event.altKey &&
1136 primaryModifier &&
1137 (event.key === "Home" || event.key === "End");
1138 if ((pageHistory || jumpHistory) && !this.core.isAlternateScreen()) {
1139 const state = this.readScrollbarState();
1140 if (state !== null) {
1141 event.preventDefault();
1142 event.stopPropagation();
1143 const delta =
1144 event.key === "Home"
1145 ? -state.offset
1146 : event.key === "End"
1147 ? state.total - state.len - state.offset
1148 : Math.max(1, state.len) * (event.key === "PageUp" ? -1 : 1);
1149 this.scrollViewport(delta);
1150 return;
1151 }
1152 }
1153 if (isTerminalCopyShortcut(event) && this.hasSelection()) {
1154 // WebKit can omit copy without DOM selection. Ctrl+Shift+C and Ctrl+Insert need synthesized copy events.
1155 const selection = this.getSelection();
1156 this.primeCopy(selection);
1157 if (event.shiftKey || event.key.toLowerCase() === "insert") {
1158 event.preventDefault();
1159 document.execCommand("copy");
1160 } else {
1161 // Clear after plain non-mac Ctrl+C so the next press sends SIGINT.
1162 this.clearSelectionAfterCopy = !event.shiftKey && !isMacPlatform(navigator.platform);
1163 const clipboard = navigator.clipboard;
1164 if (typeof clipboard?.writeText === "function") {
1165 // Defer fallback writes until native copy can claim the token; browsers may omit copy events.
1166 const token = ++this.copyShortcutToken;
1167 void Promise.resolve().then(() => {
1168 if (this.disposed || this.copyShortcutToken !== token) return;
1169 void clipboard.writeText(selection).then(
1170 () => {
1171 if (this.disposed || this.copyShortcutToken !== token) return;
1172 if (this.clearSelectionAfterCopy) {
1173 this.clearSelectionAfterCopy = false;
1174 this.clearSelection();
1175 }
1176 },
1177 () => {
1178 if (this.copyShortcutToken === token) {
1179 this.clearSelectionAfterCopy = false;
1180 }
1181 },
1182 );
1183 });
1184 }
1185 }
1186 return;
1187 }
1188 if (isTerminalPasteShortcut(event)) {
1189 const gesture = { code: event.code, readText: "" };
1190 this.pasteShortcutGesture = gesture;
1191 const clipboard = navigator.clipboard;
1192 if (typeof clipboard?.readText === "function") {
1193 // Keep native paste available if the read is denied. The token drops
1194 // a late read; the gesture drops a native duplicate when the read wins.
1195 const token = ++this.pasteShortcutToken;
1196 void clipboard.readText().then(
1197 (text) => {
1198 if (this.disposed || this.pasteShortcutToken !== token) return;
1199 this.pasteShortcutToken += 1;
1200 if (text.length === 0) return;
1201 if (this.pasteShortcutGesture === gesture) gesture.readText = text;
1202 this.options.onData(this.core.encodePaste(text));
1203 },
1204 () => {},
1205 );
1206 }
1207 return;
1208 }
1209 this.clearPrimedCopy();
1210 const data = this.core.encodeKey(event);
1211 if (data.length === 0) return;
1212 this.encodedKeyCodes.add(event.code);
1213 event.preventDefault();
1214 event.stopPropagation();
1215 this.options.onData(data);
1216 };
1217
1218 private readonly onKeyUp = (event: KeyboardEvent) => {
1219 // macOS can omit V keyup while Command is held.
1220 if (
1221 event.code === this.pasteShortcutGesture?.code ||
1222 event.key === "Meta" ||
1223 event.key === "Control" ||
1224 event.key === "Shift"
1225 ) {
1226 this.pasteShortcutGesture = null;
1227 }
1228 if (!this.encodedKeyCodes.delete(event.code)) return;
1229 if (isTerminalCompositionKey(event, this.composing)) {
1230 return;
1231 }
1232 // Ghostty emits release codes only for Kitty report-event-types sessions.
1233 const data = this.core.encodeKey(event, "release");
1234 if (data.length === 0) return;
1235 event.preventDefault();
1236 event.stopPropagation();
1237 this.options.onData(data);
1238 };
1239
1240 // A release elsewhere must not leave a press for a later app shortcut to inherit.
1241 private readonly onWindowKeyUp = (event: KeyboardEvent) => {
1242 if (event.composedPath().includes(this.input)) return;
1243 this.encodedKeyCodes.delete(event.code);
1244 };
1245
1246 // A fresh press proves a release was missed; repeats can span a focus round trip.
1247 private readonly onWindowKeyDown = (event: KeyboardEvent) => {
1248 if (!event.repeat) this.encodedKeyCodes.delete(event.code);
1249 };
1250
1251 private readonly onFocus = () => {
1252 this.setFocused(true);
1253 this.cursorOn = true;
1254 this.requestRender();
1255 };
1256
1257 private readonly onBlur = () => {
1258 this.setFocused(false);
1259 this.pasteShortcutGesture = null;
1260 this.refreshHoveredLink();
1261 this.cursorOn = true;
1262 this.requestRender();
1263 };
1264
1265 // DOM focus events can repeat without a change; report only real transitions.
1266 private setFocused(focused: boolean): void {
1267 if (this.focused === focused) return;
1268 this.focused = focused;
1269 const data = this.core.encodeFocus(focused);
1270 if (data.length > 0) this.options.onData(data);
1271 }
1272
1273 private readonly onDevicePixelRatioChange = () => {
1274 this.watchDevicePixelRatio();
1275 this.fit();
1276 };
1277
1278 private watchDevicePixelRatio(): void {
1279 this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
1280 // Resolution queries track only their initial ratio; re-arm after every change.
1281 this.dprMedia = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
1282 this.dprMedia.addEventListener("change", this.onDevicePixelRatioChange);
1283 }
1284
1285 private primeCopy(selection: string): void {
1286 this.primedCopySelection = selection;
1287 primeTerminalCopyInput(this.input, selection);
1288 }
1289
1290 private clearPrimedCopy(): void {
1291 clearPrimedTerminalCopyInput(this.input, this.primedCopySelection);
1292 this.primedCopySelection = "";
1293 }
1294
1295 private readonly onCopyEvent = (event: ClipboardEvent) => {
1296 const selection = this.hasSelection() ? this.getSelection() : this.input.value;
1297 // Menu Copy skips keydown; prime the textarea even without clipboardData for the native action.
1298 this.primeCopy(selection);
1299 const result = applyTerminalCopyEvent(selection, event.clipboardData);
1300 if (result.preventDefault) event.preventDefault();
1301 if (result.claimWriteFallback) {
1302 // Native copy wrote successfully; invalidate writeText so it cannot overwrite a later copy.
1303 this.copyShortcutToken += 1;
1304 if (this.clearSelectionAfterCopy) {
1305 this.clearSelectionAfterCopy = false;
1306 this.clearSelection();
1307 }
1308 }
1309 };
1310
1311 private readonly onPaste = (event: ClipboardEvent) => {
1312 // Default textarea insertion would bypass bracketed-paste encoding through onInput.
1313 event.preventDefault();
1314 const data = event.clipboardData?.getData("text/plain") ?? "";
1315 if (data.length === 0) return;
1316 if (data === this.pasteShortcutGesture?.readText) {
1317 // The shortcut's clipboard read already sent this paste.
1318 this.pasteShortcutGesture = null;
1319 return;
1320 }
1321 // The native paste won the race with actual text; a pending clipboard read
1322 // must not double. An empty native paste leaves the read as the only path.
1323 this.pasteShortcutToken += 1;
1324 this.options.onData(this.core.encodePaste(data));
1325 };
1326
1327 private readonly onCompositionStart = () => {
1328 this.clearPrimedCopy();
1329 this.clearCompositionInputSuppression();
1330 this.composing = true;
1331 };
1332
1333 private readonly onCompositionEnd = (event: CompositionEvent) => {
1334 this.composing = false;
1335 const data = this.input.value || event.data;
1336 if (data.length > 0) this.options.onData(data);
1337 this.input.value = "";
1338 this.compositionInputToSuppress = data;
1339 this.compositionSuppressionTimer = window.setTimeout(() => {
1340 this.compositionInputToSuppress = null;
1341 this.compositionSuppressionTimer = null;
1342 }, 100);
1343 };
1344
1345 private readonly onInput = (event: Event) => {
1346 const inputEvent = event as InputEvent;
1347 if (this.composing || inputEvent.isComposing) return;
1348 const data = this.input.value || inputEvent.data || "";
1349 if (data === this.compositionInputToSuppress && isTerminalCompositionCommitInput(inputEvent)) {
1350 this.clearCompositionInputSuppression();
1351 this.input.value = "";
1352 return;
1353 }
1354 this.clearCompositionInputSuppression();
1355 if (data.length > 0) this.options.onData(data);
1356 this.input.value = "";
1357 };
1358
1359 private clearCompositionInputSuppression(): void {
1360 if (this.compositionSuppressionTimer !== null) {
1361 window.clearTimeout(this.compositionSuppressionTimer);
1362 this.compositionSuppressionTimer = null;
1363 }
1364 this.compositionInputToSuppress = null;
1365 }
1366
1367 private readonly onPointerDown = (event: PointerEvent) => {
1368 this.linkActivationRequestId += 1;
1369 if (event.pointerType === "touch") {
1370 event.preventDefault();
1371 if (!event.isPrimary || this.touchScroll !== null) return;
1372 this.touchScroll = {
1373 pointerId: event.pointerId,
1374 startX: event.clientX,
1375 startY: event.clientY,
1376 lastY: event.clientY,
1377 remainder: 0,
1378 moved: false,
1379 };
1380 this.clearHoveredLink();
1381 this.canvas.setPointerCapture(event.pointerId);
1382 return;
1383 }
1384 this.focus();
1385 if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
1386 const button = ghosttyMouseButton(event.button);
1387 if (button === null) return;
1388 event.preventDefault();
1389 event.stopPropagation();
1390 this.clearHoveredLink("default");
1391 this.mouseReportingPointerId = event.pointerId;
1392 this.mouseReportingButton = button;
1393 this.sendMouse("press", button, event);
1394 this.canvas.setPointerCapture(event.pointerId);
1395 return;
1396 }
1397 if (event.button === 1 && isMiddleClickPastePlatform()) {
1398 // Keep pointerdown uncancelled so compatibility mousedown activates the split pane.
1399 if (window.desktopBridge?.getPrimaryPasteEnabled?.() !== false) {
1400 this.pasteTerminalSelection();
1401 }
1402 return;
1403 }
1404 if (event.button !== 0) return;
1405 const clickCount = this.recordSelectionClick(event);
1406 const link = this.linkAt(event.clientX, event.clientY, true);
1407 if (link && !event.shiftKey && clickCount === 1) {
1408 event.preventDefault();
1409 event.stopPropagation();
1410 this.linkActivationPointerId = event.pointerId;
1411 this.linkActivationLink = link;
1412 this.linkActivationValidation = this.validateLink(link.text);
1413 this.linkActivationOrigin = {
1414 x: event.clientX,
1415 y: event.clientY,
1416 clickCount,
1417 };
1418 this.canvas.setPointerCapture(event.pointerId);
1419 return;
1420 }
1421 this.clearHoveredLink();
1422 this.beginSelection(event, clickCount);
1423 this.canvas.setPointerCapture(event.pointerId);
1424 };
1425
1426 private recordSelectionClick(
1427 event: Pick<PointerEvent, "clientX" | "clientY" | "timeStamp">,
1428 ): number {
1429 this.selectionClickSequence = advanceTerminalSelectionClickSequence(
1430 this.selectionClickSequence,
1431 event,
1432 );
1433 return this.selectionClickSequence.count;
1434 }
1435
1436 private beginSelection(event: { clientX: number; clientY: number }, clickCount: number): void {
1437 const cell = this.cellAt(event.clientX, event.clientY);
1438 this.selectionMoved = false;
1439 this.selectionMode = clickCount >= 3 ? "line" : clickCount === 2 ? "word" : "cell";
1440 const range =
1441 this.selectionMode === "line"
1442 ? this.core.selectLine(cell.x, cell.y)
1443 : this.selectionMode === "word"
1444 ? this.core.selectWord(cell.x, cell.y)
1445 : null;
1446 if (range) {
1447 this.selectionBase = range.screen;
1448 this.selectionEnd = range.viewport.end;
1449 this.selectionAnchorScreen = range.screen.start;
1450 this.options.onSelectionChange();
1451 } else {
1452 this.selectionMode = "cell";
1453 this.selectionBase = null;
1454 this.selectionEnd = cell;
1455 const screen = this.core.viewportPointToScreen(cell.x, cell.y);
1456 this.selectionAnchorScreen = screen;
1457 if (screen) {
1458 this.core.setSelection({ ...screen, tag: 2 }, { ...screen, tag: 2 });
1459 } else {
1460 this.core.setSelection(cell, cell);
1461 }
1462 }
1463 this.forceFullRender = true;
1464 this.requestRender();
1465 }
1466
1467 private readonly onPointerMove = (event: PointerEvent) => {
1468 if (event.pointerType === "touch") {
1469 const touch = this.touchScroll;
1470 if (touch?.pointerId !== event.pointerId) return;
1471 event.preventDefault();
1472 touch.moved ||=
1473 Math.hypot(event.clientX - touch.startX, event.clientY - touch.startY) >
1474 TERMINAL_LINK_DRAG_THRESHOLD_PX;
1475 if (!touch.moved) return;
1476 const delta = terminalWheelDeltaRows(
1477 { deltaY: touch.lastY - event.clientY, deltaMode: 0 },
1478 this.metrics.height,
1479 this.rows,
1480 touch.remainder,
1481 );
1482 touch.lastY = event.clientY;
1483 touch.remainder = delta.remainder;
1484 this.scrollRows(delta.rows, event);
1485 return;
1486 }
1487 if (this.linkActivationPointerId === event.pointerId) {
1488 const origin = this.linkActivationOrigin;
1489 if (
1490 origin === null ||
1491 Math.hypot(event.clientX - origin.x, event.clientY - origin.y) <=
1492 TERMINAL_LINK_DRAG_THRESHOLD_PX
1493 ) {
1494 return;
1495 }
1496 this.linkActivationPointerId = null;
1497 this.linkActivationLink = null;
1498 this.linkActivationValidation = undefined;
1499 this.linkActivationOrigin = null;
1500 this.clearHoveredLink();
1501 this.beginSelection(
1502 {
1503 clientX: origin.x,
1504 clientY: origin.y,
1505 },
1506 origin.clickCount,
1507 );
1508 }
1509 // Only DEC 1003 reports hover motion without a captured pressed button.
1510 const anyEventTracking = this.synchronizeMouseTrackingState();
1511 if (
1512 this.mouseReportingPointerId === event.pointerId ||
1513 shouldReportTerminalMouse(anyEventTracking, event)
1514 ) {
1515 event.preventDefault();
1516 this.hoverPointer = { x: event.clientX, y: event.clientY };
1517 this.setHoveredLink(null);
1518 this.canvas.style.cursor = "default";
1519 this.sendMouse("motion", this.buttonFromButtons(event.buttons), event);
1520 return;
1521 }
1522 this.lastMouseMotionData = null;
1523 if (!this.selectionAnchorScreen || !this.canvas.hasPointerCapture(event.pointerId)) {
1524 this.updateHoverCursor(event);
1525 return;
1526 }
1527 this.clearHoveredLink();
1528 this.selectionPointer = { x: event.clientX, y: event.clientY };
1529 const bounds = this.canvas.getBoundingClientRect();
1530 const top = Math.max(bounds.top, 0) + CONTENT_PADDING;
1531 const bottom = Math.min(bounds.bottom, window.innerHeight) - CONTENT_PADDING;
1532 this.setSelectionAutoscroll(terminalSelectionAutoscrollRows(event.clientY, top, bottom));
1533 const cell = this.cellAt(event.clientX, event.clientY);
1534 if (cell.x === this.selectionEnd?.x && cell.y === this.selectionEnd.y) return;
1535 this.extendSelectionTo(event.clientX, event.clientY);
1536 };
1537
1538 private extendSelectionTo(clientX: number, clientY: number): void {
1539 if (this.selectionAnchorScreen === null) return;
1540 // Ghostty moves its selection with output; keep the drag on those rows too.
1541 const anchorScreen = this.core.selectionRange()?.start;
1542 if (!anchorScreen) return;
1543 const rowDelta = anchorScreen.y - this.selectionAnchorScreen.y;
1544 if (this.selectionBase && rowDelta !== 0) {
1545 const { start, end } = this.selectionBase;
1546 this.selectionBase = {
1547 start: { x: start.x, y: start.y + rowDelta },
1548 end: { x: end.x, y: end.y + rowDelta },
1549 };
1550 }
1551 const cell = this.cellAt(clientX, clientY);
1552 this.selectionMoved = true;
1553 this.selectionEnd = cell;
1554 const range =
1555 this.selectionMode === "line"
1556 ? this.core.selectLine(cell.x, cell.y)
1557 : this.selectionMode === "word"
1558 ? this.core.selectWord(cell.x, cell.y)
1559 : null;
1560 const cellScreen = this.core.viewportPointToScreen(cell.x, cell.y);
1561 if (cellScreen === null) return;
1562 const base = this.selectionBase;
1563 const beforeBase =
1564 base !== null &&
1565 (cellScreen.y < base.start.y ||
1566 (cellScreen.y === base.start.y && cellScreen.x < base.start.x));
1567 const anchor = base === null ? anchorScreen : beforeBase ? base.end : base.start;
1568 const end = range === null ? cellScreen : beforeBase ? range.screen.start : range.screen.end;
1569 this.selectionAnchorScreen = anchor;
1570 this.core.setSelection({ ...anchor, tag: 2 }, { ...end, tag: 2 });
1571 this.options.onSelectionChange();
1572 this.forceFullRender = true;
1573 this.requestRender();
1574 }
1575
1576 private setSelectionAutoscroll(delta: number): void {
1577 this.selectionScrollDelta = delta;
1578 if (delta === 0) {
1579 if (this.selectionScrollTimer !== null) {
1580 window.clearInterval(this.selectionScrollTimer);
1581 this.selectionScrollTimer = null;
1582 }
1583 return;
1584 }
1585 if (this.selectionScrollTimer !== null) return;
1586 this.selectionScrollTimer = window.setInterval(() => {
1587 if (this.disposed || this.selectionScrollDelta === 0) return;
1588 this.scrollViewport(this.selectionScrollDelta);
1589 const pointer = this.selectionPointer;
1590 if (pointer) this.extendSelectionTo(pointer.x, pointer.y);
1591 }, 80);
1592 }
1593
1594 private updateHoverCursor(event: PointerEvent): void {
1595 this.hoverPointer = { x: event.clientX, y: event.clientY };
1596 this.refreshHoveredLink();
1597 }
1598
1599 private readonly onPointerLeave = () => {
1600 this.lastMouseMotionData = null;
1601 this.clearHoveredLink();
1602 };
1603
1604 private clearHoveredLink(cursor = ""): void {
1605 this.hoverPointer = null;
1606 this.updateLinkHover(null);
1607 this.setHoveredLink(null);
1608 this.canvas.style.cursor = cursor;
1609 }
1610
1611 private refreshHoveredLink(): void {
1612 const pointer = this.hoverPointer;
1613 const link = pointer ? this.findLinkAt(pointer.x, pointer.y) : null;
1614 this.updateLinkHover(link);
1615 this.setHoveredLink(link && this.options.canActivateLink?.(link.text) !== false ? link : null);
1616 }
1617
1618 private updateLinkHover(link: TerminalLinkWithRange | null): void {
1619 if (!this.options.onLinkHover) return;
1620 if (link ? isSameTerminalLink(link, this.linkHoverCandidate) : this.linkHoverCandidate === null)
1621 return;
1622 this.linkHoverCandidate = link;
1623 if (this.linkHoverTimer !== null) {
1624 window.clearTimeout(this.linkHoverTimer);
1625 this.linkHoverTimer = null;
1626 }
1627 this.options.onLinkHover(null);
1628 if (link !== null) {
1629 const now = performance.now();
1630 let changedAt = 0;
1631 for (let y = link.range.start.y; y <= link.range.end.y; y++) {
1632 changedAt = Math.max(changedAt, this.linkRowStability[y]?.changedAt ?? now);
1633 }
1634 const delay = Math.max(0, TERMINAL_LINK_HOVER_DELAY_MS - (now - changedAt));
1635 if (delay === 0) {
1636 this.options.onLinkHover(link.text);
1637 return;
1638 }
1639 this.linkHoverTimer = window.setTimeout(() => {
1640 this.linkHoverTimer = null;
1641 this.options.onLinkHover?.(link.text);
1642 }, delay);
1643 }
1644 }
1645
1646 private updateLinkRowStability(reset: boolean): void {
1647 if (!this.options.onLinkHover || !this.snapshot) return;
1648 if (reset) {
1649 this.updateLinkHover(null);
1650 this.linkRowStability = [];
1651 }
1652 const now = performance.now();
1653 this.snapshot.rowData.forEach((row, y) => {
1654 const previous = this.linkRowStability[y]?.row;
1655 if (
1656 !previous ||
1657 previous.text !== row.text ||
1658 previous.cells.length !== row.cells.length ||
1659 previous.isWrapContinuation !== row.isWrapContinuation ||
1660 previous.wrapsToNext !== row.wrapsToNext
1661 )
1662 this.linkRowStability[y] = { row, changedAt: now };
1663 });
1664 this.linkRowStability.length = this.snapshot.rows;
1665 }
1666
1667 private setHoveredLink(link: TerminalLinkWithRange | null): void {
1668 const previous = this.hoveredLink;
1669 const unchanged =
1670 previous?.text === link?.text &&
1671 previous?.range.start.x === link?.range.start.x &&
1672 previous?.range.start.y === link?.range.start.y &&
1673 previous?.range.end.x === link?.range.end.x &&
1674 previous?.range.end.y === link?.range.end.y;
1675 this.canvas.style.cursor = link ? "pointer" : "";
1676 if (unchanged) return;
1677 this.hoveredLink = link;
1678 this.forceFullRender = true;
1679 this.requestRender();
1680 }
1681
1682 private readonly onPointerUp = (event: PointerEvent) => {
1683 if (event.pointerType === "touch") {
1684 const touch = this.touchScroll;
1685 if (touch?.pointerId !== event.pointerId) return;
1686 this.touchScroll = null;
1687 event.preventDefault();
1688 if (this.canvas.hasPointerCapture(event.pointerId)) {
1689 this.canvas.releasePointerCapture(event.pointerId);
1690 }
1691 if (event.type === "pointercancel" || touch.moved) return;
1692 this.focus();
1693 if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
1694 this.sendMouse("press", ghosttyMouseButton(0), event);
1695 this.sendMouse("release", ghosttyMouseButton(0), event);
1696 } else {
1697 const link = this.linkAt(event.clientX, event.clientY, true);
1698 if (link) this.activateLink(link, event);
1699 else this.clearSelection();
1700 }
1701 return;
1702 }
1703 this.setSelectionAutoscroll(0);
1704 if (this.linkActivationPointerId === event.pointerId) {
1705 event.preventDefault();
1706 event.stopPropagation();
1707 const link = this.linkActivationLink;
1708 const validation = this.linkActivationValidation;
1709 this.linkActivationPointerId = null;
1710 this.linkActivationLink = null;
1711 this.linkActivationValidation = undefined;
1712 this.linkActivationOrigin = null;
1713 if (this.canvas.hasPointerCapture(event.pointerId)) {
1714 this.canvas.releasePointerCapture(event.pointerId);
1715 }
1716 if (event.type !== "pointercancel") {
1717 if (link && isSameTerminalLink(link, this.linkAt(event.clientX, event.clientY, true))) {
1718 this.activateLink(link, event, validation);
1719 }
1720 }
1721 return;
1722 }
1723 if (this.mouseReportingPointerId === event.pointerId) {
1724 event.preventDefault();
1725 event.stopPropagation();
1726 this.sendMouse("release", this.mouseReportingButton, event);
1727 this.mouseReportingPointerId = null;
1728 this.mouseReportingButton = null;
1729 if (this.canvas.hasPointerCapture(event.pointerId)) {
1730 this.canvas.releasePointerCapture(event.pointerId);
1731 }
1732 if (event.type === "pointercancel") {
1733 this.clearHoveredLink();
1734 } else {
1735 this.hoverPointer = { x: event.clientX, y: event.clientY };
1736 this.refreshHoveredLink();
1737 }
1738 return;
1739 }
1740 if (this.canvas.hasPointerCapture(event.pointerId)) {
1741 this.canvas.releasePointerCapture(event.pointerId);
1742 }
1743 if (event.button === 1 && isMiddleClickPastePlatform()) {
1744 event.preventDefault();
1745 return;
1746 }
1747 if (event.button !== 0) return;
1748 if (!this.selectionMoved && this.selectionMode === "cell") {
1749 this.clearSelection();
1750 }
1751 this.options.onSelectionChange();
1752 };
1753
1754 private readonly onWheel = (event: WheelEvent) => {
1755 if (event.deltaY === 0) return;
1756 event.preventDefault();
1757 const delta = terminalWheelDeltaRows(
1758 event,
1759 this.metrics.height,
1760 this.rows,
1761 this.wheelRemainder,
1762 );
1763 this.wheelRemainder = delta.remainder;
1764 this.scrollRows(delta.rows, event);
1765 };
1766
1767 private scrollRows(rows: number, event: MouseEvent): void {
1768 if (rows === 0) return;
1769 const magnitude = Math.abs(rows);
1770 if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
1771 const button = rows < 0 ? 4 : 5;
1772 for (let index = 0; index < magnitude; index += 1) {
1773 this.sendMouse("press", button, event);
1774 }
1775 return;
1776 }
1777 if (this.core.isAlternateScreen()) {
1778 // Alternate screens have no scrollback; send arrow keys like xterm.
1779 this.options.onData(terminalWheelArrowData(rows, this.core.isApplicationCursorKeys()));
1780 return;
1781 }
1782 this.scrollViewport(rows);
1783 }
1784
1785 private readonly onMouseDown = (event: MouseEvent) => {
1786 if (event.button === 0 || (event.button === 1 && isMiddleClickPastePlatform())) {
1787 event.preventDefault();
1788 }
1789 this.focus();
1790 };
1791
1792 // Chromium middle mouseup pastes PRIMARY into the focused textarea; prevent a second paste.
1793 private readonly onMouseUp = (event: MouseEvent) => {
1794 if (event.button === 1 && isMiddleClickPastePlatform()) event.preventDefault();
1795 };
1796
1797 private readonly onContextMenu = (event: MouseEvent) => {
1798 if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
1799 event.preventDefault();
1800 return;
1801 }
1802 this.options.onContextMenu?.(event);
1803 };
1804
1805 private readonly onScrollbarPointerDown = (event: PointerEvent) => {
1806 if (event.button !== 0) return;
1807 const state = this.readScrollbarState();
1808 if (state === null) return;
1809 const bounds = this.scrollbar.getBoundingClientRect();
1810 const geometry = terminalScrollbarGeometry(state, bounds.height);
1811 if (geometry === null) return;
1812 event.preventDefault();
1813 event.stopPropagation();
1814 this.scrollbarPointerId = event.pointerId;
1815 this.scrollbarPointerOffset =
1816 event.target === this.scrollbarThumb
1817 ? event.clientY - bounds.top - geometry.thumbTop
1818 : geometry.thumbHeight / 2;
1819 this.scrollbar.setPointerCapture(event.pointerId);
1820 this.scrollbarToPointer(event.clientY, bounds);
1821 };
1822
1823 private readonly onScrollbarPointerMove = (event: PointerEvent) => {
1824 if (event.pointerId !== this.scrollbarPointerId || this.scrollbarState === null) return;
1825 event.preventDefault();
1826 this.scrollbarToPointer(event.clientY, this.scrollbar.getBoundingClientRect());
1827 };
1828
1829 private readonly onScrollbarPointerUp = (event: PointerEvent) => {
1830 if (event.pointerId !== this.scrollbarPointerId) return;
1831 event.preventDefault();
1832 this.scrollbarPointerId = null;
1833 if (this.scrollbar.hasPointerCapture(event.pointerId)) {
1834 this.scrollbar.releasePointerCapture(event.pointerId);
1835 }
1836 };
1837
1838 private readonly onScrollbarKeyDown = (event: KeyboardEvent) => {
1839 const state = this.readScrollbarState();
1840 if (state === null) return;
1841 let delta = 0;
1842 switch (event.key) {
1843 case "ArrowUp":
1844 delta = -1;
1845 break;
1846 case "ArrowDown":
1847 delta = 1;
1848 break;
1849 case "PageUp":
1850 delta = -Math.max(1, state.len);
1851 break;
1852 case "PageDown":
1853 delta = Math.max(1, state.len);
1854 break;
1855 case "Home":
1856 delta = -state.offset;
1857 break;
1858 case "End":
1859 delta = state.total - state.len - state.offset;
1860 break;
1861 default:
1862 return;
1863 }
1864 event.preventDefault();
1865 event.stopPropagation();
1866 this.scrollViewport(delta);
1867 };
1868
1869 private installEvents(): void {
1870 this.input.addEventListener("keydown", this.onKeyDown);
1871 this.input.addEventListener("keyup", this.onKeyUp);
1872 // App shortcuts stop propagation at window, so observe the same capture target.
1873 window.addEventListener("keyup", this.onWindowKeyUp, { capture: true });
1874 window.addEventListener("keydown", this.onWindowKeyDown, { capture: true });
1875 this.input.addEventListener("focus", this.onFocus);
1876 this.input.addEventListener("blur", this.onBlur);
1877 this.input.addEventListener("input", this.onInput);
1878 this.input.addEventListener("paste", this.onPaste);
1879 this.input.addEventListener("copy", this.onCopyEvent);
1880 this.input.addEventListener("compositionstart", this.onCompositionStart);
1881 this.input.addEventListener("compositionend", this.onCompositionEnd);
1882 this.canvas.addEventListener("pointerdown", this.onPointerDown);
1883 this.canvas.addEventListener("pointermove", this.onPointerMove);
1884 this.canvas.addEventListener("pointerleave", this.onPointerLeave);
1885 this.canvas.addEventListener("pointerup", this.onPointerUp);
1886 this.canvas.addEventListener("pointercancel", this.onPointerUp);
1887 this.canvas.addEventListener("wheel", this.onWheel, { passive: false });
1888 this.canvas.addEventListener("mousedown", this.onMouseDown);
1889 this.canvas.addEventListener("mouseup", this.onMouseUp);
1890 this.canvas.addEventListener("contextmenu", this.onContextMenu);
1891 this.scrollbar.addEventListener("pointerdown", this.onScrollbarPointerDown);
1892 this.scrollbar.addEventListener("pointermove", this.onScrollbarPointerMove);
1893 this.scrollbar.addEventListener("pointerup", this.onScrollbarPointerUp);
1894 this.scrollbar.addEventListener("pointercancel", this.onScrollbarPointerUp);
1895 this.scrollbar.addEventListener("keydown", this.onScrollbarKeyDown);
1896 window.addEventListener("pointerup", this.onWindowPointerRelease);
1897 window.addEventListener("pointercancel", this.onWindowPointerRelease);
1898 }
1899
1900 private removeEvents(): void {
1901 this.input.removeEventListener("keydown", this.onKeyDown);
1902 this.input.removeEventListener("keyup", this.onKeyUp);
1903 window.removeEventListener("keyup", this.onWindowKeyUp, { capture: true });
1904 window.removeEventListener("keydown", this.onWindowKeyDown, { capture: true });
1905 this.input.removeEventListener("focus", this.onFocus);
1906 this.input.removeEventListener("blur", this.onBlur);
1907 this.input.removeEventListener("input", this.onInput);
1908 this.input.removeEventListener("paste", this.onPaste);
1909 this.input.removeEventListener("copy", this.onCopyEvent);
1910 this.input.removeEventListener("compositionstart", this.onCompositionStart);
1911 this.input.removeEventListener("compositionend", this.onCompositionEnd);
1912 this.canvas.removeEventListener("pointerdown", this.onPointerDown);
1913 this.canvas.removeEventListener("pointermove", this.onPointerMove);
1914 this.canvas.removeEventListener("pointerleave", this.onPointerLeave);
1915 this.canvas.removeEventListener("pointerup", this.onPointerUp);
1916 this.canvas.removeEventListener("pointercancel", this.onPointerUp);
1917 this.canvas.removeEventListener("wheel", this.onWheel);
1918 this.canvas.removeEventListener("mousedown", this.onMouseDown);
1919 this.canvas.removeEventListener("mouseup", this.onMouseUp);
1920 this.canvas.removeEventListener("contextmenu", this.onContextMenu);
1921 this.scrollbar.removeEventListener("pointerdown", this.onScrollbarPointerDown);
1922 this.scrollbar.removeEventListener("pointermove", this.onScrollbarPointerMove);
1923 this.scrollbar.removeEventListener("pointerup", this.onScrollbarPointerUp);
1924 this.scrollbar.removeEventListener("pointercancel", this.onScrollbarPointerUp);
1925 this.scrollbar.removeEventListener("keydown", this.onScrollbarKeyDown);
1926 window.removeEventListener("pointerup", this.onWindowPointerRelease);
1927 window.removeEventListener("pointercancel", this.onWindowPointerRelease);
1928 }
1929
1930 private scrollViewport(deltaRows: number): void {
1931 let delta = Math.trunc(deltaRows);
1932 const state = this.readScrollbarState();
1933 if (state !== null) {
1934 const maxOffset = Math.max(0, state.total - state.len);
1935 const offset = Math.max(0, Math.min(state.offset + delta, maxOffset));
1936 delta = offset - state.offset;
1937 this.scrollbarState = { ...state, offset };
1938 }
1939 if (delta === 0) return;
1940 this.core.scroll(delta);
1941 this.forceFullRender = true;
1942 this.scrollbarDirty = true;
1943 this.requestRender();
1944 }
1945
1946 private scrollbarToPointer(clientY: number, bounds: DOMRect): void {
1947 const state = this.scrollbarState;
1948 if (state === null) return;
1949 const offset = terminalScrollbarOffsetAtPointer(
1950 state,
1951 bounds.height,
1952 clientY - bounds.top,
1953 this.scrollbarPointerOffset,
1954 );
1955 this.scrollViewport(offset - state.offset);
1956 }
1957
1958 private updateScrollbar(): void {
1959 const state = this.readScrollbarState();
1960 const geometry =
1961 state === null
1962 ? null
1963 : terminalScrollbarGeometry(
1964 state,
1965 Math.max(0, this.mount.clientHeight - CONTENT_PADDING * 2),
1966 );
1967 this.scrollbar.hidden = geometry === null;
1968 if (state === null || geometry === null) return;
1969 this.scrollbar.setAttribute("aria-valuemin", "0");
1970 this.scrollbar.setAttribute("aria-valuemax", String(geometry.maxOffset));
1971 this.scrollbar.setAttribute(
1972 "aria-valuenow",
1973 String(Math.max(0, Math.min(state.offset, geometry.maxOffset))),
1974 );
1975 this.scrollbarThumb.style.height = `${geometry.thumbHeight}px`;
1976 this.scrollbarThumb.style.transform = `translateY(${geometry.thumbTop}px)`;
1977 }
1978
1979 private readScrollbarState(): GhosttyScrollbar | null {
1980 const state = this.core.scrollbarState();
1981 this.scrollbarState = state;
1982 return state;
1983 }
1984
1985 private requestRender(): void {
1986 if (this.disposed || !this.visible || !this.hasSize) return;
1987 if (this.deferSynchronizedRender() || this.frame !== 0) return;
1988 this.frame = window.requestAnimationFrame(() => {
1989 this.frame = 0;
1990 this.renderFrame();
1991 });
1992 }
1993
1994 private cancelRender(): void {
1995 this.cancelSynchronizedRenderTimer();
1996 if (this.frame !== 0) {
1997 window.cancelAnimationFrame(this.frame);
1998 this.frame = 0;
1999 }
2000 if (this.cursorTimer !== null) {
2001 window.clearTimeout(this.cursorTimer);
2002 this.cursorTimer = null;
2003 }
2004 }
2005
2006 private cancelSynchronizedRenderTimer(): void {
2007 if (this.synchronizedRenderTimer === null) return;
2008 window.clearTimeout(this.synchronizedRenderTimer);
2009 this.synchronizedRenderTimer = null;
2010 }
2011
2012 private deferSynchronizedRender(): boolean {
2013 if (!this.core.isSynchronizedOutput()) {
2014 this.cancelSynchronizedRenderTimer();
2015 return false;
2016 }
2017 // A frame queued before the opening marker would now consume partial rows.
2018 if (this.frame !== 0) {
2019 window.cancelAnimationFrame(this.frame);
2020 this.frame = 0;
2021 }
2022 if (this.cursorTimer !== null) {
2023 window.clearTimeout(this.cursorTimer);
2024 this.cursorTimer = null;
2025 }
2026 if (this.synchronizedRenderTimer === null) {
2027 this.synchronizedRenderTimer = window.setTimeout(() => {
2028 this.synchronizedRenderTimer = null;
2029 this.core.endSynchronizedOutput();
2030 this.renderFrame();
2031 }, SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS);
2032 }
2033 return true;
2034 }
2035
2036 private renderFrame(): void {
2037 if (this.disposed || !this.visible) return;
2038 if (this.frame !== 0) {
2039 window.cancelAnimationFrame(this.frame);
2040 this.frame = 0;
2041 }
2042 if (this.mount.clientWidth === 0 || this.mount.clientHeight === 0) {
2043 this.hasSize = false;
2044 this.forceFullRender = true;
2045 this.cancelRender();
2046 return;
2047 }
2048 if (this.deferSynchronizedRender()) return;
2049 const canvasConfiguration = this.pendingCanvasConfiguration;
2050 if (canvasConfiguration !== null) {
2051 this.pendingCanvasConfiguration = null;
2052 this.canvas.width = canvasConfiguration.width;
2053 this.canvas.height = canvasConfiguration.height;
2054 this.context.setTransform(canvasConfiguration.ratio, 0, 0, canvasConfiguration.ratio, 0, 0);
2055 this.canvasConfigured = true;
2056 this.canvasDevicePixelRatio = canvasConfiguration.ratio;
2057 }
2058 const previousBackground = this.snapshot?.background;
2059 this.snapshot = this.core.snapshot();
2060 // Only a full render repaints the padding around the rows in the new default background.
2061 if (previousBackground && !ghosttyColorsEqual(previousBackground, this.snapshot.background)) {
2062 this.forceFullRender = true;
2063 }
2064 if (!this.blinkEnabled()) this.cursorOn = true;
2065 // Move the origin only on full repaint; dirty-row updates cannot mix origins.
2066 const scrollState = this.readScrollbarState();
2067 const anchorBottom = scrollState !== null && scrollState.total > scrollState.len;
2068 const nextOriginY = terminalContentOriginY(
2069 this.mountHeight,
2070 CONTENT_PADDING,
2071 this.rows,
2072 this.metrics.height,
2073 anchorBottom,
2074 );
2075 const geometryChanged = canvasConfiguration !== null || nextOriginY !== this.originY;
2076 if (nextOriginY !== this.originY) {
2077 this.originY = nextOriginY;
2078 this.forceFullRender = true;
2079 }
2080 this.updateLinkRowStability(geometryChanged);
2081 this.refreshHoveredLink();
2082 renderGhosttySnapshot({
2083 context: this.context,
2084 snapshot: this.snapshot,
2085 metrics: this.metrics,
2086 fontSize: this.fontSize,
2087 fontFamily: this.fontFamily,
2088 padding: CONTENT_PADDING,
2089 originY: this.originY,
2090 forceFull: this.forceFullRender,
2091 cursorOn: this.cursorOn,
2092 previousCursorY: this.renderedCursorY,
2093 focused: this.focused,
2094 hoveredLinkRange: this.hoveredLink?.range ?? null,
2095 ...(this.theme.selectionBackground !== undefined
2096 ? { selectionBackground: this.theme.selectionBackground }
2097 : {}),
2098 });
2099 this.positionInput();
2100 this.renderedCursorY =
2101 this.cursorOn && this.snapshot.cursorVisible && this.snapshot.cursorY >= 0
2102 ? this.snapshot.cursorY
2103 : null;
2104 if (this.scrollbarDirty) {
2105 this.scrollbarDirty = false;
2106 this.updateScrollbar();
2107 }
2108 this.forceFullRender = false;
2109 this.scheduleCursorBlink();
2110 }
2111
2112 private scheduleCursorBlink(): void {
2113 if (this.cursorTimer !== null) window.clearTimeout(this.cursorTimer);
2114 this.cursorTimer = null;
2115 if (!this.blinkEnabled()) return;
2116 this.cursorTimer = window.setTimeout(() => {
2117 this.cursorTimer = null;
2118 this.cursorOn = !this.cursorOn;
2119 this.requestRender();
2120 }, CURSOR_BLINK_INTERVAL_MS);
2121 }
2122
2123 private blinkEnabled(): boolean {
2124 const snapshot = this.snapshot;
2125 if (!snapshot || !this.visible || !this.hasSize) return false;
2126 return shouldBlinkTerminalCursor({
2127 focused: this.focused,
2128 cursorBlinking: snapshot.cursorBlinking,
2129 cursorVisible: snapshot.cursorVisible,
2130 reducedMotion: this.reducedMotionMedia?.matches ?? false,
2131 });
2132 }
2133
2134 private positionInput(): void {
2135 const snapshot = this.snapshot;
2136 if (!snapshot || !snapshot.cursorVisible || snapshot.cursorX < 0 || snapshot.cursorY < 0) {
2137 return;
2138 }
2139 const left = CONTENT_PADDING + snapshot.cursorX * this.metrics.width;
2140 const top = this.originY + snapshot.cursorY * this.metrics.height;
2141 if (left === this.inputLeft && top === this.inputTop) return;
2142 this.inputLeft = left;
2143 this.inputTop = top;
2144 this.input.style.left = `${left}px`;
2145 this.input.style.top = `${top}px`;
2146 this.input.style.height = `${this.metrics.height}px`;
2147 }
2148
2149 private cellAt(clientX: number, clientY: number): { x: number; y: number } {
2150 const bounds = this.canvas.getBoundingClientRect();
2151 return {
2152 x: Math.max(
2153 0,
2154 Math.min(
2155 this.cols - 1,
2156 Math.floor((clientX - bounds.left - CONTENT_PADDING) / this.metrics.width),
2157 ),
2158 ),
2159 y: Math.max(
2160 0,
2161 Math.min(
2162 this.rows - 1,
2163 Math.floor((clientY - bounds.top - this.originY) / this.metrics.height),
2164 ),
2165 ),
2166 };
2167 }
2168
2169 private validateLink(text: string): Promise<boolean> | undefined {
2170 if (this.options.canActivateLink?.(text) !== false) return;
2171 const validation = this.options.validateLink?.(text);
2172 // A drag can abandon the press before activateLink subscribes to its result.
2173 void validation?.catch(() => {});
2174 return validation;
2175 }
2176
2177 private activateLink(
2178 link: TerminalLinkWithRange,
2179 event: MouseEvent,
2180 validation = this.validateLink(link.text),
2181 ): void {
2182 if (!validation) {
2183 this.options.onLinkActivate(link.text, event);
2184 return;
2185 }
2186 const requestId = this.linkActivationRequestId;
2187 void validation.then(
2188 (valid) => {
2189 if (
2190 this.disposed ||
2191 !this.visible ||
2192 requestId !== this.linkActivationRequestId ||
2193 !isSameTerminalLink(link, this.findLinkAt(event.clientX, event.clientY))
2194 )
2195 return;
2196 if (valid) this.options.onLinkActivate(link.text, event);
2197 else this.clearSelection();
2198 },
2199 () => {},
2200 );
2201 }
2202
2203 private linkAt(
2204 clientX: number,
2205 clientY: number,
2206 allowValidation = false,
2207 ): TerminalLinkWithRange | null {
2208 const link = this.findLinkAt(clientX, clientY);
2209 return link &&
2210 ((allowValidation && this.options.validateLink) ||
2211 this.options.canActivateLink?.(link.text) !== false)
2212 ? link
2213 : null;
2214 }
2215
2216 private findLinkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {
2217 if (!this.snapshot) return null;
2218 const cell = terminalGridCellAt({
2219 bounds: this.canvas.getBoundingClientRect(),
2220 clientX,
2221 clientY,
2222 cols: this.cols,
2223 rows: this.rows,
2224 metrics: this.metrics,
2225 padding: CONTENT_PADDING,
2226 originY: this.originY,
2227 });
2228 if (!cell) return null;
2229 const explicitHyperlink = this.core.hyperlinkAt(cell.x, cell.y);
2230 if (explicitHyperlink) {
2231 const start = { ...cell };
2232 const end = { ...cell };
2233 while (true) {
2234 const previous =
2235 start.x > 0
2236 ? { x: start.x - 1, y: start.y }
2237 : start.y > 0 && this.snapshot.rowData[start.y]?.isWrapContinuation
2238 ? { x: this.cols - 1, y: start.y - 1 }
2239 : null;
2240 if (!previous || this.core.hyperlinkAt(previous.x, previous.y) !== explicitHyperlink) break;
2241 start.x = previous.x;
2242 start.y = previous.y;
2243 }
2244 while (true) {
2245 const next =
2246 end.x + 1 < this.cols
2247 ? { x: end.x + 1, y: end.y }
2248 : end.y + 1 < this.rows && this.snapshot.rowData[end.y]?.wrapsToNext
2249 ? { x: 0, y: end.y + 1 }
2250 : null;
2251 if (!next || this.core.hyperlinkAt(next.x, next.y) !== explicitHyperlink) break;
2252 end.x = next.x;
2253 end.y = next.y;
2254 }
2255 return {
2256 text: explicitHyperlink,
2257 range: { start, end },
2258 };
2259 }
2260 return terminalLinkAtPositionWithRange(this.snapshot.rowData, cell.y, cell.x);
2261 }
2262
2263 private sendMouse(action: TerminalMouseAction, button: number | null, event: MouseEvent): void {
2264 const bounds = this.canvas.getBoundingClientRect();
2265 const report = this.core.encodeMouse({
2266 action,
2267 button,
2268 mods:
2269 (event.shiftKey ? 1 : 0) |
2270 (event.ctrlKey ? 1 << 1 : 0) |
2271 (event.altKey ? 1 << 2 : 0) |
2272 (event.metaKey ? 1 << 3 : 0),
2273 x: Math.max(0, event.clientX - bounds.left),
2274 y: Math.max(0, event.clientY - bounds.top),
2275 screenWidth: bounds.width,
2276 screenHeight: bounds.height,
2277 cellWidth: this.metrics.width,
2278 cellHeight: this.metrics.height,
2279 paddingLeft: CONTENT_PADDING,
2280 paddingRight: CONTENT_PADDING,
2281 paddingTop: this.originY,
2282 paddingBottom: Math.max(0, bounds.height - this.originY - this.rows * this.metrics.height),
2283 anyButtonPressed: event.buttons !== 0,
2284 });
2285 const resolution = resolveTerminalMouseData(action, report, this.lastMouseMotionData);
2286 this.lastMouseMotionData = resolution.nextMotionData;
2287 if (!resolution.send) return;
2288 if (report.binary) this.options.onBinary(report.data);
2289 else this.options.onData(report.data);
2290 }
2291
2292 private synchronizeMouseTrackingState(): boolean {
2293 // Output can toggle DEC 1003; track the prior mode so same-cell motion can start a new session.
2294 const tracking = this.core.isMouseAnyEventTracking();
2295 const state = resolveTerminalMouseTrackingState(
2296 this.mouseAnyEventTracking,
2297 tracking,
2298 this.lastMouseMotionData,
2299 );
2300 this.mouseAnyEventTracking = state.tracking;
2301 this.lastMouseMotionData = state.motionData;
2302 return tracking;
2303 }
2304
2305 private buttonFromButtons(buttons: number): number | null {
2306 if ((buttons & 1) !== 0) return 1;
2307 if ((buttons & 4) !== 0) return 3;
2308 if ((buttons & 2) !== 0) return 2;
2309 if ((buttons & 8) !== 0) return 4;
2310 if ((buttons & 16) !== 0) return 5;
2311 return null;
2312 }
2313 }