sailfork / t3code-github / apps/ web/ src/ terminal/ ghostty/ surface.ts

import { isMacPlatform } from "../../lib/utils";
import { SELECTION_MULTI_CLICK_INTERVAL_MS } from "../../lib/selectionActions";
import { collectWrappedTerminalLinkLine, extractTerminalLinks } from "../../terminal-links";
import {
  GHOSTTY_CELL_WIDE,
  GhosttyTerminalCore,
  type GhosttyCell,
  type GhosttyScrollbar,
  type GhosttySnapshot,
  type GhosttyTheme,
} from "./core";
import {
  measureGhosttyCell,
  renderGhosttySnapshot,
  terminalGridSize,
  type GhosttyCellRange,
  type GhosttyCellMetrics,
} from "./renderer";
import symbolsFontUrl from "./fonts/SymbolsNerdFontMono-Regular.woff2?url";
import { isMonospaceFamily } from "../../appearanceFonts";
import { observeResize } from "../../lib/observeResize";

const DEFAULT_TERMINAL_FONT_SIZE = 12;
const MIN_TERMINAL_FONT_SIZE = 6;
const MAX_TERMINAL_FONT_SIZE = 32;
const TERMINAL_GLYPH_FALLBACKS =
  '"Symbols Nerd Font Mono", "Symbols Nerd Font", "JetBrainsMono Nerd Font", ' +
  '"JetBrainsMono NF", "FiraCode Nerd Font", "Hack Nerd Font", "MesloLGS NF", ' +
  '"CaskaydiaCove Nerd Font", "PowerlineSymbols", monospace';
// The platform's own monospace faces; concrete names only, because an
// unknown keyword (like ui-monospace) makes canvas font shorthand parsing
// reject the whole string.
const DEFAULT_TERMINAL_FONT_FAMILY =
  '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", ' + TERMINAL_GLYPH_FALLBACKS;
const CONTENT_PADDING = 4;
const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
const CURSOR_BLINK_INTERVAL_MS = 500;
const TERMINAL_LINK_HOVER_DELAY_MS = 250;
/** End an unterminated synchronized update instead of freezing the last frame. */
const SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS = 500;
const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
const TERMINAL_FONT_LOAD_VARIANTS = [
  "normal 400",
  "normal 700",
  "italic 400",
  "italic 700",
] as const;

export interface GhosttyTerminalFont {
  readonly family?: string;
  readonly size?: number;
}

let symbolsFontLoad: Promise<void> | null = null;

function ensureTerminalSymbolsFont(): Promise<void> {
  if (symbolsFontLoad !== null) return symbolsFontLoad;
  symbolsFontLoad = (async () => {
    try {
      const face = new FontFace("Symbols Nerd Font Mono", `url(${symbolsFontUrl})`);
      document.fonts.add(await face.load());
    } catch {}
  })();
  return symbolsFontLoad;
}

