Skip to content

Visual Studio Code, rebuilt in Rust

Rust
23.6 KB
Raw Blame
//! terminalContrib/links: Cmd+click (the `editor.multiCursorModifier` opposite) on a URL or a file path in the
//! terminal opens it, URLs through terminalUriLinkDetector.ts and paths with their line and column suffix through
//! terminalLocalLinkDetector.ts. Links are read from the whole wrapped line; the hovered link is underlined while
//! the modifier is down and shows terminalLinkManager.ts's hover ("Follow link (cmd + click)"). Links of
//! `window.registerTerminalLinkProvider` come first: `_registerStandardLinkProviders` registers them before the
//! builtin detectors, and xterm takes the first provider's link at the pointer.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use ghostty_vt::{Column, Flags, Line};
use gpui::{Bounds, Context, Modifiers, Window, point, px, size};
use serde_json::{Value, json};

use super::Workbench;
use super::hover::{HoverContent, HoverOptions};
use super::terminal_view::grid;
use super::model_events::Cursor;
use crate::editor::Reveal;
use crate::editor::marker_decorations::validate;
use crate::editor::{Selection, VerticalReveal};
use crate::link_computer::compute_links;
use crate::terminal::link_parsing::detect_links;
use crate::workbench::editor_options::MULTI_CURSOR_MODIFIER;

/// The element id name of a terminal link's hover.
pub(super) const TERMINAL_LINK_HOVER: &str = "terminal-link";

/// What a click in the terminal opens.
#[derive(Clone, Debug, PartialEq)]
pub(super) enum TerminalLink {
    Url(String),
    File { path: PathBuf, line: Option<u32>, column: Option<u32> },
    /// mainThreadTerminalService.ts `ExtensionTerminalLinkProvider`: activating calls `$activateLink`.
    Extension { instance: u32, id: u64, text: String, label: Option<String> },
}

/// terminalExternalLinkDetector.ts `maxLinkLength`: longer lines are not sent to the extensions.
const MAX_EXTENSION_LINE_LENGTH: usize = 2000;

/// `$startLinkProvider` and the links the host answered `$provideLinks` with.
#[derive(Default)]
pub(super) struct ExtensionLinks {
    pub started: bool,
    /// Per instance, the last line asked about; its links once the host answered.
    lines: HashMap<u32, (String, Option<Vec<ProvidedLink>>)>,
    /// The cell under the pointer, hovered again when an answer arrives.
    pointer: Option<(u32, i32, usize)>,
}

/// `ITerminalLinkDto`: `start` and `length` count UTF-16 code units of the line.
#[derive(Clone, Debug, PartialEq)]
struct ProvidedLink {
    id: u64,
    start: usize,
    length: usize,
    label: Option<String>,
}

/// The link under the pointer: its instance and the cells it covers (grid line, column).
#[derive(Clone, Debug, PartialEq)]
pub(super) struct HoveredLink {
    pub id: u32,
    pub cells: Vec<(i32, usize)>,
    link: TerminalLink,
}

impl Workbench {
    /// `TerminalLinkManager` activation: opens the link under `row` and `column`; false when there is none.
    pub(super) fn open_terminal_link(&mut self, id: u32, row: i32, column: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
        let Some(hovered) = self.terminal_link_at(id, row, column) else { return false };
        self.activate_terminal_link(hovered.link, window, cx);
        true
    }

    pub(super) fn activate_terminal_link(&mut self, link: TerminalLink, window: &mut Window, cx: &mut Context<Self>) {
        match link {
            TerminalLink::Url(url) => cx.open_url(&url),
            TerminalLink::File { path, line, column } => self.open_terminal_file_link(path, line, column, window, cx),
            TerminalLink::Extension { instance, id, .. } => self.host.send("ExtHostTerminalService", "$activateLink", vec![json!(instance), json!(id)]),
        }
    }

    /// The link at a viewport row and column.
    fn terminal_link_at(&self, id: u32, row: i32, column: usize) -> Option<HoveredLink> {
        let instance = self.terminal_view.instance(id)?;
        if !(0..instance.term.screen_lines() as i32).contains(&row) {
            return None;
        }
        let line = row - instance.term.display_offset() as i32;
        let (text, cells) = wrapped_line_text(instance, line);
        let index = cells.iter().position(|&(cell_line, cell_column)| cell_line == line && cell_column >= column)?;
        let line_text = extension_line_text(&text);
        match self.terminal_view.extension_links.lines.get(&id) {
            // xterm waits for the extension provider before it takes a builtin link.
            Some((asked, None)) if asked == line_text => return None,
            Some((asked, Some(links))) if asked == line_text => {
                if let Some((link, range)) = provided_link_at(id, line_text, links, index) {
                    return Some(HoveredLink { id, cells: cells[range].to_vec(), link });
                }
            }
            _ => {}
        }
        let cwd = instance.shell_integration.cwd().map(PathBuf::from).unwrap_or_else(|| instance.launch.cwd.clone());
        let home = std::env::home_dir();
        let (link, range) = link_at(&text, index, &cwd, home.as_deref())?;
        Some(HoveredLink { id, cells: cells[range].to_vec(), link })
    }

