diff --git a/src/renderer/src/components/TerminalPane.tsx b/src/renderer/src/components/TerminalPane.tsx index 9af06aa9f..23f39a8f3 100644 --- a/src/renderer/src/components/TerminalPane.tsx +++ b/src/renderer/src/components/TerminalPane.tsx @@ -35,6 +35,7 @@ import { resolvePaneStyleOptions, resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' +import { TerminalLinkDetector } from '@/lib/terminal-link-detector' type PtyTransport = { connect: (options: { @@ -363,6 +364,8 @@ export default function TerminalPane({ }: TerminalPaneProps): React.JSX.Element { const containerRef = useRef(null) const resttyRef = useRef(null) + const linkDetectorsRef = useRef>(new Map()) + const cellSizeRef = useRef<{ w: number; h: number }>({ w: 0, h: 0 }) const contextPaneIdRef = useRef(null) const wasActiveRef = useRef(false) const expandedPaneIdRef = useRef(null) @@ -619,6 +622,11 @@ export default function TerminalPane({ } restty.closePane(id) } + + // Link detector for this pane + const linkDetector = new TerminalLinkDetector() + linkDetectorsRef.current.set(id, linkDetector) + return { renderer: 'auto', fontSize: currentSettings?.terminalFontSize ?? 14, @@ -632,7 +640,17 @@ export default function TerminalPane({ onPtySpawn, onBell ) as never, - fontSources: buildTerminalFontSources(currentSettings?.terminalFontFamily ?? 'SF Mono') + fontSources: buildTerminalFontSources(currentSettings?.terminalFontFamily ?? 'SF Mono'), + callbacks: { + onGridSize: (cols: number, rows: number) => linkDetector.setGridSize(cols, rows), + onCellSize: (cellW: number, cellH: number) => { + cellSizeRef.current = { w: cellW, h: cellH } + } + }, + beforeRenderOutput: (payload: { text: string; source: string }) => { + if (payload.source === 'pty') linkDetector.feed(payload.text) + return payload.text + } } }, onPaneCreated: async (pane) => { @@ -643,7 +661,9 @@ export default function TerminalPane({ pane.canvas.focus({ preventScroll: true }) queueResizeAll(true) }, - onPaneClosed: () => {}, + onPaneClosed: (pane) => { + linkDetectorsRef.current.delete(pane.id) + }, onActivePaneChange: () => { if (shouldPersistLayout) persistLayoutSnapshot() }, @@ -687,6 +707,7 @@ export default function TerminalPane({ restoreExpandedLayout() restty.destroy() resttyRef.current = null + linkDetectorsRef.current.clear() setTabPaneExpanded(tabId, false) setTabCanExpandPane(tabId, false) } @@ -845,6 +866,95 @@ export default function TerminalPane({ return () => window.removeEventListener('keydown', onKeyDown, { capture: true }) }, [isActive]) + // Ctrl+Click to open terminal links and Ctrl+hover for pointer cursor + useEffect(() => { + if (!isActive) return + const container = containerRef.current + if (!container) return + + const resolveClickPane = (target: Node) => { + const restty = resttyRef.current + if (!restty) return null + return restty.getPanes().find((pane) => pane.container.contains(target)) ?? null + } + + const getCellAtEvent = (e: MouseEvent, canvas: HTMLCanvasElement) => { + const { w, h } = cellSizeRef.current + if (!w || !h) return null + const rect = canvas.getBoundingClientRect() + const x = e.clientX - rect.left + const y = e.clientY - rect.top + return { col: Math.floor(x / w), row: Math.floor(y / h) } + } + + const onPointerUp = (e: PointerEvent): void => { + if (e.button !== 0) return + if (!e.ctrlKey && !e.metaKey) return + if (!(e.target instanceof Node)) return + + const pane = resolveClickPane(e.target) + if (!pane) return + const cell = getCellAtEvent(e, pane.canvas) + if (!cell) return + + const detector = linkDetectorsRef.current.get(pane.id) + const url = detector?.getLinkAt(cell.row, cell.col) + if (url) { + e.preventDefault() + e.stopPropagation() + window.api.shell.openExternal(url) + } + } + + const onPointerMove = (e: PointerEvent): void => { + if (!e.ctrlKey && !e.metaKey) { + // Restore cursor when Ctrl is released while moving + for (const canvas of container.querySelectorAll('canvas')) { + if ((canvas as HTMLCanvasElement).style.cursor === 'pointer') { + ;(canvas as HTMLCanvasElement).style.cursor = '' + } + } + return + } + if (!(e.target instanceof Node)) return + + const pane = resolveClickPane(e.target) + if (!pane) return + const cell = getCellAtEvent(e, pane.canvas) + if (!cell) return + + const detector = linkDetectorsRef.current.get(pane.id) + const hasLink = detector?.hasLinkAt(cell.row, cell.col) ?? false + pane.canvas.style.cursor = hasLink ? 'pointer' : '' + } + + const onKeyDown = (e: KeyboardEvent): void => { + if (e.key === 'Control' || e.key === 'Meta') { + // Trigger a cursor check when Ctrl/Cmd is pressed + // (onPointerMove won't fire until the mouse moves) + } + } + + const onKeyUp = (e: KeyboardEvent): void => { + if (e.key === 'Control' || e.key === 'Meta') { + for (const canvas of container.querySelectorAll('canvas')) { + if ((canvas as HTMLCanvasElement).style.cursor === 'pointer') { + ;(canvas as HTMLCanvasElement).style.cursor = '' + } + } + } + } + + container.addEventListener('pointerup', onPointerUp, { capture: true }) + container.addEventListener('pointermove', onPointerMove) + window.addEventListener('keyup', onKeyUp) + return () => { + container.removeEventListener('pointerup', onPointerUp, { capture: true }) + container.removeEventListener('pointermove', onPointerMove) + window.removeEventListener('keyup', onKeyUp) + } + }, [isActive]) + const resolveMenuPane = () => { const restty = resttyRef.current if (!restty) return null diff --git a/src/renderer/src/lib/terminal-link-detector.ts b/src/renderer/src/lib/terminal-link-detector.ts new file mode 100644 index 000000000..5353354d7 --- /dev/null +++ b/src/renderer/src/lib/terminal-link-detector.ts @@ -0,0 +1,107 @@ +/** + * Detects URLs in terminal output by tracking PTY data and maintaining + * a simplified screen buffer. Supports Ctrl+Click to open links. + */ + +// Matches http(s) URLs and bare domain-style URLs (e.g. github.com/foo) +const URL_RE = + /https?:\/\/[^\s<>"'`)\]},;]+|(?:[\w-]+\.)+(?:com|org|net|io|dev|app|co|me|sh|cc|info|xyz|ai)(?:\/[^\s<>"'`)\]},;]*)*/g + +// Strips most common ANSI escape sequences (SGR, cursor, erase, OSC, etc.) +const ANSI_RE = + // eslint-disable-next-line no-control-regex + /\x1b\[[0-9;]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[()][AB012]|\x1b[>=<]|\x1b\x1b|\x1b./g + +export type TerminalLink = { url: string; col: number; len: number } + +export class TerminalLinkDetector { + private lines: string[] = [] + private cols = 80 + private rows = 24 + private cursorRow = 0 + + /** Update grid dimensions (call on terminal resize). */ + setGridSize(cols: number, rows: number): void { + this.cols = cols + this.rows = rows + // Resize line buffer to match visible rows + while (this.lines.length < rows) this.lines.push('') + if (this.lines.length > rows) this.lines.length = rows + if (this.cursorRow >= rows) this.cursorRow = rows - 1 + } + + /** Feed a chunk of raw PTY output. */ + feed(data: string): void { + // Strip ANSI escape sequences to get visible text + const clean = data.replace(ANSI_RE, '') + + for (let i = 0; i < clean.length; i++) { + const ch = clean[i] + + if (ch === '\n') { + this.cursorRow++ + if (this.cursorRow >= this.rows) { + // Scroll: shift lines up + this.lines.shift() + this.lines.push('') + this.cursorRow = this.rows - 1 + } + continue + } + + if (ch === '\r') { + // Carriage return: overwrite current line from start + this.lines[this.cursorRow] = '' + continue + } + + // eslint-disable-next-line no-control-regex + if (ch.charCodeAt(0) < 0x20) continue // skip other control chars + + // Append character to current line + this.lines[this.cursorRow] = (this.lines[this.cursorRow] ?? '') + ch + } + } + + /** Clear the screen buffer (e.g. on Ctrl+L / clear). */ + clear(): void { + this.lines = Array.from({ length: this.rows }, () => '') + this.cursorRow = 0 + } + + /** Find all URLs in the line at the given row. */ + getLinksAtRow(row: number): TerminalLink[] { + const line = this.lines[row] + if (!line) return [] + + const links: TerminalLink[] = [] + let match: RegExpExecArray | null + URL_RE.lastIndex = 0 + while ((match = URL_RE.exec(line)) !== null) { + let url = match[0] + // Strip trailing punctuation that's unlikely part of the URL + url = url.replace(/[.,;:!?)]+$/, '') + // Ensure http(s) prefix for bare domains + if (!url.startsWith('http://') && !url.startsWith('https://')) { + url = 'https://' + url + } + links.push({ url, col: match.index, len: match[0].length }) + } + return links + } + + /** Find the URL at a specific row/col, or null. */ + getLinkAt(row: number, col: number): string | null { + for (const link of this.getLinksAtRow(row)) { + if (col >= link.col && col < link.col + link.len) { + return link.url + } + } + return null + } + + /** Check if there is any URL at the given row/col. */ + hasLinkAt(row: number, col: number): boolean { + return this.getLinkAt(row, col) !== null + } +} diff --git a/src/renderer/src/main.tsx b/src/renderer/src/main.tsx index 243cf3125..0f229d687 100644 --- a/src/renderer/src/main.tsx +++ b/src/renderer/src/main.tsx @@ -13,49 +13,6 @@ function applySystemTheme(): void { applySystemTheme() window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applySystemTheme) -// --------------------------------------------------------------------------- -// Ctrl+Click to open terminal links -// --------------------------------------------------------------------------- -// Restty (the terminal renderer) detects URLs in terminal output and calls -// window.open() on any left-click over a detected link. In Electron, -// window.open with "noopener,noreferrer" may not properly trigger -// setWindowOpenHandler. We override window.open to: -// 1. Route http/https URLs through shell.openExternal (reliable in Electron) -// 2. Only open when Ctrl (Linux/Windows) or Cmd (macOS) was held — matching -// the standard Ctrl+Click-to-open-link UX in terminals like VS Code. -// --------------------------------------------------------------------------- -let lastPointerModifiers = { ctrlKey: false, metaKey: false } -window.addEventListener( - 'pointerup', - (e) => { - lastPointerModifiers = { ctrlKey: e.ctrlKey, metaKey: e.metaKey } - }, - { capture: true } -) - -const originalWindowOpen = window.open.bind(window) -window.open = function ( - url?: string | URL, - target?: string, - features?: string -): WindowProxy | null { - if (url) { - const urlStr = url.toString() - try { - const parsed = new URL(urlStr) - if (parsed.protocol === 'http:' || parsed.protocol === 'https:') { - if (lastPointerModifiers.ctrlKey || lastPointerModifiers.metaKey) { - window.api.shell.openExternal(urlStr) - } - return null - } - } catch { - // not a valid URL — fall through to original - } - } - return originalWindowOpen(url, target, features) -} as typeof window.open - createRoot(document.getElementById('root')!).render(