function quoteTerminalFontFamilies(list: string): string {
  return list
    .split(",")
    .map((name) => {
      const bare = name.trim();
      if (bare.length === 0) return "";
      if (/^(['"]).*\1$/.test(bare)) return bare;
      if (/^[a-zA-Z][a-zA-Z0-9-]*$/.test(bare)) return bare;
      return `"${bare.replaceAll('"', "")}"`;
    })
    .filter((name) => name.length > 0)
    .join(", ");
}

function uncheckedTerminalFontFamily(family?: string): string {
  const custom = family === undefined ? "" : quoteTerminalFontFamilies(family);
  return custom.length === 0
    ? DEFAULT_TERMINAL_FONT_FAMILY
    : `${custom}, ${TERMINAL_GLYPH_FALLBACKS}`;
}

function terminalFontFamily(family?: string): string {
  // Quote non-ident names ("3270 Nerd Font", "M+ 1m"): an unquoted one makes
  // the whole canvas font string invalid and the assignment silently no-ops.
  const custom = family === undefined ? "" : quoteTerminalFontFamilies(family);
  if (custom.length === 0) return DEFAULT_TERMINAL_FONT_FAMILY;
  if (!isMonospaceFamily(custom)) return DEFAULT_TERMINAL_FONT_FAMILY;
  return uncheckedTerminalFontFamily(custom);
}

async function loadTerminalFontFamily(
  family: string | undefined,
  size: number,
  environment?: {
    readonly load: (font: string, text: string) => Promise<unknown>;
    readonly resolve: (family: string | undefined) => string;
  },
): Promise<string> {
  const candidate = uncheckedTerminalFontFamily(family);
  const load =
    environment?.load ?? ((font: string, text: string) => document.fonts.load(font, text));
  try {
    await Promise.all(
      TERMINAL_FONT_LOAD_VARIANTS.map((variant) =>
        load(`${variant} ${size}px ${candidate}`, TERMINAL_FONT_LOAD_TEXT),
      ),
    );
  } catch {}
  return (environment?.resolve ?? terminalFontFamily)(family);
}

function terminalFontSize(size?: number): number {
  if (size === undefined || !Number.isFinite(size)) return DEFAULT_TERMINAL_FONT_SIZE;
  return Math.max(MIN_TERMINAL_FONT_SIZE, Math.min(MAX_TERMINAL_FONT_SIZE, Math.round(size)));
}

function shouldBlinkTerminalCursor(state: {
  readonly focused: boolean;
  readonly cursorBlinking: boolean;
  readonly cursorVisible: boolean;
  readonly reducedMotion: boolean;
}): boolean {
  return state.focused && state.cursorBlinking && state.cursorVisible && !state.reducedMotion;
}

export function terminalContentOriginY(
  mountHeight: number,
  padding: number,
  rows: number,
  cellHeight: number,
  anchorBottom: boolean,
): number {
  if (!anchorBottom) return padding;
  const slack = mountHeight - padding * 2 - rows * cellHeight;
  return padding + Math.max(0, slack);
}

export interface TerminalScrollbarGeometry {
  readonly thumbHeight: number;
  readonly thumbTop: number;
  readonly maxOffset: number;
}

function terminalScrollbarGeometry(
  state: GhosttyScrollbar,
  trackHeight: number,
): TerminalScrollbarGeometry | null {
  const total = Math.max(0, state.total);
  const len = Math.max(0, Math.min(state.len, total));
  const maxOffset = Math.max(0, total - len);
  if (trackHeight <= 0 || len <= 0 || maxOffset === 0) return null;
  const thumbHeight = Math.min(
    trackHeight,
    Math.max(MIN_SCROLLBAR_THUMB_HEIGHT, (trackHeight * len) / total),
  );
  const travel = Math.max(0, trackHeight - thumbHeight);
  const offset = Math.max(0, Math.min(state.offset, maxOffset));
  return {
    thumbHeight,
    thumbTop: travel * (offset / maxOffset),
    maxOffset,
  };
}

function terminalScrollbarOffsetAtPointer(
  state: GhosttyScrollbar,
  trackHeight: number,
  pointerY: number,
  pointerOffset: number,
): number {
  const geometry = terminalScrollbarGeometry(state, trackHeight);
  if (geometry === null) return 0;
  const travel = Math.max(0, trackHeight - geometry.thumbHeight);
  if (travel === 0) return 0;
  const thumbTop = Math.max(0, Math.min(pointerY - pointerOffset, travel));
  return Math.round((thumbTop / travel) * geometry.maxOffset);
}

function terminalGridCellAt(options: {
  bounds: { left: number; top: number };
  clientX: number;
  clientY: number;
  cols: number;
  rows: number;
  metrics: Pick<GhosttyCellMetrics, "width" | "height">;
  padding: number;
  originY: number;
}): { x: number; y: number } | null {
  const { bounds, clientX, clientY, cols, rows, metrics, padding, originY } = options;
  const gridX = clientX - bounds.left - padding;
  const gridY = clientY - bounds.top - originY;
  if (gridX < 0 || gridY < 0 || gridX >= cols * metrics.width || gridY >= rows * metrics.height) {
    return null;
  }
  return {
    x: Math.floor(gridX / metrics.width),
    y: Math.floor(gridY / metrics.height),
  };
}

function terminalCellText(cell: GhosttyCell): string {
  if (cell.wide === GHOSTTY_CELL_WIDE.spacerTail || cell.wide === GHOSTTY_CELL_WIDE.spacerHead) {
    return "";
  }
  return cell.text || " ";
}

function terminalRowText(row: GhosttySnapshot["rowData"][number], trimRight: boolean): string {
  const text = row.cells.map(terminalCellText).join("");
  return trimRight ? text.trimEnd() : text;
}

function terminalColumnOffset(row: GhosttySnapshot["rowData"][number], column: number): number {
  let offset = 0;
  for (let cellIndex = 0; cellIndex < column; cellIndex += 1) {
    const cell = row.cells[cellIndex];
    offset += cell ? terminalCellText(cell).length : 1;
  }
  return offset;
}

export interface TerminalLinkWithRange {
  readonly text: string;
  readonly range: GhosttyCellRange;
}

function isSameTerminalLink(
  left: TerminalLinkWithRange,
  right: TerminalLinkWithRange | null,
): boolean {
  return (
    right?.text === left.text &&
    right.range.start.x === left.range.start.x &&
    right.range.start.y === left.range.start.y &&
    right.range.end.x === left.range.end.x &&
    right.range.end.y === left.range.end.y
  );
}

function terminalColumnAtOffset(row: GhosttySnapshot["rowData"][number], offset: number): number {
  for (let column = 0; column < row.cells.length; column += 1) {
    const nextOffset = terminalColumnOffset(row, column + 1);
    if (offset < nextOffset) return column;
  }
  return Math.max(0, row.cells.length - 1);
}

export function terminalLinkAtPositionWithRange(
  rows: GhosttySnapshot["rowData"],
  rowIndex: number,
  column: number,
): TerminalLinkWithRange | null {
  const wrappedLine = collectWrappedTerminalLinkLine(rowIndex + 1, (index) => {
    const row = rows[index];
    if (!row) return null;
    return {
      isWrapped: row.isWrapContinuation,
      translateToString: (trimRight = false) => terminalRowText(row, trimRight),
    };
  });
  if (!wrappedLine) return null;
  // A wrapped line starting above the viewport would produce a truncated, incorrect link.
  const firstSegment = wrappedLine.segments[0];
  if (firstSegment && rows[firstSegment.bufferLineNumber - 1]?.isWrapContinuation) {
    return null;
  }
  const segment = wrappedLine.segments.find((value) => value.bufferLineNumber === rowIndex + 1);
  const row = rows[rowIndex];
  if (!segment || !row) return null;
  const lastSegment = wrappedLine.segments.at(-1);
  const lastRow = lastSegment ? rows[lastSegment.bufferLineNumber - 1] : undefined;
  const continuesBelowViewport = lastRow !== undefined && lastRow.wrapsToNext;
  const hitColumn = row.cells[column]?.wide === GHOSTTY_CELL_WIDE.spacerTail ? column - 1 : column;
  const offset = segment.startIndex + terminalColumnOffset(row, hitColumn);
  for (const match of extractTerminalLinks(wrappedLine.text)) {
    if (offset >= match.start && offset < match.end) {
      if (match.end === wrappedLine.text.length && continuesBelowViewport) return null;
      const startSegment = wrappedLine.segments.find(
        (value) => match.start >= value.startIndex && match.start < value.endIndex,
      );
      const endSegment = wrappedLine.segments.find(
        (value) => match.end - 1 >= value.startIndex && match.end - 1 < value.endIndex,
      );
      const startRow = startSegment ? rows[startSegment.bufferLineNumber - 1] : undefined;
      const endRow = endSegment ? rows[endSegment.bufferLineNumber - 1] : undefined;
      if (!startSegment || !endSegment || !startRow || !endRow) return null;
      const endColumn = terminalColumnAtOffset(endRow, match.end - 1 - endSegment.startIndex);
      return {
        text: match.text,
        range: {
          start: {
            x: terminalColumnAtOffset(startRow, match.start - startSegment.startIndex),
            y: startSegment.bufferLineNumber - 1,
          },
          end: {
            x:
              endRow.cells[endColumn + 1]?.wide === GHOSTTY_CELL_WIDE.spacerTail
                ? endColumn + 1
                : endColumn,
            y: endSegment.bufferLineNumber - 1,
          },
        },
      };
    }
  }
  return null;
}

export function isTerminalCopyShortcut(
  event: Pick<KeyboardEvent, "ctrlKey" | "key" | "metaKey" | "shiftKey">,
  platform = navigator.platform,
) {
  const key = event.key.toLowerCase();
  if (key === "insert" && !isMacPlatform(platform)) {
    return event.ctrlKey && !event.shiftKey && !event.metaKey;
  }
  if (key !== "c") return false;
  return isMacPlatform(platform) ? event.metaKey : event.ctrlKey;
}

/** Primes native and Electron menu copy from the focused textarea; canvas has no DOM selection. */
export function primeTerminalCopyInput(
  input: Pick<HTMLTextAreaElement, "value" | "select">,
  selection: string,
): void {
  input.value = selection;
  if (selection.length === 0) return;
  input.select();
}

export function clearPrimedTerminalCopyInput(
  input: Pick<HTMLTextAreaElement, "value">,
  primedSelection: string,
): void {
  // Only clear the parked copy; other text may be an active CJK composition.
  if (primedSelection.length === 0 || input.value !== primedSelection) return;
  input.value = "";
}

export function applyTerminalCopyEvent(
  selection: string,
  clipboardData: { setData: (type: string, data: string) => void } | null | undefined,
): { preventDefault: boolean; claimWriteFallback: boolean } {
  if (selection.length === 0 || !clipboardData) {
    return { preventDefault: false, claimWriteFallback: false };
  }
  clipboardData.setData("text/plain", selection);
  return { preventDefault: true, claimWriteFallback: true };
}

function isTerminalPasteShortcut(
  event: Pick<KeyboardEvent, "ctrlKey" | "key" | "metaKey" | "shiftKey">,
  platform = navigator.platform,
) {
  const key = event.key.toLowerCase();
  if (key === "insert" && !isMacPlatform(platform)) {
    return event.shiftKey && !event.ctrlKey && !event.metaKey;
  }
  if (key !== "v") return false;
  return isMacPlatform(platform) ? event.metaKey : event.ctrlKey && event.shiftKey;
}

// X11/Wayland expects middle-click paste; macOS and Windows use it for autoscroll.
function isMiddleClickPastePlatform(): boolean {
  return /linux|bsd/i.test(navigator.platform);
}

function isTerminalCompositionCommitInput(event: Pick<InputEvent, "inputType">): boolean {
  return (
    event.inputType === "" ||
    event.inputType === "insertCompositionText" ||
    event.inputType === "insertFromComposition"
  );
}

export function isTerminalCompositionKey(
  event: Pick<KeyboardEvent, "isComposing" | "key" | "keyCode">,
  composing: boolean,
): boolean {
  return event.isComposing || composing || event.key === "Process" || event.keyCode === 229;
}

function isTerminalAltGraphText(event: Pick<KeyboardEvent, "getModifierState" | "key">): boolean {
  return event.getModifierState("AltGraph") && [...event.key].length === 1;
}

function shouldReportTerminalMouse(
  tracking: boolean,
  event: Pick<MouseEvent, "ctrlKey" | "metaKey" | "shiftKey">,
): boolean {
  return tracking && !event.shiftKey && !event.ctrlKey && !event.metaKey;
}

type TerminalMouseAction = "press" | "release" | "motion";

export function resolveTerminalMouseData(
  action: TerminalMouseAction,
  data: string,
  previousMotionData: string,
): { readonly send: boolean; readonly nextMotionData: string } {
  const nextMotionData = action === "motion" ? data : "";
  return {
    send: data.length > 0 && (action !== "motion" || data !== previousMotionData),
    nextMotionData,
  };
}

function resolveTerminalMouseTrackingState(
  previousTracking: boolean,
  tracking: boolean,
  motionData: string,
): { readonly tracking: boolean; readonly motionData: string } {
  return {
    tracking,
    motionData: previousTracking === tracking ? motionData : "",
  };
}

export function terminalWheelDeltaRows(
  event: Pick<WheelEvent, "deltaY" | "deltaMode">,
  cellHeight: number,
  viewportRows: number,
  remainder: number,
): { readonly rows: number; readonly remainder: number } {
  const pixels =
    event.deltaMode === 1
      ? event.deltaY * cellHeight
      : event.deltaMode === 2
        ? event.deltaY * viewportRows * cellHeight
        : event.deltaY;
  const total = remainder + pixels / cellHeight;
  const rows = Math.trunc(total);
  return { rows, remainder: total - rows };
}

// Ramp from 1 to 15 rows per autoscroll tick over the first 50px past the edge, as xterm.js does.
const SELECTION_AUTOSCROLL_RAMP_PX = 50;
const SELECTION_AUTOSCROLL_MAX_ROWS = 15;

export function terminalSelectionAutoscrollRows(
  clientY: number,
  top: number,
  bottom: number,
): number {
  const distance = clientY < top ? clientY - top : clientY > bottom ? clientY - bottom : 0;
  if (distance === 0) return 0;
  const ramp = Math.max(-1, Math.min(1, distance / SELECTION_AUTOSCROLL_RAMP_PX));
  return Math.sign(ramp) + Math.round(ramp * (SELECTION_AUTOSCROLL_MAX_ROWS - 1));
}

function terminalWheelArrowData(rows: number, applicationCursorKeys: boolean): string {
  if (rows === 0) return "";
  const sequence =
    rows < 0
      ? applicationCursorKeys
        ? "\u001bOA"
        : "\u001b[A"
      : applicationCursorKeys
        ? "\u001bOB"
        : "\u001b[B";
  return sequence.repeat(Math.abs(rows));
}

function ghosttyMouseButton(button: number): number | null {
  switch (button) {
    case 0:
      return 1;
    case 1:
      return 3;
    case 2:
      return 2;
    case 3:
      return 4;
    case 4:
      return 5;
    default:
      return null;
  }
}

export interface TerminalSelectionClickSequence {
  readonly count: number;
  readonly time: number;
  readonly x: number;
  readonly y: number;
}

const TERMINAL_LINK_DRAG_THRESHOLD_PX = 4;

export function advanceTerminalSelectionClickSequence(
  previous: TerminalSelectionClickSequence | null,
  event: Pick<PointerEvent, "clientX" | "clientY" | "timeStamp">,
): TerminalSelectionClickSequence {
  const repeats =
    previous !== null &&
    event.timeStamp - previous.time <= SELECTION_MULTI_CLICK_INTERVAL_MS &&
    Math.hypot(event.clientX - previous.x, event.clientY - previous.y) <=
      TERMINAL_LINK_DRAG_THRESHOLD_PX;
  return {
    count: repeats ? (previous.count >= 3 ? 1 : previous.count + 1) : 1,
    time: event.timeStamp,
    x: event.clientX,
    y: event.clientY,
  };
}

export interface GhosttySelectionPosition {
  readonly start: { readonly x: number; readonly y: number };
  readonly end: { readonly x: number; readonly y: number };
}

export interface GhosttyTerminalSurfaceOptions {
  readonly theme: GhosttyTheme;
  readonly font?: GhosttyTerminalFont;
  /** Read after font and WASM loading. */
  readonly visible?: boolean;
  readonly onData: (data: string) => void;
  readonly onResize: (cols: number, rows: number) => void;
  readonly onSelectionChange: () => void;
  readonly beforeKey: (event: KeyboardEvent) => boolean;
  readonly onLinkActivate: (text: string, event: MouseEvent) => void;
  readonly canActivateLink?: (text: string) => boolean;
  readonly validateLink?: (text: string) => Promise<boolean>;
  /** Reports hovered candidates once their rendered text is stable for 250 ms; null cancels. */
  readonly onLinkHover?: (text: string | null) => void;
  /** The host must prevent the default menu; native Paste cannot reach a canvas terminal. */
  readonly onContextMenu?: (event: MouseEvent) => void;
}

export class GhosttyTerminalSurface {
  readonly canvas: HTMLCanvasElement;
  readonly input: HTMLTextAreaElement;
  readonly scrollbar: HTMLDivElement;
  /** The drawn grid: the shared PTY grid, clamped per axis to the measured one. */
  cols = 1;
  rows = 1;

  private readonly mount: HTMLElement;
  private measuredCols = 1;
  private measuredRows = 1;
  private sharedGrid: { readonly cols: number; readonly rows: number } | null = null;
  private readonly context: CanvasRenderingContext2D;
  private readonly core: GhosttyTerminalCore;
  private readonly options: GhosttyTerminalSurfaceOptions;
  private visible: boolean;
  private hasSize = false;
  private metrics: GhosttyCellMetrics;
  private fontFamily: string;
  private requestedFontFamily: string | undefined;
  private fontSize: number;
  private fontEpoch = 0;
  private pendingFontEpoch: number | null = null;
  private readonly stopObservingResize: () => void;
  private readonly scrollbarThumb: HTMLDivElement;
  private snapshot: GhosttySnapshot | null = null;
  private frame = 0;
  private synchronizedRenderTimer: number | null = null;
  private cursorTimer: number | null = null;
  private compositionInputToSuppress: string | null = null;
  private compositionSuppressionTimer: number | null = null;
  private cursorOn = true;
  private renderedCursorY: number | null = null;
  private forceFullRender = true;
  private scrollbarDirty = true;
  private scrollbarState: GhosttyScrollbar | null = null;
  private scrollbarPointerId: number | null = null;
  private scrollbarPointerOffset = 0;
  private disposed = false;
  private resizeNotifyTimer: number | null = null;
  private originY = CONTENT_PADDING;
  private mountHeight = 0;
  private selectionEnd: { x: number; y: number } | null = null;
  private selectionAnchorScreen: { x: number; y: number } | null = null;
  private selectionMode: "cell" | "word" | "line" = "cell";
  private selectionBase: {
    start: { x: number; y: number };
    end: { x: number; y: number };
  } | null = null;
  private selectionScrollTimer: number | null = null;
  private selectionScrollDelta = 0;
  private selectionPointer: { x: number; y: number } | null = null;
  private mouseReportingPointerId: number | null = null;
  private mouseReportingButton: number | null = null;
  private linkActivationPointerId: number | null = null;
  private linkActivationLink: TerminalLinkWithRange | null = null;
  private linkActivationValidation: Promise<boolean> | undefined;
  private linkActivationRequestId = 0;
  private linkActivationOrigin: {
    x: number;
    y: number;
    clickCount: number;
  } | null = null;
  private hoveredLink: TerminalLinkWithRange | null = null;
  private hoverPointer: { x: number; y: number } | null = null;
  private linkHoverCandidate: TerminalLinkWithRange | null = null;
  private linkHoverTimer: number | null = null;
  private linkRowStability: Array<{
    row: GhosttySnapshot["rowData"][number];
    changedAt: number;
  }> = [];
  private selectionClickSequence: TerminalSelectionClickSequence | null = null;
  private selectionMoved = false;
  private composing = false;
  private focused = false;
  private resizeNotified = false;
  private canvasConfigured = false;
  private canvasDevicePixelRatio = 0;
  private pendingCanvasConfiguration: {
    readonly width: number;
    readonly height: number;
    readonly ratio: number;
  } | null = null;
  private theme: GhosttyTheme;
  // App capture can hide keydowns, so only encoded presses qualify for Kitty releases.
  private readonly encodedKeyCodes = new Set<string>();
  private pasteShortcutToken = 0;
  // Chromium can deliver native paste after the clipboard read resolves.
  // Suppress its duplicate only for the current shortcut gesture.
  private pasteShortcutGesture: { code: string; readText: string } | null = null;
  private copyShortcutToken = 0;
  private clearSelectionAfterCopy = false;
  private primedCopySelection = "";
  private wheelRemainder = 0;
  private touchScroll: {
    pointerId: number;
    startX: number;
    startY: number;
    lastY: number;
    remainder: number;
    moved: boolean;
  } | null = null;
  private lastMouseMotionData = "";
  private mouseAnyEventTracking = false;
  private dprMedia: MediaQueryList | null = null;
  // Watch reduced motion changes to restart blink cycles that have no remaining timer.
  private readonly reducedMotionMedia = window.matchMedia?.("(prefers-reduced-motion: reduce)");
  private inputLeft = -1;
  private inputTop = -1;

  private constructor(
    mount: HTMLElement,
    canvas: HTMLCanvasElement,
    input: HTMLTextAreaElement,
    scrollbar: HTMLDivElement,
    scrollbarThumb: HTMLDivElement,
    context: CanvasRenderingContext2D,
    core: GhosttyTerminalCore,
    metrics: GhosttyCellMetrics,
    fontFamily: string,
    options: GhosttyTerminalSurfaceOptions,
  ) {
    this.mount = mount;
    this.canvas = canvas;
    this.input = input;
    this.scrollbar = scrollbar;
    this.scrollbarThumb = scrollbarThumb;
    this.context = context;
    this.core = core;
    this.mouseAnyEventTracking = core.isMouseAnyEventTracking();
    this.metrics = metrics;
    this.options = options;
    this.visible = options.visible ?? true;
    this.theme = options.theme;
    this.fontFamily = fontFamily;
    this.requestedFontFamily = options.font?.family;
    this.fontSize = terminalFontSize(options.font?.size);
    this.installEvents();
    this.watchDevicePixelRatio();
    this.reducedMotionMedia?.addEventListener("change", this.onReducedMotionChange);
    document.fonts.addEventListener("loadingdone", this.onFontsLoaded);
    this.stopObservingResize = observeResize(mount, () => this.fit());
  }

  static async create(
    mount: HTMLElement,
    options: GhosttyTerminalSurfaceOptions,
  ): Promise<GhosttyTerminalSurface> {
    const canvas = document.createElement("canvas");
    canvas.className = "block size-full cursor-text";
    canvas.style.touchAction = "pan-x pinch-zoom";
    canvas.setAttribute("aria-hidden", "true");

    const input = document.createElement("textarea");
    input.className = "t3-ghostty-input";
    input.setAttribute("aria-label", "Terminal input");
    input.autocapitalize = "off";
    input.autocomplete = "off";
    input.spellcheck = false;
    input.style.cssText =
      "position:absolute;left:4px;top:4px;width:1px;height:1px;opacity:0;padding:0;border:0;resize:none;pointer-events:none;";

    const scrollbar = document.createElement("div");
    scrollbar.className =
      "group absolute top-1 right-px bottom-1 z-1 w-[var(--app-scrollbar-width)] cursor-default touch-none";
    scrollbar.setAttribute("role", "scrollbar");
    scrollbar.setAttribute("aria-label", "Terminal scrollback");
    scrollbar.setAttribute("aria-orientation", "vertical");
    scrollbar.tabIndex = 0;
    scrollbar.hidden = true;
    const scrollbarThumb = document.createElement("div");
    scrollbarThumb.className =
      "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)]";
    scrollbar.append(scrollbarThumb);
    mount.replaceChildren(canvas, input, scrollbar);

    const context = canvas.getContext("2d", { alpha: false });
    if (!context) throw new Error("Canvas 2D is unavailable");
    context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
    context.fillRect(0, 0, canvas.width, canvas.height);
    const fontSize = terminalFontSize(options.font?.size);
    try {
      // Load bundled fonts before measuring; fallback metrics would size the wrong grid.
      await ensureTerminalSymbolsFont();
    } catch {}
    const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
    const metrics = measureGhosttyCell(context, fontSize, fontFamily);
    const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
    const core = await GhosttyTerminalCore.create(
      grid.cols,
      grid.rows,
      metrics.width,
      metrics.height,
      options.theme,
      options.onData,
    );
    const surface = new GhosttyTerminalSurface(
      mount,
      canvas,
      input,
      scrollbar,
      scrollbarThumb,
      context,
      core,
      metrics,
      fontFamily,
      options,
    );
    surface.fit();
    return surface;
  }

  setVisible(visible: boolean): void {
    if (this.disposed || this.visible === visible) return;
    this.visible = visible;
    this.cursorOn = true;
    this.forceFullRender = true;
    this.scrollbarDirty = true;
    if (!visible) {
      this.linkActivationRequestId += 1;
      this.clearHoveredLink();
      this.linkRowStability = [];
      this.cancelRender();
      this.setSelectionAutoscroll(0);
      return;
    }
    this.fit();
  }

  write(data: string): void {
    if (this.disposed) return;
    this.core.write(
      data,
      this.synchronizedRenderTimer === null
        ? undefined
        : () => this.cancelSynchronizedRenderTimer(),
    );
    this.synchronizeMouseTrackingState();
    this.cursorOn = true;
    this.scrollbarDirty = true;
    this.requestRender();
  }

  resetAndWrite(data: string): void {
    if (this.disposed) return;
    this.cancelSynchronizedRenderTimer();
    this.lastMouseMotionData = "";
    this.core.resetAndWrite(data);
    this.synchronizeMouseTrackingState();
    this.cursorOn = true;
    this.forceFullRender = true;
    this.scrollbarDirty = true;
    this.requestRender();
  }

  setTheme(theme: GhosttyTheme): void {
    if (this.disposed) return;
    this.theme = theme;
    this.core.setTheme(theme);
    this.forceFullRender = true;
    this.requestRender();
  }

  refreshLinkActivation(): void {
    if (this.disposed) return;
    this.refreshHoveredLink();
  }

  /** Mount height, in CSS pixels, that shows exactly `rows` rows at the current font. */
  heightForRows(rows: number): number {
    return Math.ceil(rows * this.metrics.height + CONTENT_PADDING * 2);
  }

  async setFont(font: GhosttyTerminalFont): Promise<void> {
    if (this.disposed) return;
    const fontSize = terminalFontSize(font.size);
    // Commit fields with loaded metrics; the epoch makes the newest overlapping call win.
    const epoch = ++this.fontEpoch;
    this.pendingFontEpoch = epoch;
    const fontFamily = await loadTerminalFontFamily(font.family, fontSize);
    if (this.disposed || epoch !== this.fontEpoch) return;
    this.pendingFontEpoch = null;
    this.fontFamily = fontFamily;
    this.requestedFontFamily = font.family;
    this.fontSize = fontSize;
    this.applyFontMetrics();
  }

  private applyFontMetrics(): void {
    this.metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
    this.core.resize(this.cols, this.rows, this.metrics.width, this.metrics.height);
    this.inputLeft = -1;
    this.inputTop = -1;
    this.forceFullRender = true;
    this.scrollbarDirty = true;
    this.fit();
    this.requestRender();
  }

  private readonly onReducedMotionChange = () => {
    if (this.disposed) return;
    // Restart from render; reduced motion left the steady cursor with no blink timer.
    this.cursorOn = true;
    this.requestRender();
  };

  private readonly onFontsLoaded = () => {
    if (this.disposed) return;
    // Explicit loads validate and apply the newest request; ignore their events for the old face.
    if (this.pendingFontEpoch !== null) return;
    const fontFamily = terminalFontFamily(this.requestedFontFamily);
    if (fontFamily !== this.fontFamily) {
      this.fontFamily = fontFamily;
      this.applyFontMetrics();
      return;
    }
    const metrics = measureGhosttyCell(this.context, this.fontSize, this.fontFamily);
    if (
      metrics.width === this.metrics.width &&
      metrics.height === this.metrics.height &&
      metrics.baseline === this.metrics.baseline
    ) {
      return;
    }
    this.applyFontMetrics();
  };

  resendSize(): void {
    this.resizeNotified = false;
    this.fit();
  }

  fit(): boolean {
    if (this.disposed || !this.visible) return false;
    const width = this.mount.clientWidth;
    const height = this.mount.clientHeight;
    if (width <= 0 || height <= 0) {
      this.hasSize = false;
      this.forceFullRender = true;
      this.cancelRender();
      return false;
    }
    this.hasSize = true;
    const ratio = window.devicePixelRatio || 1;
    const pixelWidth = Math.max(1, Math.round(width * ratio));
    const pixelHeight = Math.max(1, Math.round(height * ratio));
    let shouldRender = false;
    // First fit must install DPR even if backing size matches the canvas default.
    if (
      this.canvas.width !== pixelWidth ||
      this.canvas.height !== pixelHeight ||
      !this.canvasConfigured ||
      this.canvasDevicePixelRatio !== ratio
    ) {
      // A backing-size change clears the canvas. Apply it with the gated paint
      // so a DPR change cannot erase a frame while synchronized output is open.
      this.pendingCanvasConfiguration = { width: pixelWidth, height: pixelHeight, ratio };
      this.forceFullRender = true;
      this.scrollbarDirty = true;
      shouldRender = true;
    } else {
      // A resize can return to the painted size before its queued frame runs.
      this.pendingCanvasConfiguration = null;
    }
    const grid = terminalGridSize(width, height, this.metrics, CONTENT_PADDING);
    this.mountHeight = height;
    // onResize is the only PTY resize channel, so the first successful fit must
    // notify even when the measured grid equals the 1x1 construction sentinel.
    if (
      grid.cols !== this.measuredCols ||
      grid.rows !== this.measuredRows ||
      !this.resizeNotified
    ) {
      this.measuredCols = grid.cols;
      this.measuredRows = grid.rows;
      this.notifyResize();
    }
    if (this.applyGrid()) shouldRender = true;
    // Repaint synchronously before paint so resize never stretches the old backing store.
    if (shouldRender || this.forceFullRender) this.renderFrame();
    return true;
  }

  /**
   * Other clients can share this PTY, so the server owns its grid. Drawing that grid
   * keeps wrapping and cursor positions in step with the PTY. Each axis is clamped to
   * this surface's own fit: the server's grid lags a local resize, and read-only
   * observers never constrain it.
   */
  setSharedGrid(grid: { readonly cols: number; readonly rows: number } | null): void {
    if (this.disposed) return;
    if (this.sharedGrid?.cols === grid?.cols && this.sharedGrid?.rows === grid?.rows) return;
    this.sharedGrid = grid;
    if (this.hasSize && this.applyGrid()) this.requestRender();
  }

  private applyGrid(): boolean {
    const cols = Math.min(this.sharedGrid?.cols ?? this.measuredCols, this.measuredCols);
    const rows = Math.min(this.sharedGrid?.rows ?? this.measuredRows, this.measuredRows);
    if (cols === this.cols && rows === this.rows) return false;
    this.cols = cols;
    this.rows = rows;
    this.core.resize(cols, rows, this.metrics.width, this.metrics.height);
    this.forceFullRender = true;
    this.scrollbarDirty = true;
    return true;
  }

  /**
   * The local grid reflows immediately, but the PTY only hears about settled
   * dimensions: notifying on every drag step makes the shell reprint its
   * prompt mid-drag, which reads as jitter.
   */
  private notifyResize(): void {
    this.resizeNotified = true;
    if (this.resizeNotifyTimer !== null) window.clearTimeout(this.resizeNotifyTimer);
    this.resizeNotifyTimer = window.setTimeout(() => {
      this.resizeNotifyTimer = null;
      if (!this.disposed) this.options.onResize(this.measuredCols, this.measuredRows);
    }, 150);
  }

  // Flush on release so immediate typing reaches a shell with the settled width.
  private readonly onWindowPointerRelease = () => {
    if (this.disposed || this.resizeNotifyTimer === null) return;
    this.fit();
    if (this.resizeNotifyTimer === null) return;
    window.clearTimeout(this.resizeNotifyTimer);
    this.resizeNotifyTimer = null;
    this.options.onResize(this.measuredCols, this.measuredRows);
  };

  focus(): void {
    if (this.disposed || !this.visible) return;
    this.input.focus({ preventScroll: true });
  }

  /** Claims before reading; later shortcut or native pastes supersede the pending read. */
  async pasteFromClipboard(
    readText: () => Promise<string>,
    isCurrent: () => boolean = () => true,
  ): Promise<void> {
    const token = ++this.pasteShortcutToken;
    const text = await readText();
    if (this.disposed || this.pasteShortcutToken !== token || !isCurrent()) return;
    this.pasteShortcutToken += 1;
    if (text.length === 0) return;
    const encoded = this.core.encodePaste(text);
    if (encoded.length > 0) this.options.onData(encoded);
  }

  // The terminal selection is the only browser-readable PRIMARY-like buffer.
  private pasteTerminalSelection(): void {
    const selection = this.getSelection();
    if (selection.length === 0) return;
    void this.pasteFromClipboard(() => Promise.resolve(selection));
  }

  hasSelection(): boolean {
    return this.core.selectionText().length > 0;
  }

  getSelection(): string {
    return this.core.selectionText();
  }

  /** An upper bound on the selection's size, read without formatting its text. */
  getSelectionCellCount(): number {
    const range = this.core.selectionRange();
    return range ? (Math.abs(range.end.y - range.start.y) + 1) * this.cols : 0;
  }

  selectAll(): void {
    this.linkActivationRequestId += 1;
    this.clearPrimedCopy();
    const range = this.core.selectAll();
    this.selectionAnchorScreen = range?.start ?? null;
    this.selectionEnd = range ? this.core.screenPointToViewport(range.end.x, range.end.y) : null;
    this.selectionMode = "cell";
    this.selectionBase = null;
    this.setSelectionAutoscroll(0);
    this.options.onSelectionChange();
    this.forceFullRender = true;
    this.requestRender();
  }

  getSelectionPosition(): GhosttySelectionPosition | null {
    // Ask Ghostty rather than the gesture's coordinates, which go stale once
    // output scrolls the selected rows (alternate screen, scrollback pruning).
    const range = this.hasSelection() ? this.core.selectionRange() : null;
    if (!range) return null;
    const { start, end } = range;
    const before = start.y < end.y || (start.y === end.y && start.x <= end.x);
    return before ? { start, end } : { start: end, end: start };
  }

  getSelectionEndClientRect(): { readonly right: number; readonly bottom: number } | null {
    const position = this.getSelectionPosition();
    if (!position) return null;
    const viewportEnd = this.core.screenPointToViewport(position.end.x, position.end.y);
    if (
      !viewportEnd ||
      viewportEnd.x < 0 ||
      viewportEnd.x >= this.cols ||
      viewportEnd.y < 0 ||
      viewportEnd.y >= this.rows
    ) {
      return null;
    }
    const bounds = this.canvas.getBoundingClientRect();
    return {
      right: bounds.left + CONTENT_PADDING + (viewportEnd.x + 1) * this.metrics.width,
      bottom: bounds.top + this.originY + (viewportEnd.y + 1) * this.metrics.height,
    };
  }

  clearSelection({ source = "user" }: { source?: "user" | "output" } = {}): void {
    if (source === "user") this.linkActivationRequestId += 1;
    this.clearPrimedCopy();
    this.core.clearSelection();
    this.selectionEnd = null;
    this.selectionAnchorScreen = null;
    this.selectionMode = "cell";
    this.selectionBase = null;
    this.setSelectionAutoscroll(0);
    this.options.onSelectionChange();
    // Selection highlights span rows Ghostty may not mark dirty for this change.
    this.forceFullRender = true;
    this.requestRender();
  }

  scrollToBottom(): void {
    this.core.scrollToBottom();
    this.forceFullRender = true;
    this.scrollbarDirty = true;
    this.requestRender();
  }

  isAtBottom(): boolean {
    return this.core.isViewportActive();
  }

  dispose(): void {
    if (this.disposed) return;
    this.disposed = true;
    this.clearHoveredLink();
    this.stopObservingResize();
    document.fonts.removeEventListener("loadingdone", this.onFontsLoaded);
    this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
    this.dprMedia = null;
    this.reducedMotionMedia?.removeEventListener("change", this.onReducedMotionChange);
    if (this.selectionScrollTimer !== null) window.clearInterval(this.selectionScrollTimer);
    if (this.resizeNotifyTimer !== null) {
      window.clearTimeout(this.resizeNotifyTimer);
      this.resizeNotifyTimer = null;
      this.options.onResize(this.measuredCols, this.measuredRows);
    }
    this.cancelRender();
    if (this.compositionSuppressionTimer !== null) {
      window.clearTimeout(this.compositionSuppressionTimer);
    }
    this.removeEvents();
    this.core.dispose();
    if (
      this.canvas.parentElement === this.mount ||
      this.input.parentElement === this.mount ||
      this.scrollbar.parentElement === this.mount
    ) {
      this.canvas.remove();
      this.input.remove();
      this.scrollbar.remove();
    }
  }

  private readonly onKeyDown = (event: KeyboardEvent) => {
    // A consumed repeat still owes the original encoded press a release.
    if (!event.repeat) this.encodedKeyCodes.delete(event.code);
    if (isTerminalAltGraphText(event) || !this.options.beforeKey(event)) return;
    // IME candidates belong to the textarea, even if the key also resembles
    // a local shortcut. Safari signals the initial composition with code 229.
    if (isTerminalCompositionKey(event, this.composing)) {
      return;
    }
    const mac = isMacPlatform(navigator.platform);
    const primaryModifier = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
    const selectAllShortcut =
      event.key.toLowerCase() === "a" &&
      primaryModifier &&
      !event.altKey &&
      (mac ? !event.shiftKey : event.shiftKey);
    if (selectAllShortcut) {
      event.preventDefault();
      event.stopPropagation();
      this.selectAll();
      return;
    }
    const pageHistory =
      event.shiftKey &&
      !event.altKey &&
      !event.ctrlKey &&
      !event.metaKey &&
      (event.key === "PageUp" || event.key === "PageDown");
    const jumpHistory =
      event.shiftKey &&
      !event.altKey &&
      primaryModifier &&
      (event.key === "Home" || event.key === "End");
    if ((pageHistory || jumpHistory) && !this.core.isAlternateScreen()) {
      const state = this.readScrollbarState();
      if (state !== null) {
        event.preventDefault();
        event.stopPropagation();
        const delta =
          event.key === "Home"
            ? -state.offset
            : event.key === "End"
              ? state.total - state.len - state.offset
              : Math.max(1, state.len) * (event.key === "PageUp" ? -1 : 1);
        this.scrollViewport(delta);
        return;
      }
    }
    if (isTerminalCopyShortcut(event) && this.hasSelection()) {
      // WebKit can omit copy without DOM selection. Ctrl+Shift+C and Ctrl+Insert need synthesized copy events.
      const selection = this.getSelection();
      this.primeCopy(selection);
      if (event.shiftKey || event.key.toLowerCase() === "insert") {
        event.preventDefault();
        document.execCommand("copy");
      } else {
        // Clear after plain non-mac Ctrl+C so the next press sends SIGINT.
        this.clearSelectionAfterCopy = !event.shiftKey && !isMacPlatform(navigator.platform);
        const clipboard = navigator.clipboard;
        if (typeof clipboard?.writeText === "function") {
          // Defer fallback writes until native copy can claim the token; browsers may omit copy events.
          const token = ++this.copyShortcutToken;
          void Promise.resolve().then(() => {
            if (this.disposed || this.copyShortcutToken !== token) return;
            void clipboard.writeText(selection).then(
              () => {
                if (this.disposed || this.copyShortcutToken !== token) return;
                if (this.clearSelectionAfterCopy) {
                  this.clearSelectionAfterCopy = false;
                  this.clearSelection();
                }
              },
              () => {
                if (this.copyShortcutToken === token) {
                  this.clearSelectionAfterCopy = false;
                }
              },
            );
          });
        }
      }
      return;
    }
    if (isTerminalPasteShortcut(event)) {
      const gesture = { code: event.code, readText: "" };
      this.pasteShortcutGesture = gesture;
      const clipboard = navigator.clipboard;
      if (typeof clipboard?.readText === "function") {
        // Keep native paste available if the read is denied. The token drops
        // a late read; the gesture drops a native duplicate when the read wins.
        const token = ++this.pasteShortcutToken;
        void clipboard.readText().then(
          (text) => {
            if (this.disposed || this.pasteShortcutToken !== token) return;
            this.pasteShortcutToken += 1;
            if (text.length === 0) return;
            if (this.pasteShortcutGesture === gesture) gesture.readText = text;
            this.options.onData(this.core.encodePaste(text));
          },
          () => {},
        );
      }
      return;
    }
    this.clearPrimedCopy();
    const data = this.core.encodeKey(event);
    if (data.length === 0) return;
    this.encodedKeyCodes.add(event.code);
    event.preventDefault();
    event.stopPropagation();
    this.options.onData(data);
  };

  private readonly onKeyUp = (event: KeyboardEvent) => {
    // macOS can omit V keyup while Command is held.
    if (
      event.code === this.pasteShortcutGesture?.code ||
      event.key === "Meta" ||
      event.key === "Control" ||
      event.key === "Shift"
    ) {
      this.pasteShortcutGesture = null;
    }
    if (!this.encodedKeyCodes.delete(event.code)) return;
    if (isTerminalCompositionKey(event, this.composing)) {
      return;
    }
    // Ghostty emits release codes only for Kitty report-event-types sessions.
    const data = this.core.encodeKey(event, "release");
    if (data.length === 0) return;
    event.preventDefault();
    event.stopPropagation();
    this.options.onData(data);
  };

  // A release elsewhere must not leave a press for a later app shortcut to inherit.
  private readonly onWindowKeyUp = (event: KeyboardEvent) => {
    if (event.composedPath().includes(this.input)) return;
    this.encodedKeyCodes.delete(event.code);
  };

  // A fresh press proves a release was missed; repeats can span a focus round trip.
  private readonly onWindowKeyDown = (event: KeyboardEvent) => {
    if (!event.repeat) this.encodedKeyCodes.delete(event.code);
  };

  private readonly onFocus = () => {
    this.focused = true;
    this.cursorOn = true;
    this.requestRender();
  };

  private readonly onBlur = () => {
    this.focused = false;
    this.pasteShortcutGesture = null;
    this.refreshHoveredLink();
    this.cursorOn = true;
    this.requestRender();
  };

  private readonly onDevicePixelRatioChange = () => {
    this.watchDevicePixelRatio();
    this.fit();
  };

  private watchDevicePixelRatio(): void {
    this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
    // Resolution queries track only their initial ratio; re-arm after every change.
    this.dprMedia = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
    this.dprMedia.addEventListener("change", this.onDevicePixelRatioChange);
  }

  private primeCopy(selection: string): void {
    this.primedCopySelection = selection;
    primeTerminalCopyInput(this.input, selection);
  }

  private clearPrimedCopy(): void {
    clearPrimedTerminalCopyInput(this.input, this.primedCopySelection);
    this.primedCopySelection = "";
  }

  private readonly onCopyEvent = (event: ClipboardEvent) => {
    const selection = this.hasSelection() ? this.getSelection() : this.input.value;
    // Menu Copy skips keydown; prime the textarea even without clipboardData for the native action.
    this.primeCopy(selection);
    const result = applyTerminalCopyEvent(selection, event.clipboardData);
    if (result.preventDefault) event.preventDefault();
    if (result.claimWriteFallback) {
      // Native copy wrote successfully; invalidate writeText so it cannot overwrite a later copy.
      this.copyShortcutToken += 1;
      if (this.clearSelectionAfterCopy) {
        this.clearSelectionAfterCopy = false;
        this.clearSelection();
      }
    }
  };

  private readonly onPaste = (event: ClipboardEvent) => {
    // Default textarea insertion would bypass bracketed-paste encoding through onInput.
    event.preventDefault();
    const data = event.clipboardData?.getData("text/plain") ?? "";
    if (data.length === 0) return;
    if (data === this.pasteShortcutGesture?.readText) {
      // The shortcut's clipboard read already sent this paste.
      this.pasteShortcutGesture = null;
      return;
    }
    // The native paste won the race with actual text; a pending clipboard read
    // must not double. An empty native paste leaves the read as the only path.
    this.pasteShortcutToken += 1;
    this.options.onData(this.core.encodePaste(data));
  };

  private readonly onCompositionStart = () => {
    this.clearPrimedCopy();
    this.clearCompositionInputSuppression();
    this.composing = true;
  };

  private readonly onCompositionEnd = (event: CompositionEvent) => {
    this.composing = false;
    const data = this.input.value || event.data;
    if (data.length > 0) this.options.onData(data);
    this.input.value = "";
    this.compositionInputToSuppress = data;
    this.compositionSuppressionTimer = window.setTimeout(() => {
      this.compositionInputToSuppress = null;
      this.compositionSuppressionTimer = null;
    }, 100);
  };

  private readonly onInput = (event: Event) => {
    const inputEvent = event as InputEvent;
    if (this.composing || inputEvent.isComposing) return;
    const data = this.input.value || inputEvent.data || "";
    if (data === this.compositionInputToSuppress && isTerminalCompositionCommitInput(inputEvent)) {
      this.clearCompositionInputSuppression();
      this.input.value = "";
      return;
    }
    this.clearCompositionInputSuppression();
    if (data.length > 0) this.options.onData(data);
    this.input.value = "";
  };

  private clearCompositionInputSuppression(): void {
    if (this.compositionSuppressionTimer !== null) {
      window.clearTimeout(this.compositionSuppressionTimer);
      this.compositionSuppressionTimer = null;
    }
    this.compositionInputToSuppress = null;
  }

  private readonly onPointerDown = (event: PointerEvent) => {
    this.linkActivationRequestId += 1;
    if (event.pointerType === "touch") {
      event.preventDefault();
      if (!event.isPrimary || this.touchScroll !== null) return;
      this.touchScroll = {
        pointerId: event.pointerId,
        startX: event.clientX,
        startY: event.clientY,
        lastY: event.clientY,
        remainder: 0,
        moved: false,
      };
      this.clearHoveredLink();
      this.canvas.setPointerCapture(event.pointerId);
      return;
    }
    this.focus();
    if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
      const button = ghosttyMouseButton(event.button);
      if (button === null) return;
      event.preventDefault();
      event.stopPropagation();
      this.clearHoveredLink("default");
      this.mouseReportingPointerId = event.pointerId;
      this.mouseReportingButton = button;
      this.sendMouse("press", button, event);
      this.canvas.setPointerCapture(event.pointerId);
      return;
    }
    if (event.button === 1 && isMiddleClickPastePlatform()) {
      // Keep pointerdown uncancelled so compatibility mousedown activates the split pane.
      this.pasteTerminalSelection();
      return;
    }
    if (event.button !== 0) return;
    const clickCount = this.recordSelectionClick(event);
    const link = this.linkAt(event.clientX, event.clientY, true);
    if (link && !event.shiftKey && clickCount === 1) {
      event.preventDefault();
      event.stopPropagation();
      this.linkActivationPointerId = event.pointerId;
      this.linkActivationLink = link;
      this.linkActivationValidation = this.validateLink(link.text);
      this.linkActivationOrigin = {
        x: event.clientX,
        y: event.clientY,
        clickCount,
      };
      this.canvas.setPointerCapture(event.pointerId);
      return;
    }
    this.clearHoveredLink();
    this.beginSelection(event, clickCount);
    this.canvas.setPointerCapture(event.pointerId);
  };

  private recordSelectionClick(
    event: Pick<PointerEvent, "clientX" | "clientY" | "timeStamp">,
  ): number {
    this.selectionClickSequence = advanceTerminalSelectionClickSequence(
      this.selectionClickSequence,
      event,
    );
    return this.selectionClickSequence.count;
  }

  private beginSelection(event: { clientX: number; clientY: number }, clickCount: number): void {
    const cell = this.cellAt(event.clientX, event.clientY);
    this.selectionMoved = false;
    this.selectionMode = clickCount >= 3 ? "line" : clickCount === 2 ? "word" : "cell";
    const range =
      this.selectionMode === "line"
        ? this.core.selectLine(cell.x, cell.y)
        : this.selectionMode === "word"
          ? this.core.selectWord(cell.x, cell.y)
          : null;
    if (range) {
      this.selectionBase = range.screen;
      this.selectionEnd = range.viewport.end;
      this.selectionAnchorScreen = range.screen.start;
      this.options.onSelectionChange();
    } else {
      this.selectionMode = "cell";
      this.selectionBase = null;
      this.selectionEnd = cell;
      const screen = this.core.viewportPointToScreen(cell.x, cell.y);
      this.selectionAnchorScreen = screen;
      if (screen) {
        this.core.setSelection({ ...screen, tag: 2 }, { ...screen, tag: 2 });
      } else {
        this.core.setSelection(cell, cell);
      }
    }
    this.forceFullRender = true;
    this.requestRender();
  }

  private readonly onPointerMove = (event: PointerEvent) => {
    if (event.pointerType === "touch") {
      const touch = this.touchScroll;
      if (touch?.pointerId !== event.pointerId) return;
      event.preventDefault();
      touch.moved ||=
        Math.hypot(event.clientX - touch.startX, event.clientY - touch.startY) >
        TERMINAL_LINK_DRAG_THRESHOLD_PX;
      if (!touch.moved) return;
      const delta = terminalWheelDeltaRows(
        { deltaY: touch.lastY - event.clientY, deltaMode: 0 },
        this.metrics.height,
        this.rows,
        touch.remainder,
      );
      touch.lastY = event.clientY;
      touch.remainder = delta.remainder;
      this.scrollRows(delta.rows, event);
      return;
    }
    if (this.linkActivationPointerId === event.pointerId) {
      const origin = this.linkActivationOrigin;
      if (
        origin === null ||
        Math.hypot(event.clientX - origin.x, event.clientY - origin.y) <=
          TERMINAL_LINK_DRAG_THRESHOLD_PX
      ) {
        return;
      }
      this.linkActivationPointerId = null;
      this.linkActivationLink = null;
      this.linkActivationValidation = undefined;
      this.linkActivationOrigin = null;
      this.clearHoveredLink();
      this.beginSelection(
        {
          clientX: origin.x,
          clientY: origin.y,
        },
        origin.clickCount,
      );
    }
    // Only DEC 1003 reports hover motion without a captured pressed button.
    const anyEventTracking = this.synchronizeMouseTrackingState();
    if (
      this.mouseReportingPointerId === event.pointerId ||
      shouldReportTerminalMouse(anyEventTracking, event)
    ) {
      event.preventDefault();
      this.hoverPointer = { x: event.clientX, y: event.clientY };
      this.setHoveredLink(null);
      this.canvas.style.cursor = "default";
      this.sendMouse("motion", this.buttonFromButtons(event.buttons), event);
      return;
    }
    this.lastMouseMotionData = "";
    if (!this.selectionAnchorScreen || !this.canvas.hasPointerCapture(event.pointerId)) {
      this.updateHoverCursor(event);
      return;
    }
    this.clearHoveredLink();
    this.selectionPointer = { x: event.clientX, y: event.clientY };
    const bounds = this.canvas.getBoundingClientRect();
    const top = Math.max(bounds.top, 0) + CONTENT_PADDING;
    const bottom = Math.min(bounds.bottom, window.innerHeight) - CONTENT_PADDING;
    this.setSelectionAutoscroll(terminalSelectionAutoscrollRows(event.clientY, top, bottom));
    const cell = this.cellAt(event.clientX, event.clientY);
    if (cell.x === this.selectionEnd?.x && cell.y === this.selectionEnd.y) return;
    this.extendSelectionTo(event.clientX, event.clientY);
  };

  private extendSelectionTo(clientX: number, clientY: number): void {
    if (this.selectionAnchorScreen === null) return;
    // Ghostty moves its selection with output; keep the drag on those rows too.
    const anchorScreen = this.core.selectionRange()?.start;
    if (!anchorScreen) return;
    const rowDelta = anchorScreen.y - this.selectionAnchorScreen.y;
    if (this.selectionBase && rowDelta !== 0) {
      const { start, end } = this.selectionBase;
      this.selectionBase = {
        start: { x: start.x, y: start.y + rowDelta },
        end: { x: end.x, y: end.y + rowDelta },
      };
    }
    const cell = this.cellAt(clientX, clientY);
    this.selectionMoved = true;
    this.selectionEnd = cell;
    const range =
      this.selectionMode === "line"
        ? this.core.selectLine(cell.x, cell.y)
        : this.selectionMode === "word"
          ? this.core.selectWord(cell.x, cell.y)
          : null;
    const cellScreen = this.core.viewportPointToScreen(cell.x, cell.y);
    if (cellScreen === null) return;
    const base = this.selectionBase;
    const beforeBase =
      base !== null &&
      (cellScreen.y < base.start.y ||
        (cellScreen.y === base.start.y && cellScreen.x < base.start.x));
    const anchor = base === null ? anchorScreen : beforeBase ? base.end : base.start;
    const end = range === null ? cellScreen : beforeBase ? range.screen.start : range.screen.end;
    this.selectionAnchorScreen = anchor;
    this.core.setSelection({ ...anchor, tag: 2 }, { ...end, tag: 2 });
    this.options.onSelectionChange();
    this.forceFullRender = true;
    this.requestRender();
  }

  private setSelectionAutoscroll(delta: number): void {
    this.selectionScrollDelta = delta;
    if (delta === 0) {
      if (this.selectionScrollTimer !== null) {
        window.clearInterval(this.selectionScrollTimer);
        this.selectionScrollTimer = null;
      }
      return;
    }
    if (this.selectionScrollTimer !== null) return;
    this.selectionScrollTimer = window.setInterval(() => {
      if (this.disposed || this.selectionScrollDelta === 0) return;
      this.scrollViewport(this.selectionScrollDelta);
      const pointer = this.selectionPointer;
      if (pointer) this.extendSelectionTo(pointer.x, pointer.y);
    }, 80);
  }

  private updateHoverCursor(event: PointerEvent): void {
    this.hoverPointer = { x: event.clientX, y: event.clientY };
    this.refreshHoveredLink();
  }

  private readonly onPointerLeave = () => {
    this.lastMouseMotionData = "";
    this.clearHoveredLink();
  };

  private clearHoveredLink(cursor = ""): void {
    this.hoverPointer = null;
    this.updateLinkHover(null);
    this.setHoveredLink(null);
    this.canvas.style.cursor = cursor;
  }

  private refreshHoveredLink(): void {
    const pointer = this.hoverPointer;
    const link = pointer ? this.findLinkAt(pointer.x, pointer.y) : null;
    this.updateLinkHover(link);
    this.setHoveredLink(link && this.options.canActivateLink?.(link.text) !== false ? link : null);
  }

  private updateLinkHover(link: TerminalLinkWithRange | null): void {
    if (!this.options.onLinkHover) return;
    if (link ? isSameTerminalLink(link, this.linkHoverCandidate) : this.linkHoverCandidate === null)
      return;
    this.linkHoverCandidate = link;
    if (this.linkHoverTimer !== null) {
      window.clearTimeout(this.linkHoverTimer);
      this.linkHoverTimer = null;
    }
    this.options.onLinkHover(null);
    if (link !== null) {
      const now = performance.now();
      let changedAt = 0;
      for (let y = link.range.start.y; y <= link.range.end.y; y++) {
        changedAt = Math.max(changedAt, this.linkRowStability[y]?.changedAt ?? now);
      }
      const delay = Math.max(0, TERMINAL_LINK_HOVER_DELAY_MS - (now - changedAt));
      if (delay === 0) {
        this.options.onLinkHover(link.text);
        return;
      }
      this.linkHoverTimer = window.setTimeout(() => {
        this.linkHoverTimer = null;
        this.options.onLinkHover?.(link.text);
      }, delay);
    }
  }

  private updateLinkRowStability(reset: boolean): void {
    if (!this.options.onLinkHover || !this.snapshot) return;
    if (reset) {
      this.updateLinkHover(null);
      this.linkRowStability = [];
    }
    const now = performance.now();
    this.snapshot.rowData.forEach((row, y) => {
      const previous = this.linkRowStability[y]?.row;
      if (
        !previous ||
        previous.text !== row.text ||
        previous.cells.length !== row.cells.length ||
        previous.isWrapContinuation !== row.isWrapContinuation ||
        previous.wrapsToNext !== row.wrapsToNext
      )
        this.linkRowStability[y] = { row, changedAt: now };
    });
    this.linkRowStability.length = this.snapshot.rows;
  }

  private setHoveredLink(link: TerminalLinkWithRange | null): void {
    const previous = this.hoveredLink;
    const unchanged =
      previous?.text === link?.text &&
      previous?.range.start.x === link?.range.start.x &&
      previous?.range.start.y === link?.range.start.y &&
      previous?.range.end.x === link?.range.end.x &&
      previous?.range.end.y === link?.range.end.y;
    this.canvas.style.cursor = link ? "pointer" : "";
    if (unchanged) return;
    this.hoveredLink = link;
    this.forceFullRender = true;
    this.requestRender();
  }

  private readonly onPointerUp = (event: PointerEvent) => {
    if (event.pointerType === "touch") {
      const touch = this.touchScroll;
      if (touch?.pointerId !== event.pointerId) return;
      this.touchScroll = null;
      event.preventDefault();
      if (this.canvas.hasPointerCapture(event.pointerId)) {
        this.canvas.releasePointerCapture(event.pointerId);
      }
      if (event.type === "pointercancel" || touch.moved) return;
      this.focus();
      if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
        this.sendMouse("press", ghosttyMouseButton(0), event);
        this.sendMouse("release", ghosttyMouseButton(0), event);
      } else {
        const link = this.linkAt(event.clientX, event.clientY, true);
        if (link) this.activateLink(link, event);
        else this.clearSelection();
      }
      return;
    }
    this.setSelectionAutoscroll(0);
    if (this.linkActivationPointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      const link = this.linkActivationLink;
      const validation = this.linkActivationValidation;
      this.linkActivationPointerId = null;
      this.linkActivationLink = null;
      this.linkActivationValidation = undefined;
      this.linkActivationOrigin = null;
      if (this.canvas.hasPointerCapture(event.pointerId)) {
        this.canvas.releasePointerCapture(event.pointerId);
      }
      if (event.type !== "pointercancel") {
        if (link && isSameTerminalLink(link, this.linkAt(event.clientX, event.clientY, true))) {
          this.activateLink(link, event, validation);
        }
      }
      return;
    }
    if (this.mouseReportingPointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      this.sendMouse("release", this.mouseReportingButton, event);
      this.mouseReportingPointerId = null;
      this.mouseReportingButton = null;
      if (this.canvas.hasPointerCapture(event.pointerId)) {
        this.canvas.releasePointerCapture(event.pointerId);
      }
      if (event.type === "pointercancel") {
        this.clearHoveredLink();
      } else {
        this.hoverPointer = { x: event.clientX, y: event.clientY };
        this.refreshHoveredLink();
      }
      return;
    }
    if (this.canvas.hasPointerCapture(event.pointerId)) {
      this.canvas.releasePointerCapture(event.pointerId);
    }
    if (event.button === 1 && isMiddleClickPastePlatform()) {
      event.preventDefault();
      return;
    }
    if (event.button !== 0) return;
    if (!this.selectionMoved && this.selectionMode === "cell") {
      this.clearSelection();
    }
    this.options.onSelectionChange();
  };

  private readonly onWheel = (event: WheelEvent) => {
    if (event.deltaY === 0) return;
    event.preventDefault();
    const delta = terminalWheelDeltaRows(
      event,
      this.metrics.height,
      this.rows,
      this.wheelRemainder,
    );
    this.wheelRemainder = delta.remainder;
    this.scrollRows(delta.rows, event);
  };

  private scrollRows(rows: number, event: MouseEvent): void {
    if (rows === 0) return;
    const magnitude = Math.abs(rows);
    if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
      const button = rows < 0 ? 4 : 5;
      for (let index = 0; index < magnitude; index += 1) {
        this.sendMouse("press", button, event);
      }
      return;
    }
    if (this.core.isAlternateScreen()) {
      // Alternate screens have no scrollback; send arrow keys like xterm.
      this.options.onData(terminalWheelArrowData(rows, this.core.isApplicationCursorKeys()));
      return;
    }
    this.scrollViewport(rows);
  }

  private readonly onMouseDown = (event: MouseEvent) => {
    if (event.button === 0 || (event.button === 1 && isMiddleClickPastePlatform())) {
      event.preventDefault();
    }
    this.focus();
  };

  // Chromium middle mouseup pastes PRIMARY into the focused textarea; prevent a second paste.
  private readonly onMouseUp = (event: MouseEvent) => {
    if (event.button === 1 && isMiddleClickPastePlatform()) event.preventDefault();
  };

  private readonly onContextMenu = (event: MouseEvent) => {
    if (shouldReportTerminalMouse(this.core.isMouseTracking(), event)) {
      event.preventDefault();
      return;
    }
    this.options.onContextMenu?.(event);
  };

  private readonly onScrollbarPointerDown = (event: PointerEvent) => {
    if (event.button !== 0) return;
    const state = this.readScrollbarState();
    if (state === null) return;
    const bounds = this.scrollbar.getBoundingClientRect();
    const geometry = terminalScrollbarGeometry(state, bounds.height);
    if (geometry === null) return;
    event.preventDefault();
    event.stopPropagation();
    this.scrollbarPointerId = event.pointerId;
    this.scrollbarPointerOffset =
      event.target === this.scrollbarThumb