rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! VS Code in a pane: opening a folder or a file, the editor setting, and the page's
//! own quirks.

use super::*;

/// VS Code's page is drawn this much smaller, to fit more in a pane.
pub(super) const CODE_ZOOM: f64 = 0.9;

/// What to show in VS Code.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CodeRequest {
    pub folder: PathBuf,
    pub file: Option<Spot>,
}

/// VS Code lays its window out before it has read the server's settings, so the setting
/// that hides the chat side bar comes too late the first time, and the layout is then
/// remembered. So close that bar once, with its own button; opened again, it stays.
pub(super) const HIDE_CHAT_ONCE: &str = r#"
    const hid = "rustimal.hid-secondary-side-bar";
    let looks = 0;
    const timer = setInterval(() => {
        if (localStorage.getItem(hid) || ++looks > 120) return clearInterval(timer);
        const bar = document.querySelector(".part.auxiliarybar");
        const close = bar && bar.offsetWidth > 0
            && bar.querySelector(".title .global-actions .codicon-close, .title .global-actions .codicon-auxiliarybar-close, .title .codicon-close");
        if (close) {
            close.click();
            localStorage.setItem(hid, "1");
        }
    }, 500);"#;

/// The cookie VS Code's web page takes its display language from.
pub(super) const NLS_COOKIE: &str = "vscode.nls.locale";

/// With no language chosen, VS Code's web server goes by the system's. For one it has no
/// matching translation of (Hungarian, for one) it fetches text that doesn't fit this
/// version, and menus and labels come out scrambled. So ask for English, unless a display
/// language has been chosen in VS Code.
pub(super) fn prefer_english_unless_chosen(web: &WebView, origin: &str) {
    let chosen = web.cookies_for_url(origin).is_ok_and(|all| all.iter().any(|c| c.name() == NLS_COOKIE));
    if !chosen {
        let cookie = wry::cookie::Cookie::build((NLS_COOKIE, "en")).domain("127.0.0.1").path("/").build();
        if let Err(e) = web.set_cookie(&cookie) {
            log::warn!("could not set VS Code's language: {e}");
        }
    }
}

/// Why VS Code can't be shown, if it can't.
pub(super) fn code_unavailable() -> Option<&'static str> {
    if vscode::tool().is_none() {
        Some("it isn't installed")
    } else if !vscode::license_accepted() {
        Some("run `vscode` in a terminal once, to accept its server's license")
    } else {
        None
    }
}

/// Whether the address of a VS Code page is that of `folder`.
pub(super) fn shows_folder(url: &str, folder: &Path) -> bool {
    let Some(value) = url.split(['?', '&']).find_map(|part| part.strip_prefix("folder=")) else { return false };
    let bytes = value.as_bytes();
    let (mut out, mut i) = (Vec::new(), 0);
    while i < bytes.len() {
        let hex = value.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok());
        match (bytes[i], hex) {
            (b'%', Some(byte)) => {
                out.push(byte);
                i += 3;
            }
            (byte, _) => {
                out.push(byte);
                i += 1;
            }
        }
    }
    let shown = String::from_utf8_lossy(&out).trim_end_matches('/').to_lowercase();
    let wanted = folder.to_string_lossy().replace('\\', "/").trim_end_matches('/').to_lowercase();
    shown == format!("/{wanted}")
}

/// What the shell's `vscode` or `open` left in its file: the path on the first line, and
/// on the second the line and column, if any, as `12` or `12:5`.
pub(super) fn read_request(request: &str) -> Option<(PathBuf, Option<u32>, Option<u32>)> {
    let mut lines = request.lines();
    let path = PathBuf::from(lines.next().filter(|l| !l.is_empty())?);
    let mut numbers = lines.next().unwrap_or_default().split(':').map(|n| n.parse::<u32>().ok().filter(|&n| n > 0));
    let line = numbers.next().flatten();
    let col = line.and(numbers.next().flatten());
    path.exists().then_some((path, line, col))
}

impl App {
    /// VS Code, with a folder and maybe a file: start its server off the UI thread.
    pub(in crate::app) fn open_code(&mut self, pane: PaneId, request: CodeRequest) {
        let keys = self.keymap.describe(Action::Embed);
        let Some(st) = self.state.as_mut() else { return };
        if st.web.opening.contains(&(pane, WebKind::Code)) {
            return;
        }
        st.web.opening.push((pane, WebKind::Code));
        let proxy = self.proxy.clone();
        std::thread::spawn(move || {
            let server = vscode::ensure();
            let _ = proxy.send_event(UserEvent::CodeReady { pane, request, server });
        });
        let close = self.keymap.describe(Action::ClosePane);
        self.toast(format!("Opening VS Code\u{2026} {keys} switches back, {close} closes it"));
    }