    /// `TerminalLink` hover: the link under the pointer, its hover after the delay; the underline follows the
    /// link modifier (`_isLinkActivationModifierDown`).
    pub(super) fn terminal_link_hover(&mut self, id: u32, row: i32, column: usize, modifiers: Modifiers, window: &mut Window, cx: &mut Context<Self>) {
        self.terminal_view.link_modifier = self.terminal_link_modifier(modifiers);
        self.terminal_view.extension_links.pointer = Some((id, row, column));
        self.ask_extension_links(id, row, window, cx);
        self.show_terminal_link_hover(id, row, column, window, cx);
    }

    /// terminalExternalLinkDetector.ts `detect`: the wrapped line under `row` goes to `$provideLinks` once; the
    /// answer hovers the pointer's cell again.
    fn ask_extension_links(&mut self, id: u32, row: i32, window: &mut Window, cx: &mut Context<Self>) {
        if !self.terminal_view.extension_links.started {
            return;
        }
        let Some(instance) = self.terminal_view.instance(id) else { return };
        if !(0..instance.term.screen_lines() as i32).contains(&row) {
            return;
        }
        let (text, _) = wrapped_line_text(instance, row - instance.term.display_offset() as i32);
        let line_text = extension_line_text(&text).to_owned();
        if line_text.is_empty() || line_text.encode_utf16().count() > MAX_EXTENSION_LINE_LENGTH {
            return;
        }
        let lines = &mut self.terminal_view.extension_links.lines;
        if lines.get(&id).is_some_and(|(asked, _)| *asked == line_text) {
            return;
        }
        let answer = self.host.call("ExtHostTerminalService", "$provideLinks", vec![json!(id), json!(line_text)]);
        lines.insert(id, (line_text.clone(), None));
        cx.spawn_in(window, async move |workbench, cx| {
            let links = match answer.await {
                Ok(Ok(Value::Array(links))) => links.iter().filter_map(provided_link).collect(),
                _ => Vec::new(),
            };
            let _ = workbench.update_in(cx, |workbench, window, cx| {
                let extension_links = &mut workbench.terminal_view.extension_links;
                let Some(entry) = extension_links.lines.get_mut(&id).filter(|(asked, _)| *asked == line_text) else { return };
                entry.1 = Some(links);
                if let Some((id, row, column)) = extension_links.pointer {
                    workbench.terminal_view.hovered_link = None;
                    workbench.show_terminal_link_hover(id, row, column, window, cx);
                }
            });
        })
        .detach();
    }

    fn show_terminal_link_hover(&mut self, id: u32, row: i32, column: usize, window: &mut Window, cx: &mut Context<Self>) {
        let hovered = self.terminal_link_at(id, row, column);
        if hovered.as_ref().map(|link| (&link.cells, link.id)) == self.terminal_view.hovered_link.as_ref().map(|link| (&link.cells, link.id)) {
            return;
        }
        self.terminal_view.hovered_link = hovered.clone();
        cx.notify();
        let Some(hovered) = hovered else {
            self.leave_hover_target(cx);
            return;
        };
        let (Some(pane), Some(metrics)) = (self.terminal_view.pane_bounds.get(&id).copied(), self.terminal_view.metrics.clone()) else { return };
        let (first, last) = (hovered.cells[0], *hovered.cells.last().expect("a link covers a cell"));
        let Some(instance) = self.terminal_view.instance(id) else { return };
        let origin = grid::grid_origin(pane, instance);
        let offset = instance.term.display_offset() as i32;
        let cell = |(line, column): (i32, usize)| point(origin.x + px(column as f32 * metrics.cell_width), origin.y + px((line + offset) as f32 * metrics.cell_height));
        let top_left = cell(if first.0 == last.0 { first } else { (first.0, 0) });
        let bottom_right = cell((last.0, last.1 + 1)) + point(px(0.), px(metrics.cell_height));
        let bounds = Bounds { origin: top_left, size: size(bottom_right.x - top_left.x, bottom_right.y - top_left.y) };
        let markdown = self.terminal_link_hover_text(&hovered);
        // Trusted as upstream: the hover's link handler activates `link_in_hover` and never opens the href.
        self.terminal_view.link_in_hover = Some(hovered.link);
        self.show_managed_hover((TERMINAL_LINK_HOVER, hovered.cells[0].0 as usize * 10_000 + hovered.cells[0].1), HoverContent::Markdown(serde_json::json!({ "value": markdown, "isTrusted": true })), HoverOptions::element(), bounds, window, cx);
    }

