diff --git a/e2e/terminal-ui.spec.ts b/e2e/terminal-ui.spec.ts index 8cd86b058..599da22d2 100644 --- a/e2e/terminal-ui.spec.ts +++ b/e2e/terminal-ui.spec.ts @@ -167,3 +167,49 @@ test("terminal ⌘F highlights active/inactive search matches and seeds with a n await expect(input).toHaveValue("gamma"); await expect(search.locator("[aria-live=polite]")).toHaveText(/\d+\/2/); }); + +test("terminal shows URLs in the link colour with an underline without hovering, in light and dark themes", async ({ + workbench: page, +}) => { + await page.evaluate(async () => { + const path = "/src/workbench/toolwindows/store.ts"; + const layout = await import(path); + layout.showToolWindow("terminal", true); + }); + const terminal = page.getByRole("region", { name: "Terminal", exact: true }); + await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused(); + await page.evaluate(async () => { + const path = "/src/features/terminal/runtime.ts"; + const { activeSession } = await import(path); + const s = activeSession()!; + s.term.reset(); + await new Promise((resolve) => + s.term.write( + " ➜ Local: http://localhost:5173/\r\n文档 https://example.com/docs 和 https://example.org/a\r\nno link\r\n", + resolve, + ), + ); + }); + const links = terminal.locator(".openidea-terminal-link"); + await expect(links).toHaveCount(3); + + for (const theme of ["light", "dark"]) { + const link = await page.evaluate(async (theme) => { + const path = "/src/workbench/theme.ts"; + const { setTheme } = await import(path); + await setTheme(theme); + const probe = document.createElement("span"); + probe.style.color = "var(--link)"; + document.body.append(probe); + const color = getComputedStyle(probe).color; + probe.remove(); + return color; + }, theme); + await expect(page.locator("html")).toHaveAttribute("data-theme", theme); + // The underline and the recoloured text both follow the theme's `--link`. + await expect(links.first()).toHaveCSS("border-bottom-color", link); + await expect(terminal.locator(".xterm-rows span", { hasText: /^h$/ }).first()).toHaveCSS("color", link); + if (process.env.OPENIDEA_TERMINAL_SHOTS) + await terminal.screenshot({ path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/terminal-links-${theme}.png` }); + } +}); diff --git a/src/features/terminal/embedded.test.ts b/src/features/terminal/embedded.test.ts index 68d527ccb..d140ade5f 100644 --- a/src/features/terminal/embedded.test.ts +++ b/src/features/terminal/embedded.test.ts @@ -55,7 +55,16 @@ vi.mock("@xterm/xterm", () => ({ })); vi.mock("@xterm/addon-fit", () => ({ FitAddon: class {} })); vi.mock("./session", () => ({ fontFor: () => ({}), LINK_HANDLER: {}, openExternal: vi.fn(), openFileLink: vi.fn() })); -vi.mock("./theme", () => ({ readTerminalTheme: () => ({}), remeasureWhenFontsLoad: vi.fn(), MIN_CONTRAST_RATIO: 1 })); +vi.mock("./theme", () => ({ + readTerminalTheme: () => ({}), + readLinkColor: () => "#000000", + remeasureWhenFontsLoad: vi.fn(), + MIN_CONTRAST_RATIO: 1, +})); +vi.mock("./linkHighlights", () => ({ + installLinkHighlights: () => ({ refresh() {}, update() {}, dispose() {} }), + xtermLink: vi.fn(), +})); vi.mock("./fit", () => ({ fitScheduler: () => ({ schedule() {}, cancel() {} }), settledResize: () => ({ resized() {}, cancel() {} }), diff --git a/src/features/terminal/embedded.ts b/src/features/terminal/embedded.ts index 3ef487afb..6b68355db 100644 --- a/src/features/terminal/embedded.ts +++ b/src/features/terminal/embedded.ts @@ -24,14 +24,18 @@ import { fitScheduler, settledResize } from "./fit"; import { watchWindowsPty, windowsPty } from "./windowsPty"; import { findTerminalLinks } from "./links"; import { LINK_HANDLER, fontFor, openExternal, openFileLink } from "./session"; -import { MIN_CONTRAST_RATIO, readTerminalTheme, remeasureWhenFontsLoad } from "./theme"; +import { MIN_CONTRAST_RATIO, readLinkColor, readTerminalTheme, remeasureWhenFontsLoad } from "./theme"; +import { installLinkHighlights, xtermLink, type LinkHighlightController } from "./linkHighlights"; -const live = new Set(); +const live = new Map(); /** Follows a theme change (called with the terminal sessions' own update). */ export function applyThemeToEmbedded() { const theme = readTerminalTheme(); - for (const t of live) t.options.theme = theme; + for (const [t, links] of live) { + t.options.theme = theme; + links.refresh(); + } } export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminalOptions): EmbeddedTerminal { @@ -78,7 +82,7 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal }); const fit = new FitAddon(); term.loadAddon(fit); - live.add(term); + live.set(term, installLinkHighlights(term, readLinkColor)); let lastSize = { cols: term.cols, rows: term.rows }; const processResize = settledResize((cols, rows) => { if (cols === lastSize.cols && rows === lastSize.rows) return; @@ -93,18 +97,15 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal provideLinks(y, callback) { const line = term.buffer.active.getLine(y - 1); const found = line ? findTerminalLinks(line.translateToString(true)) : []; - if (!found.length) return callback(undefined); + if (!line || !found.length) return callback(undefined); callback( - found.map((l) => ({ - text: l.text, - range: { start: { x: l.start + 1, y }, end: { x: l.end, y } }, - decorations: { underline: true, pointerCursor: true }, - activate: (event: MouseEvent) => { + found.map((l) => + xtermLink(term, line, y, l, (event) => { event.preventDefault(); if (l.kind === "url") void openExternal(l.url); else void openFileLink(l, opts.cwd ?? useProject.getState().project?.root ?? ""); - }, - })), + }), + ), ); }, }), @@ -149,6 +150,7 @@ export function createEmbeddedTerminal(host: HTMLElement, opts: EmbeddedTerminal removePaste(); removeDrop(); for (const d of disposables) d.dispose(); + live.get(term)?.dispose(); live.delete(term); term.dispose(); }, diff --git a/src/features/terminal/embeddedFit.test.ts b/src/features/terminal/embeddedFit.test.ts index 2812164d2..3bd894217 100644 --- a/src/features/terminal/embeddedFit.test.ts +++ b/src/features/terminal/embeddedFit.test.ts @@ -40,7 +40,16 @@ vi.mock("@xterm/addon-fit", () => ({ }, })); vi.mock("./session", () => ({ fontFor: () => ({}), LINK_HANDLER: {}, openExternal: vi.fn(), openFileLink: vi.fn() })); -vi.mock("./theme", () => ({ readTerminalTheme: () => ({}), remeasureWhenFontsLoad: vi.fn(), MIN_CONTRAST_RATIO: 1 })); +vi.mock("./theme", () => ({ + readTerminalTheme: () => ({}), + readLinkColor: () => "#000000", + remeasureWhenFontsLoad: vi.fn(), + MIN_CONTRAST_RATIO: 1, +})); +vi.mock("./linkHighlights", () => ({ + installLinkHighlights: () => ({ refresh() {}, update() {}, dispose() {} }), + xtermLink: vi.fn(), +})); beforeEach(() => { vi.useFakeTimers(); diff --git a/src/features/terminal/linkHighlights.test.ts b/src/features/terminal/linkHighlights.test.ts new file mode 100644 index 000000000..1c22eac9f --- /dev/null +++ b/src/features/terminal/linkHighlights.test.ts @@ -0,0 +1,166 @@ +// @vitest-environment jsdom +import { Terminal, type IDecoration, type IDecorationOptions } from "@xterm/xterm"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { findTerminalLinks } from "./links"; +import { installLinkHighlights, xtermLink } from "./linkHighlights"; +import { buildLinkColor } from "./theme"; + +const mock = vi.hoisted(() => ({ highlightHyperlinks: true })); +vi.mock("@/platform/workflowSettings", () => ({ + workflowSettings: () => ({ terminal: { highlightHyperlinks: mock.highlightHyperlinks } }), +})); + +const write = (term: Terminal, data: string) => new Promise((resolve) => term.write(data, resolve)); + +describe("terminal link highlights", () => { + const terms: Terminal[] = []; + const created: Array<{ options: IDecorationOptions; decoration: IDecoration }> = []; + + const createTerm = (cols = 60, rows = 5) => { + window.matchMedia ??= (() => + ({ + matches: false, + addListener() {}, + removeListener() {}, + addEventListener() {}, + removeEventListener() {}, + }) as unknown as MediaQueryList) as typeof window.matchMedia; + const host = document.createElement("div"); + document.body.appendChild(host); + const term = new Terminal({ allowProposedApi: true, cols, rows, scrollback: 500 }); + term.open(host); + const register = term.registerDecoration.bind(term); + term.registerDecoration = (options) => { + const decoration = register(options); + if (decoration) created.push({ options, decoration }); + return decoration; + }; + terms.push(term); + return term; + }; + + /** `{ line, x, width }` of every live link decoration, top to bottom. */ + const live = () => + created + .filter((d) => !d.decoration.isDisposed) + .map(({ options: o }) => ({ line: o.marker.line, x: o.x, width: o.width, fg: o.foregroundColor })) + .sort((a, b) => a.line - b.line || (a.x ?? 0) - (b.x ?? 0)); + + beforeEach(() => { + mock.highlightHyperlinks = true; + created.length = 0; + }); + afterEach(() => { + while (terms.length) terms.pop()!.dispose(); + document.body.replaceChildren(); + }); + + it("colours every visible URL without hovering, in cell columns", async () => { + const term = createTerm(); + const links = installLinkHighlights(term, () => "#112233"); + // The reporter's case: a dev server banner, plus a CJK prefix (two cells per glyph) and two URLs on one row. + await write( + term, + " ➜ Local: http://localhost:5173/\r\n访问 https://a.dev 或 https://b.dev/x.\r\nno links here", + ); + links.update(); + expect(live()).toEqual([ + { line: 0, x: 14, width: 22, fg: "#112233" }, + { line: 1, x: 5, width: 13, fg: "#112233" }, + { line: 1, x: 22, width: 15, fg: "#112233" }, + ]); + links.dispose(); + expect(live()).toEqual([]); + }); + + it("does nothing while Highlight hyperlinks is off, and follows the toggle on refresh", async () => { + mock.highlightHyperlinks = false; + const term = createTerm(); + const links = installLinkHighlights(term, () => "#112233"); + await write(term, "https://example.com"); + links.update(); + expect(live()).toEqual([]); + mock.highlightHyperlinks = true; + links.refresh(); + links.update(); + expect(live()).toHaveLength(1); + mock.highlightHyperlinks = false; + links.update(); + expect(live()).toEqual([]); + }); + + it("only decorates rows near the viewport as output scrolls", async () => { + const term = createTerm(60, 5); + const links = installLinkHighlights(term, () => "#112233"); + for (let i = 0; i < 100; i++) { + await write(term, `row ${i} https://example.com/${i}\r\n`); + links.update(); + } + const top = term.buffer.active.viewportY; + expect(live().every((d) => d.line >= top - term.rows && d.line < top + 2 * term.rows)).toBe(true); + expect(live().length).toBeLessThanOrEqual(3 * term.rows); + // Every visible URL row is still highlighted. + for (let y = top; y < top + term.rows; y++) { + if (term.buffer.active.getLine(y)!.translateToString(true).includes("https://")) + expect(live().some((d) => d.line === y)).toBe(true); + } + }); + + it("drops a highlight when its line is overwritten", async () => { + const term = createTerm(); + const links = installLinkHighlights(term, () => "#112233"); + await write(term, "https://example.com"); + links.update(); + expect(live()).toHaveLength(1); + await write(term, "\r\x1b[2Kdone"); + links.update(); + expect(live()).toEqual([]); + }); + + it("clears in the alternate buffer and comes back after it", async () => { + const term = createTerm(); + const links = installLinkHighlights(term, () => "#112233"); + await write(term, "https://example.com\r\n"); + links.update(); + expect(live()).toHaveLength(1); + await write(term, "\x1b[?1049hhttps://inside.vim"); + links.update(); + expect(live()).toEqual([]); + await write(term, "\x1b[?1049l"); + links.update(); + expect(live()).toHaveLength(1); + }); + + it("redraws with the new colour after a theme change", async () => { + const term = createTerm(); + let color = "#112233"; + const links = installLinkHighlights(term, () => color); + await write(term, "https://example.com"); + links.update(); + color = "#445566"; + links.refresh(); + links.update(); + expect(live().map((d) => d.fg)).toEqual(["#445566"]); + }); + + it("builds click ranges in cells and skips the hover underline on highlighted URLs", async () => { + const term = createTerm(); + await write(term, "访问 https://a.dev src/main.rs:10"); + const line = term.buffer.active.getLine(0)!; + const [url, file] = findTerminalLinks(line.translateToString(true)).map((l) => + xtermLink(term, line, 1, l, () => {}), + ); + expect(url!.range).toEqual({ start: { x: 6, y: 1 }, end: { x: 18, y: 1 } }); + expect(url!.decorations).toEqual({ underline: false, pointerCursor: true }); + expect(file!.decorations).toEqual({ underline: true, pointerCursor: true }); + mock.highlightHyperlinks = false; + expect(xtermLink(term, line, 1, findTerminalLinks("https://a.dev")[0]!, () => {}).decorations?.underline).toBe( + true, + ); + }); + + it("reads the link colour from the theme's --link token, else the accent", () => { + expect(buildLinkColor((n) => ({ "--link": "#71a1fe", "--accent": "#000000" })[n] ?? "")).toBe("#71a1fe"); + expect(buildLinkColor((n) => (n === "--accent" ? "rgb(1, 2, 3)" : ""))).toBe("#010203"); + }); +}); diff --git a/src/features/terminal/linkHighlights.ts b/src/features/terminal/linkHighlights.ts new file mode 100644 index 000000000..44f8757ee --- /dev/null +++ b/src/features/terminal/linkHighlights.ts @@ -0,0 +1,131 @@ +/** + * Always-on link styling for URLs in the terminal (Settings › Tools › Terminal › + * Highlight hyperlinks), as in IntelliJ's terminal: link colour + underline without hovering. + * + * - One xterm decoration per visible URL: `foregroundColor` recolours the cells, the + * decoration element (`LINK_DECORATION_CLASS`) draws the underline. + * - Scans only the viewport, coalesced to one pass per animation frame; markers keep + * decorations on their line while it scrolls, and ones a screen beyond the viewport are dropped. + * - Off in the alternate buffer (`vim`, `less`): xterm decorations only live in the normal one. + */ +import type { IBufferLine, IDecoration, IDisposable, ILink, IMarker, Terminal } from "@xterm/xterm"; +import { workflowSettings } from "@/platform/workflowSettings"; +import { stringOffsetToCol } from "./highlight"; +import { findTerminalLinks, type TerminalLink } from "./links"; + +export const LINK_DECORATION_CLASS = "openidea-terminal-link"; + +/** 0-based cell columns `[start, end)` of `link` (string offsets) in `line`; wide CJK glyphs take two cells. */ +export function linkCells(line: IBufferLine, link: TerminalLink): { start: number; end: number } { + return { start: stringOffsetToCol(line, link.start), end: stringOffsetToCol(line, link.end) }; +} + +const enabled = () => workflowSettings().terminal.highlightHyperlinks; +const highlighted = (term: Terminal) => enabled() && term.buffer.active.type === "normal"; + +/** The xterm link for `link` on buffer row `y` (1-based), for a link provider. */ +export function xtermLink( + term: Terminal, + line: IBufferLine, + y: number, + link: TerminalLink, + activate: (event: MouseEvent) => void, +): ILink { + const { start, end } = linkCells(line, link); + return { + text: link.text, + range: { start: { x: start + 1, y }, end: { x: end, y } }, + // A highlighted URL is already underlined; a second hover underline would sit just above it. + decorations: { underline: link.kind !== "url" || !highlighted(term), pointerCursor: true }, + activate, + }; +} + +export interface LinkHighlightController extends IDisposable { + /** Drops every decoration and redraws, e.g. after a theme or setting change. */ + refresh(): void; + /** Runs the pending viewport pass now. */ + update(): void; +} + +interface Entry { + marker: IMarker; + decoration: IDecoration; + start: number; + end: number; +} + +export function installLinkHighlights(term: Terminal, color: () => string): LinkHighlightController { + const entries = new Set(); + let rafId = 0; + let disposed = false; + + const drop = (e: Entry) => { + entries.delete(e); + e.decoration.dispose(); + e.marker.dispose(); + }; + const clear = () => entries.forEach(drop); + + const update = () => { + if (rafId) cancelAnimationFrame(rafId); + rafId = 0; + if (disposed) return; + if (!highlighted(term)) return clear(); + const buf = term.buffer.active; + const top = buf.viewportY; + const bottom = top + term.rows; + const byLine = new Map(); + for (const e of entries) { + const y = e.marker.line; + if (e.marker.isDisposed || y < top - term.rows || y >= bottom + term.rows) drop(e); + else byLine.set(y, [...(byLine.get(y) ?? []), e]); + } + let fg: string | undefined; + // Rescans every visible row per pass (one regex pass per row); cache per line if profiles show the cost. + for (let y = top; y < bottom; y++) { + const line = buf.getLine(y); + const want = line + ? findTerminalLinks(line.translateToString(true)) + .filter((l) => l.kind === "url") + .map((l) => linkCells(line, l)) + .filter((c) => c.end > c.start) + : []; + const have = byLine.get(y) ?? []; + if (have.length === want.length && have.every((e, i) => e.start === want[i]!.start && e.end === want[i]!.end)) + continue; + have.forEach(drop); + for (const { start, end } of want) { + const marker = term.registerMarker(y - (buf.baseY + buf.cursorY)); + if (!marker) continue; + fg ??= color(); + const decoration = term.registerDecoration({ marker, x: start, width: end - start, foregroundColor: fg }); + if (!decoration) { + marker.dispose(); + continue; + } + decoration.onRender((el) => el.classList.add(LINK_DECORATION_CLASS)); + entries.add({ marker, decoration, start, end }); + } + } + }; + + const schedule = () => { + if (!rafId && !disposed) rafId = requestAnimationFrame(update); + }; + const subs = [term.onRender(schedule), term.onScroll(schedule), term.buffer.onBufferChange(schedule)]; + + return { + refresh() { + clear(); + schedule(); + }, + update, + dispose() { + disposed = true; + if (rafId) cancelAnimationFrame(rafId); + subs.forEach((s) => s.dispose()); + clear(); + }, + }; +} diff --git a/src/features/terminal/session.ts b/src/features/terminal/session.ts index 344968b2b..99d3039f1 100644 --- a/src/features/terminal/session.ts +++ b/src/features/terminal/session.ts @@ -19,6 +19,7 @@ import { watchWindowsPty, windowsPty } from "./windowsPty"; import { installTerminalDrop } from "./drop"; import { installDomRowCache } from "./domRowCache"; import { installSelectionHighlights, type SelectionHighlightController } from "./highlight"; +import { installLinkHighlights, xtermLink, type LinkHighlightController } from "./linkHighlights"; import { installTerminalPaste, pasteTerminalClipboard } from "./paste"; import { ImeCommitGate } from "./imeCommit"; import { ownTerminalInput } from "./imeInput"; @@ -30,6 +31,7 @@ import { usePlatform } from "@/platform/platformInfo"; import { workflowSettings, type TerminalSettingsValid } from "@/platform/workflowSettings"; import { editorPrefs } from "@/platform/editorSettings"; import { + readLinkColor, readSearchDecorations, readTerminalTheme, remeasureWhenFontsLoad, @@ -213,6 +215,7 @@ export class TerminalSession { private selectingSearchMatch = false; private searchSelection = false; private readonly selectionHighlights: SelectionHighlightController; + private readonly linkHighlights: LinkHighlightController; private opts: SessionOptions; private snapshot: SessionSnapshot; private ptyId: TerminalId | null = null; @@ -368,7 +371,8 @@ export class TerminalSession { this.selectionHighlights = installSelectionHighlights(this.term, { isSearchSelection: () => this.searchSelection, }); - this.disposables.push(this.selectionHighlights); + this.linkHighlights = installLinkHighlights(this.term, readLinkColor); + this.disposables.push(this.selectionHighlights, this.linkHighlights); this.disposables.push( { dispose: installTerminalPaste(this.host, (text) => this.paste(text), this.clipboardTarget) }, { dispose: installTerminalDrop(this.host, (text) => this.paste(text)) }, @@ -437,6 +441,7 @@ export class TerminalSession { o.cursorBlink = t.cursorBlink; o.macOptionIsMeta = t.optionAsMeta; this.selectionHighlights.refresh(); + this.linkHighlights.refresh(); this.scheduleFit(); } @@ -479,17 +484,14 @@ export class TerminalSession { const text = line.translateToString(true); const found = findTerminalLinks(text); if (found.length === 0) return undefined; - return found.map((l) => ({ - text: l.text, - range: { start: { x: l.start + 1, y }, end: { x: l.end, y } }, - decorations: { underline: true, pointerCursor: true }, - activate: (event: MouseEvent) => { + return found.map((l) => + xtermLink(this.term, line, y, l, (event) => { // Plain click opens; a click that ends a drag-selection never reaches here. event.preventDefault(); if (l.kind === "url") void openExternal(l.url); else void openFileLink(l, this.snapshot.cwd); - }, - })); + }), + ); } /** Moves the host into `container` and fits / starts once the pane has a size. */ @@ -838,6 +840,7 @@ export class TerminalSession { applyTheme() { this.term.options.theme = readTerminalTheme(); this.searchDecorations = null; + this.linkHighlights.refresh(); } /** Finds `query` (highlighting every match); `incremental` keeps the current match while typing. */ diff --git a/src/features/terminal/theme.ts b/src/features/terminal/theme.ts index 8a230f72c..3d1a1b035 100644 --- a/src/features/terminal/theme.ts +++ b/src/features/terminal/theme.ts @@ -122,6 +122,15 @@ export function buildSearchDecorations(read: TokenReader) { }; } +/** Terminal URL colour (`#rrggbb` for xterm decorations): the theme's `--link`, else the accent. */ +export function buildLinkColor(read: TokenReader): string { + return toHex(parseColor(read("--link")) ?? parseColor(read("--accent")) ?? parseColor(FALLBACK["--accent"]!)!); +} + +export function readLinkColor() { + return buildLinkColor(documentTokenReader()); +} + export function readSearchDecorations() { return buildSearchDecorations(documentTokenReader()); } diff --git a/src/features/terminal/xtermInput.css b/src/features/terminal/xtermInput.css index c02c6bd20..f7d2c6db7 100644 --- a/src/features/terminal/xtermInput.css +++ b/src/features/terminal/xtermInput.css @@ -13,3 +13,10 @@ position: relative; z-index: 1; } + +/* Always-on underline for highlighted URLs (linkHighlights); the decoration's foreground colour tints the text. */ +.xterm .xterm-decoration.openidea-terminal-link { + box-sizing: border-box; + border-bottom: 1px solid var(--link, var(--accent)); + pointer-events: none; +}