    pub(in crate::app) fn code_ready(
        &mut self,
        pane: PaneId,
        request: CodeRequest,
        server: Result<vscode::Server, String>,
    ) {
        if !self.stop_waiting(pane, WebKind::Code) {
            return;
        }
        let shown = server.and_then(|server| {
            let url = server.url(&request.folder, request.file.as_ref());
            // The folder it shows already needs no loading, unless a file is to be opened.
            let same = request.file.is_none()
                && self.state.as_ref().and_then(|st| st.web.get(pane, WebKind::Code)).is_some_and(|v| {
                    v.origin == server.origin() && v.web.url().is_ok_and(|at| shows_folder(&at, &request.folder))
                });
            self.show_page(pane, WebKind::Code, request.folder.clone(), &server.origin(), &url, !same)
        });
        self.report(WebKind::Code, shown);
    }

    /// Ctrl+Shift+I: VS Code in particular.
    pub(in crate::app) fn toggle_code(&mut self) {
        let Some(st) = self.state.as_mut() else { return };
        let id = st.focused;
        let cwd = st.panes.iter().find(|p| p.id == id).and_then(|p| p.cwd.clone()).or_else(|| self.start_dir.clone());
        let Some(cwd) = cwd.or_else(dirs::home_dir) else { return };
        match st.web.get(id, WebKind::Code) {
            Some(view) if !view.hidden => {
                st.web.hide(id);
                st.blink_epoch = Instant::now();
                st.window.request_redraw();
            }
            // Back to the same place, unless the shell has moved out of the folder shown.
            Some(view) if cwd.starts_with(&view.dir) => bring_forward(st, id, WebKind::Code),
            _ => self.code_folder(id, cwd),
        }
    }

    /// Show a folder in VS Code, if it can be: installed, and its license accepted.
    pub(super) fn code_folder(&mut self, pane: PaneId, folder: PathBuf) {
        match code_unavailable() {
            Some(why) => self.toast(format!("VS Code: {why}")),
            None => self.open_code(pane, CodeRequest { folder, file: None }),
        }
    }

    /// `vscode PATH` in a shell, or `open FILE`.
    pub(in crate::app) fn shell_code(&mut self, pane: PaneId, cwd: &Path, mode: &str, request: &str) {
        let Some((path, line, col)) = read_request(request) else { return };
        if mode == "vscode" {
            if path.is_dir() {
                self.code_folder(pane, path);
            } else if let Some(why) = code_unavailable() {
                self.toast(format!("VS Code: {why}"));
            } else {
                self.open_code_file(pane, Spot { file: path, line, col }, Some(cwd));
            }
            return;
        }
        // `open`: as a click on the same thing would.
        let target = match line {
            Some(line) => Target::Location { path, pos: links::Pos { line, col } },
            None => Target::Path(path),
        };
        self.open_target(pane, &target);
    }

    pub(super) fn open_code_file(&mut self, pane: PaneId, spot: Spot, cwd: Option<&Path>) {
        let Some(st) = self.state.as_ref() else { return };
        let open = st.web.get(pane, WebKind::Code).map(|v| v.dir.clone());
        let folder = vscode::workspace_for(&spot.file, open.as_deref(), cwd);
        self.open_code(pane, CodeRequest { folder, file: Some(spot) });
    }

    /// Open what was clicked in `pane`. With the built-in editor, files to edit open in VS
    /// Code in that pane; everything else opens as it always has.
    pub(in crate::app) fn open_target(&mut self, pane: PaneId, target: &Target) {
        let wanted = self.config.editor.trim() == links::BUILT_IN_EDITOR;
        let file = match target {
            Target::Location { path, pos } if path.is_file() => {
                Some(Spot { file: path.clone(), line: Some(pos.line), col: pos.col })
            }
            Target::Path(path) | Target::Entry { path, .. } if links::opens_in_editor(path) => {
                Some(Spot { file: path.clone(), line: None, col: None })
            }
            _ => None,
        };
        if wanted
            && let Some(spot) = file
            && vscode::tool().is_some()
        {
            if vscode::license_accepted() {
                let cwd = self.state.as_ref().and_then(|st| st.panes.iter().find(|p| p.id == pane)?.cwd.clone());
                return self.open_code_file(pane, spot, cwd.as_deref());
            }
            if let Some(st) = self.state.as_mut()
                && !std::mem::replace(&mut st.web.told_about_license, true)
            {
                self.toast("Run `vscode` once to open files in VS Code here");
            }
        }
        links::open(target, &self.config.editor);
    }
}