    /// `modifierDownCallback` and `modifierUpCallback`: the hovered link's underline follows the modifier.
    pub(super) fn terminal_link_modifiers_changed(&mut self, modifiers: Modifiers, cx: &mut Context<Self>) {
        let down = self.terminal_link_modifier(modifiers);
        if down != self.terminal_view.link_modifier {
            self.terminal_view.link_modifier = down;
            if self.terminal_view.hovered_link.is_some() {
                cx.notify();
            }
        }
    }

    pub(super) fn terminal_link_modifier(&self, modifiers: Modifiers) -> bool {
        // `editor.multiCursorModifier` alt (the default) makes Cmd the link modifier.
        if self.setting(MULTI_CURSOR_MODIFIER.key) == "ctrlCmd" { modifiers.alt } else { modifiers.platform }
    }

    /// `_getLinkHoverString`: "[Follow link](target) (cmd + click)", the click label after the modifier.
    fn terminal_link_hover_text(&self, hovered: &HoveredLink) -> String {
        let click = if self.setting(MULTI_CURSOR_MODIFIER.key) == "ctrlCmd" { "option + click" } else { "cmd + click" };
        // The hover's markdown only links schemes, so a path links through its file URI. Terminal output is
        // untrusted: characters that could end the link and start another are percent-encoded.
        let (target, label) = match &hovered.link {
            TerminalLink::Url(url) => (url.clone(), None),
            TerminalLink::File { path, .. } => (crate::editor_history::file_uri_string(path), None),
            TerminalLink::Extension { text, label, .. } => {
                let target = if text.chars().any(char::is_whitespace) { "Link".to_owned() } else { text.clone() };
                (target, label.as_deref().map(escape_markdown))
            }
        };
        let mut encoded = String::new();
        for character in target.chars() {
            match character {
                c if c.is_whitespace() || c.is_control() || "()[]<>\"'\\".contains(c) => {
                    let mut buffer = [0; 4];
                    for byte in c.encode_utf8(&mut buffer).bytes() {
                        encoded.push_str(&format!("%{byte:02X}"));
                    }
                }
                c => encoded.push(c),
            }
        }
        let label = label.unwrap_or_else(|| "Follow link".to_owned());
        format!("[{label}]({encoded}) ({click})")
    }

    /// The cells of the hovered link to underline in pane `id`, while the modifier is down.
    pub(super) fn terminal_link_underline(&self, id: u32) -> Option<&[(i32, usize)]> {
        self.terminal_view.hovered_link.as_ref().filter(|link| link.id == id && self.terminal_view.link_modifier).map(|link| link.cells.as_slice())
    }

    fn open_terminal_file_link(&mut self, path: PathBuf, line: Option<u32>, column: Option<u32>, window: &mut Window, cx: &mut Context<Self>) {
        self.open_file(path, true, window, cx);
        let Some(line) = line else { return };
        let viewport = self.editors.viewport;
        let Some(editor) = self.editors.active_mut() else { return };
        let position = validate(&editor.document().lines, line as usize, column.unwrap_or(1) as usize);
        editor.set_selections(vec![Selection::caret(position)]);
        editor.reveal_range(position, position, VerticalReveal::CenterIfOutsideViewport, viewport);
        self.cursor_position_changed(Cursor { moved: true, source: "code.jump", reveal: Reveal::Nothing }, cx);
        self.editor_scrolled(cx);
    }
}

/// The characters of the wrapped line through `row` (the rows it continues and those continuing it) and the screen
/// cell of each; a wide character's spacer cell adds none.
fn wrapped_line_text(instance: &crate::terminal::TerminalInstance, row: i32) -> (String, Vec<(i32, usize)>) {
    let columns = instance.term.columns();
    let top = -(instance.term.history_size() as i32);
    let bottom = instance.term.screen_lines() as i32 - 1;
    let wraps = |row: i32| instance.term.wraps(Line(row));
    let mut first = row;
    while first > top && wraps(first - 1) {
        first -= 1;
    }
    let mut last = row;
    while last < bottom && wraps(last) {
        last += 1;
    }
    let mut text = String::new();
    let mut cells = Vec::new();
    for row in first..=last {
        let cells_of_row = instance.term.row(Line(row));
        for column in 0..columns {
            let cell = &cells_of_row[Column(column)];
            if cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
                continue;
            }
            text.push(cell.c);
            cells.push((row, column));
        }
    }
    (text, cells)
}

/// `translateToString(true)`: the line without the blank cells after its text.
fn extension_line_text(text: &str) -> &str {
    text.trim_end_matches(' ')
}

/// One `ITerminalLinkDto` of the `$provideLinks` answer.
fn provided_link(dto: &Value) -> Option<ProvidedLink> {
    Some(ProvidedLink { id: dto["id"].as_u64()?, start: dto["startIndex"].as_u64()? as usize, length: dto["length"].as_u64()? as usize, label: dto["label"].as_str().map(str::to_owned) })
}

/// The first provided link covering the character at `index`, its character range of `text`.
fn provided_link_at(instance: u32, text: &str, links: &[ProvidedLink], index: usize) -> Option<(TerminalLink, std::ops::Range<usize>)> {
    let mut utf16_starts = Vec::new();
    let mut offset = 0;
    for character in text.chars() {
        utf16_starts.push(offset);
        offset += character.len_utf16();
    }
    let char_at = |utf16: usize| utf16_starts.iter().position(|&start| start >= utf16).unwrap_or(utf16_starts.len());
    for link in links {
        let range = char_at(link.start)..char_at(link.start + link.length);
        if range.contains(&index) {
            let text = text.chars().skip(range.start).take(range.len()).collect();
            return Some((TerminalLink::Extension { instance, id: link.id, text, label: link.label.clone() }, range));
        }
    }
    None
}

/// `MarkdownString.appendText`: the label shows as plain text.
fn escape_markdown(text: &str) -> String {
    let mut escaped = String::new();
    for character in text.chars() {
        if "\\`*_{}[]()#+-!~".contains(character) {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped
}

/// The link covering the character at `index` and its character range: a URL first (the URI detector runs before
/// the local one), then an existing file path resolved against the terminal's cwd and `~`.
fn link_at(text: &str, index: usize, cwd: &Path, home: Option<&Path>) -> Option<(TerminalLink, std::ops::Range<usize>)> {
    for link in compute_links(&[text]) {
        let range = link.start_column - 1..link.end_column - 1;
        if range.contains(&index) {
            return Some((TerminalLink::Url(link.url), range));
        }
    }
    for parsed in detect_links(text) {
        let start = parsed.prefix.as_ref().map_or(parsed.path.index, |prefix| prefix.index);
        let end = parsed.suffix.as_ref().map_or(parsed.path.index + parsed.path.text.chars().count(), |suffix| suffix.suffix.index + suffix.suffix.text.chars().count());
        if !(start..end).contains(&index) {
            continue;
        }
        let raw = parsed.path.text.as_str();
        let path = match (raw.strip_prefix("~/"), home) {
            (Some(rest), Some(home)) => home.join(rest),
            _ => cwd.join(raw),
        };
        if !files::unc::is_unc_access_allowed(&path) || !path.is_file() {
            return None;
        }
        let (line, column) = parsed.suffix.map_or((None, None), |suffix| (suffix.row, suffix.col));
        return Some((TerminalLink::File { path, line, column }, start..end));
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn urls_and_existing_files_with_suffixes() {
        let dir = std::env::temp_dir().join(format!("terminal-links-{}", std::process::id()));
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(dir.join("src/main.rs"), "fn main() {}\n").unwrap();
        let text = "see https://example.com/a and src/main.rs:12:5 or missing.rs:3";
        assert_eq!(link_at(text, 6, &dir, None), Some((TerminalLink::Url("https://example.com/a".into()), 4..25)));
        assert_eq!(link_at(text, 32, &dir, None), Some((TerminalLink::File { path: dir.join("src/main.rs"), line: Some(12), column: Some(5) }, 30..46)));
        assert_eq!(link_at(text, 52, &dir, None), None);
        assert_eq!(link_at(text, 0, &dir, None), None);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// `//var/...` is `/var/...` on macOS and Linux, and a path on UNC host `var` to the check.
    #[cfg(unix)]
    #[test]
    fn a_file_on_a_refused_unc_host_is_not_probed() {
        let dir = std::env::temp_dir().join(format!("terminal-links-unc-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("main.rs"), "fn main() {}\n").unwrap();
        let text = format!("/{}", dir.join("main.rs").display());
        let host = dir.components().nth(1).unwrap().as_os_str().to_str().unwrap().to_owned();
        files::unc::restrict_unc_access_on_this_thread(Some(&[]));
        assert_eq!(link_at(&text, 3, Path::new("/"), None), None);
        files::unc::restrict_unc_access_on_this_thread(Some(&[&host]));
        assert!(link_at(&text, 3, Path::new("/"), None).is_some());
        files::unc::restrict_unc_access_on_this_thread(None);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn a_link_wrapped_over_two_rows_is_found_from_either_row() {
        let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let colors = crate::terminal::colors::TerminalColors::new(&crate::theme::load_theme(&[themes], "Dark Modern").unwrap());
        let launch = crate::terminal::ShellLaunchConfig { extension_pty: true, cwd: std::env::temp_dir(), ..Default::default() };
        let (mut instance, _) = crate::terminal::TerminalInstance::new(1, launch, 20, 4, ghostty_vt::Config::default());
        instance.process(b"go https://example.com/abc/def ok", &colors);
        let (text, cells) = wrapped_line_text(&instance, 1);
        assert!(text.starts_with("go https://example.com/abc/def ok"), "{text:?}");
        let index = cells.iter().position(|&cell| cell == (1, 2)).unwrap();
        let (link, range) = link_at(&text, index, Path::new("/"), None).unwrap();
        assert_eq!(link, TerminalLink::Url("https://example.com/abc/def".into()));
        assert_eq!((cells[range.start], cells[range.end - 1]), ((0, 3), (1, 9)));
    }

    /// window.test.ts `registerTerminalLinkProvider`: the hovered line goes to the host, the link it answers covers
    /// its UTF-16 range and a click activates it.
    #[gpui::test]
    fn extension_link_providers_answer_the_hovered_line(cx: &mut gpui::TestAppContext) {
        let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let (sender, messages) = std::sync::mpsc::channel();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx));
        let id = workbench.update_in(cx, |workbench, window, cx| {
            let launch = crate::terminal::ShellLaunchConfig { extension_pty: true, cwd: std::env::temp_dir(), ..Default::default() };
            let id = workbench.add_terminal(launch, None, window, cx);
            // The hover anchors on the painted pane.
            workbench.terminal_view.pane_bounds.insert(id, Bounds::new(point(px(0.), px(0.)), size(px(400.), px(200.))));
            let (bold_weight, normal_weight) = (gpui::FontWeight::BOLD, gpui::FontWeight::NORMAL);
            workbench.terminal_view.metrics = Some(grid::CellMetrics { family: "Menlo".into(), font_size: 12., bold_weight, normal_weight, line_height: 1., letter_spacing: 0., cell_width: 7., dom_cell_width: 7.2, cell_height: 16., descent: 3.3, scale: 2. });
            workbench.terminal_data(id, "go \u{1F980} run:task now".as_bytes(), window, cx);
            let start = exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadTerminalService", method: "$startLinkProvider".into(), args: Vec::new() };
            drop(workbench.handle_terminal_request(start, window, cx));
            id
        });
        cx.run_until_parked();
        let _ = messages.try_iter().count();
        workbench.update_in(cx, |workbench, window, cx| workbench.terminal_link_hover(id, 0, 7, Modifiers::default(), window, cx));
        let asked = messages.try_iter().find(|message| message.method == "$provideLinks").expect("asked the host");
        assert_eq!(asked.args, [json!(id), json!("go \u{1F980} run:task now")]);
        // The crab is two UTF-16 code units: "run:task" starts at 6.
        let _ = asked.reply.expect("a call").send(Ok(json!([{ "id": 3, "startIndex": 6, "length": 8, "label": "Run task" }])));
        cx.run_until_parked();
        let hovered = workbench.read_with(cx, |workbench, _| workbench.terminal_view.hovered_link.clone()).expect("the extension link");
        assert_eq!(hovered.link, TerminalLink::Extension { instance: id, id: 3, text: "run:task".into(), label: Some("Run task".into()) });
        assert_eq!((hovered.cells[0], *hovered.cells.last().unwrap()), ((0, 6), (0, 13)));
        // terminalLinkManager.ts `_showHover`: the hover's link activates the link, its href is never opened.
        workbench.update_in(cx, |workbench, window, cx| workbench.open_hover_link("run:task", window, cx));
        let activated = messages.try_iter().find(|message| message.method == "$activateLink").expect("the hover link activated");
        assert_eq!(activated.args, [json!(id), json!(3)]);
        assert!(workbench.update_in(cx, |workbench, window, cx| workbench.open_terminal_link(id, 0, 7, window, cx)));
        let activated = messages.try_iter().find(|message| message.method == "$activateLink").expect("activated");
        assert_eq!(activated.args, [json!(id), json!(3)]);
    }
}