Skip to content

Visual Studio Code, rebuilt in Rust

Rust
23.2 KB
Raw Blame
//! terminalEditorService.ts, terminalEditorInput.ts and terminalEditor.ts: terminals the editor area shows, each
//! a `vscode-terminal` editor whose body is the instance's pane.

use std::path::{Path, PathBuf};
use gpui::{Context, Div, Rgba, Window, div, prelude::*, px};
use serde_json::{Value, json};

use super::Workbench;
use super::terminal_view::TerminalLocation;
use super::webview_panels::SIDE_GROUP;
use crate::commands::Outcome;
use crate::editor::{OpenEditor, TextDocument};
use crate::terminal::colors::TerminalColors;
use crate::terminal::profiles::Profile;
use crate::terminal::{ShellLaunchConfig, TerminalInstance, format_loud_message_for_terminal};

/// network.ts `Schemas.vscodeTerminal`.
pub const TERMINAL_EDITOR_SCHEME: &str = "vscode-terminal";

/// Where `createTerminal({ location: { viewColumn } })` opens the editor.
#[derive(Clone, Copy)]
pub(super) enum EditorTarget {
    /// `ACTIVE_GROUP`: the active group, or an unlocked one when it is locked.
    Active,
    /// The active group even when it is locked (`CreateTerminalEditorSameGroup`).
    SameGroup,
    /// `SIDE_GROUP`.
    Side,
    /// `AUX_WINDOW_GROUP`: the group of a new editor window.
    NewWindow,
}

pub(super) fn terminal_editor_id(editor: &OpenEditor) -> Option<u32> {
    let document = editor.document();
    if document.scheme != TERMINAL_EDITOR_SCHEME {
        return None;
    }
    instance_id(&document.path)
}

/// The `{instanceId}` of terminalUri.ts's `/{workspaceId}/{instanceId}`.
fn instance_id(path: &Path) -> Option<u32> {
    path.file_name()?.to_str()?.parse().ok()
}

impl Workbench {
    /// terminalUri.ts `getTerminalUri` as terminalInstance.ts calls it, before the instance has a title: no fragment.
    fn terminal_editor_path(&self, id: u32) -> PathBuf {
        PathBuf::from(format!("/{}/{id}", self.workspace_id()))
    }

    /// `IWorkspace.id`: the name of the window's backup folder (`Backups/<workspace id>`); without one, an extension
    /// development window, the workspace's id or `EXTENSION_DEVELOPMENT_EMPTY_WINDOW_WORKSPACE`'s `ext-dev`.
    fn workspace_id(&self) -> String {
        if let Some(name) = self.lifecycle.backups.home.as_ref().and_then(|home| home.file_name()) {
            return name.to_string_lossy().into_owned();
        }
        self.workspace().map_or_else(|| "ext-dev".to_owned(), exthost::session::workspace_id)
    }

    pub(super) fn register_terminal_editor_actions(&mut self) {
        self.commands.register("workbench.action.createTerminalEditor", |workbench, _, window, cx| {
            workbench.create_terminal_editor(None, EditorTarget::Active, window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.createTerminalEditorSameGroup", |workbench, _, window, cx| {
            workbench.create_terminal_editor(None, EditorTarget::SameGroup, window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.createTerminalEditorSide", |workbench, _, window, cx| {
            workbench.create_terminal_editor(None, EditorTarget::Side, window, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.terminal.moveToEditor", |workbench, _, window, cx| {
            if let Some(id) = workbench.terminal_view.group_active_instance_id() {
                workbench.move_terminal_to_editor(id, EditorTarget::Active, window, cx);
            }
            Outcome::done()
        });
        // terminalService.ts `moveIntoNewEditor`.
        self.commands.register("workbench.action.terminal.moveIntoNewWindow", |workbench, _, window, cx| {
            if let Some(id) = workbench.terminal_view.group_active_instance_id() {
                workbench.move_terminal_to_editor(id, EditorTarget::NewWindow, window, cx);
            }
            Outcome::done()
        });
        self.commands.register("workbench.action.terminal.moveToTerminalPanel", |workbench, _, window, cx| {
            if let Some(id) = workbench.active_terminal_editor() {
                workbench.move_terminal_to_panel(id, window, cx);
            }
            Outcome::done()
        });
    }

    /// `terminalEditorService.activeInstance`: the terminal of the active editor.
    pub(super) fn active_terminal_editor(&self) -> Option<u32> {
        terminal_editor_id(self.editors.active()?)
    }

    /// `createTerminal({ location: { viewColumn } })`: the instance joins no group and opens as an editor.
    pub(super) fn create_terminal_editor(&mut self, profile: Option<Profile>, target: EditorTarget, window: &mut Window, cx: &mut Context<Self>) {
        let profile = profile.unwrap_or_else(|| self.default_terminal_profile());
        let launch = self.shell_launch_config(&profile, self.terminal_initial_cwd());
        let id = self.add_terminal_at(launch, TerminalLocation::Editor, window, cx);
        self.open_terminal_editor(id, target, window, cx);
    }

    /// terminalService.ts `moveToEditor`: the pane leaves its group, which hides the panel when it was the last one.
    pub(super) fn move_terminal_to_editor(&mut self, id: u32, target: EditorTarget, window: &mut Window, cx: &mut Context<Self>) {
        if self.terminal_view.editor_instances.contains(&id) {
            return;
        }
        self.terminal_view.remove_from_groups(id);
        if self.terminal_view.groups.is_empty() {
            self.hide_terminal_view_on_last_closed(cx);
        }
        self.open_terminal_editor(id, target, window, cx);
    }

    /// terminalService.ts `moveToTerminalView`: the editor closes without killing the instance, which becomes a group
    /// of its own in the shown panel.
    pub(super) fn move_terminal_to_panel(&mut self, id: u32, window: &mut Window, cx: &mut Context<Self>) {
        self.terminal_view.editor_instances.retain(|instance| *instance != id);
        self.close_terminal_editor(id, cx);
        self.terminal_view.add_group(id);
        self.terminal_view.set_active(id);
        self.show_terminal_tab(window, cx);
        cx.notify();
    }

    /// terminalEditorService.ts `openEditor`.
    pub(super) fn open_terminal_editor(&mut self, id: u32, target: EditorTarget, window: &mut Window, cx: &mut Context<Self>) {
        let path = self.terminal_editor_path(id);
        match target {
            EditorTarget::Active => self.leave_locked_group(TERMINAL_EDITOR_SCHEME, &path),
            EditorTarget::SameGroup => {}
            EditorTarget::Side => {
                if let Some(group) = self.webview_target_group(&json!(SIDE_GROUP)) {
                    self.activate_group(group);
                }
            }
            EditorTarget::NewWindow => self.open_empty_editor_window(window, cx),
        }
        self.terminal_view.editor_instances.push(id);
        let document = TextDocument::from_text(TERMINAL_EDITOR_SCHEME, &path, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap());
        self.editors.open(document, false);
        self.terminal_view.set_active(id);
        self.editors_changed(cx);
        window.focus(&self.terminal_view.focus, cx);
        self.sync_terminals_to_host();
        cx.notify();
    }

    /// Closes every editor of `id`'s terminal, as `detachInstance` and the instance's disposal do.
    pub(super) fn close_terminal_editor(&mut self, id: u32, cx: &mut Context<Self>) {
        let path = self.terminal_editor_path(id);
        for group in self.editors.group_ids_mru() {
            self.with_group(group, |workbench| {
                while let Some(index) = workbench.editors.editors.iter().position(|editor| editor.document().is(TERMINAL_EDITOR_SCHEME, &path)) {
                    workbench.editors.close(index);
                }
            });
        }
        self.editors_changed(cx);
    }

    /// After a change of the editors: the active terminal editor's instance is the active one
    /// (`onDidActiveEditorChange`), and the terminal of a closed terminal editor is killed (`TerminalEditorInput.dispose`).
    pub(super) fn sync_terminal_editors(&mut self, cx: &mut Context<Self>) {
        match self.active_terminal_editor() {
            Some(id) => self.terminal_view.set_active(id),
            None => self.terminal_view.active_editor = None,
        }
        let open: Vec<u32> = self.editors.all_tabs().filter_map(terminal_editor_id).collect();
        self.host.terminal_tabs = open.iter().map(|id| (self.terminal_editor_path(*id), self.terminal_editor_name(&self.terminal_editor_path(*id)))).collect();
        let closed: Vec<u32> = self.terminal_view.editor_instances.iter().copied().filter(|id| !open.contains(id)).collect();
        let Some(main_window) = self.auxiliary_windows.main_window.filter(|_| !closed.is_empty()) else { return };
        let workbench = cx.entity();
        cx.defer(move |cx| {
            let _ = main_window.update(cx, |_, window, cx| {
                workbench.update(cx, |workbench, cx| {
                    for id in closed {
                        workbench.kill_terminal(id, window, cx);
                    }
                })
            });
        });
    }

    /// `TerminalEditorInput.getName`: the instance's title.
    pub(super) fn terminal_editor_name(&self, path: &Path) -> String {
        instance_id(path).and_then(|id| self.terminal_view.instance(id)).map(|instance| instance.title()).unwrap_or_default()
    }

    /// `TerminalEditorInput.getIcon`: the instance's icon.
    pub(super) fn terminal_editor_icon(&self, editor: &OpenEditor, line_height: f32, foreground: Rgba) -> Option<Div> {
        let instance = self.terminal_view.instance(terminal_editor_id(editor)?)?;
        self.predefined_file_icon(instance.icon(), line_height, self.terminal_icon_color(instance, foreground))
    }

    /// terminalMenus.ts `EditorTitle` navigation: New Terminal (order 0) with terminalEditor.ts's profile dropdown.
    pub(super) fn terminal_editor_title_action(&self, bar: Option<&'static str>, cx: &mut Context<Self>) -> Option<gpui::AnyElement> {
        self.active_terminal_editor()?;
        let foreground = self.color("icon.foreground");
        let new = self.search_action("add", "workbench.action.createTerminalEditorSameGroup", true, cx);
        let chevron = self.terminal_profile_chevron(foreground, vec![json!({ "location": { "viewColumn": -1 } })], cx);
        // dropdownWithPrimaryActionViewItem.ts: Right and Left move between the primary action and its dropdown.
        let (new, chevron) = (self.title_action(bar, "terminal-new", new, cx), self.title_action(bar, "terminal-profile", chevron, cx));
        // The fixed width of terminal_view.rs's panel title pair: taffy sizes a row with a negative-margin child to 0.
        Some(div().w(px(35.)).flex_none().flex().items_center().child(new).child(chevron).into_any_element())
    }

    /// terminalEditor.ts: the instance's pane fills the editor, on `terminal.background` over the editor's.
    pub(super) fn terminal_editor_body(&self, editor: &OpenEditor, window: &mut Window, cx: &mut Context<Self>) -> Div {
        let id = terminal_editor_id(editor).expect("a terminal editor's resource names its instance");
        // `TerminalEditor.focus`: the editor's focus is its terminal's.
        if self.editor_focus.is_focused(window) {
            cx.defer_in(window, |workbench, window, cx| window.focus(&workbench.terminal_view.focus, cx));
        }
        let view = &self.terminal_view;
        let background = self.theme.color("terminal.background").unwrap_or(self.color("editor.background"));
        let shows_widgets = view.active_instance_id() == Some(id) && view.active_editor.is_some();
        let mut pane = div().id("terminal-editor").track_focus(&view.focus).relative().flex_1().min_h_0().flex().bg(background).child(self.terminal_pane(id, false, self.color("terminal.border"), cx));
        if shows_widgets {
            pane = pane.children(self.terminal_find_widget(window, cx)).children(self.terminal_suggest_widget(window, cx));
        }
        div().flex_1().min_h_0().flex().child(pane)
    }

    /// terminalProcessManager.ts `shouldPersist`: a shell under `enablePersistentSessions`, not a task's or an
    /// extension's pty.
    pub(super) fn terminal_persists(&self, instance: &TerminalInstance) -> bool {
        self.setting("terminal.integrated.enablePersistentSessions") != false && !instance.launch.extension_pty && !instance.launch.is_feature_terminal
    }

    /// terminalEditorSerializer.ts `serialize`: the editor of a persistent terminal, by its process id.
    pub(super) fn serialized_terminal_editor(&self, editor: &OpenEditor) -> Option<Value> {
        let instance = self.terminal_view.instance(terminal_editor_id(editor)?)?;
        if !self.terminal_persists(instance) {
            return None;
        }
        let value = json!({
            "id": instance.id,
            "pid": instance.pid.unwrap_or(0),
            "title": instance.title(),
            "titleSource": title_source(instance),
            "cwd": "",
            "icon": { "id": instance.icon() },
            "color": instance.launch.color,
            "hasChildProcesses": false,
            "isFeatureTerminal": instance.launch.is_feature_terminal,
            "hideFromUser": instance.launch.hide_from_user,
            "shellIntegrationNonce": instance.launch.nonce,
        });
        Some(json!({ "id": TERMINAL_EDITOR_INPUT, "value": value.to_string() }))
    }

    /// terminalService.ts `_onWillShutdown` on quit, with localTerminalBackend.ts `persistTerminalState` and
    /// ptyService.ts `serializeTerminalState`: each persistent terminal with its buffer replay, and the panel's groups
    /// (`_saveState`, which upstream stores on each change; nothing changes them between the last change and quit).
    pub(super) fn persist_terminal_state(&self) {
        if self.setting("terminal.integrated.enablePersistentSessions") == false || self.setting("terminal.integrated.persistentSessionReviveProcess") == "never" {
            let mut storage = self.workspace_storage.lock().unwrap();
            storage.delete(BUFFER_STATE_KEY);
            storage.delete(LAYOUT_INFO_KEY);
            return;
        }
        let scrollback = self.setting("terminal.integrated.persistentSessionScrollback").as_u64().unwrap_or(100) as usize;
        let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis() as u64);
        let view = &self.terminal_view;
        let mut state = Vec::new();
        for id in view.groups.iter().flat_map(|group| &group.instances).chain(&view.editor_instances) {
            let Some(instance) = view.instance(*id).filter(|instance| self.terminal_persists(instance)) else { continue };
            let launch = &instance.launch;
            let cwd = instance.cwd.clone().unwrap_or_else(|| launch.cwd.to_string_lossy().into_owned());
            state.push(json!({
                "id": instance.id,
                "shellLaunchConfig": { "name": launch.name, "executable": launch.executable, "args": launch.args },
                "processDetails": { "cwd": cwd, "title": instance.title(), "titleSource": title_source(instance), "icon": { "id": instance.icon() }, "color": launch.color },
                "replayEvent": { "events": [{ "cols": instance.term.columns(), "rows": instance.term.screen_lines(), "data": instance.serialize_buffer(scrollback) }] },
                "timestamp": timestamp,
            }));
        }
        let serialized = json!({ "version": 1, "state": state }).to_string();
        let layout = self.terminal_layout_info().to_string();
        let mut storage = self.workspace_storage.lock().unwrap();
        storage.set(BUFFER_STATE_KEY, serialized);
        storage.set(LAYOUT_INFO_KEY, layout);
    }

    /// terminalGroup.ts `getLayoutInfo` of each group as localTerminalBackend.ts `setTerminalLayoutInfo` stores them.
    fn terminal_layout_info(&self) -> Value {
        let view = &self.terminal_view;
        let mut tabs = Vec::new();
        for (index, group) in view.groups.iter().enumerate() {
            let persistent: Vec<u32> = group.instances.iter().copied().filter(|id| view.instance(*id).is_some_and(|instance| self.terminal_persists(instance))).collect();
            // The port's split panes share their group's width equally.
            let relative_size = 1. / persistent.len().max(1) as f64;
            tabs.push(json!({
                "isActive": index == view.active_group,
                "activePersistentProcessId": group.instances.get(group.active),
                "terminals": persistent.iter().map(|id| json!({ "relativeSize": relative_size, "terminal": id })).collect::<Vec<_>>(),
            }));
        }
        json!({ "workspaceId": self.workspace_id(), "tabs": tabs, "background": [] })
    }

    fn stored_buffer_state(&self) -> Option<Value> {
        serde_json::from_str(self.workspace_storage.lock().unwrap().get(BUFFER_STATE_KEY)?).ok()
    }

    /// ptyService.ts `_reviveTerminalProcess`: the launch of the stored terminal `id`, with its replayed buffer as the
    /// initial text, under a new instance id.
    fn terminal_revive(&mut self, stored: &Value, id: &Value) -> Option<TerminalRevive> {
        let terminal = stored["state"].as_array()?.iter().find(|terminal| terminal["id"] == *id)?;
        let (launch, details, replay) = (&terminal["shellLaunchConfig"], &terminal["processDetails"], &terminal["replayEvent"]["events"][0]);
        let cwd = PathBuf::from(details["cwd"].as_str()?);
        // A name only for a title the API gave, a freshly resolved environment.
        let launch = ShellLaunchConfig {
            name: (details["titleSource"] == TITLE_SOURCE_API).then(|| details["title"].as_str().map(str::to_owned)).flatten(),
            executable: PathBuf::from(launch["executable"].as_str()?),
            args: launch["args"].as_array().into_iter().flatten().filter_map(|arg| arg.as_str().map(str::to_owned)).collect(),
            env: self.terminal_environment(&Default::default()),
            cwd,
            icon: details["icon"]["id"].as_str().map(str::to_owned),
            color: details["color"].as_str().map(str::to_owned),
            ..ShellLaunchConfig::default()
        };
        let size = (replay["cols"].as_u64().unwrap_or(80) as u16, replay["rows"].as_u64().unwrap_or(30) as u16);
        // `initialText` goes out with `writeln`.
        let initial_text = format!("{}{}\r\n", replay["data"].as_str().unwrap_or_default(), format_loud_message_for_terminal("History restored"));
        Some(TerminalRevive { id: self.terminal_view.reserve_id(), launch, size, initial_text })
    }

    /// terminalEditorSerializer.ts `deserialize` and terminalEditorService.ts `reviveInput`: the editor of a stored
    /// terminal; its shell starts in `revive_terminals`. Without a stored buffer there is nothing to revive.
    pub(super) fn revive_terminal_editor(&mut self, value: &Value) -> Option<TextDocument> {
        let stored = self.stored_buffer_state()?;
        let revive = self.terminal_revive(&stored, &value["id"])?;
        let path = self.terminal_editor_path(revive.id);
        self.terminal_view.revives.push(revive);
        Some(TextDocument::from_text(TERMINAL_EDITOR_SCHEME, &path, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap()))
    }

    /// localTerminalBackend.ts `getTerminalLayoutInfo` with terminalService.ts `_reconnectToLocalTerminals`: the
    /// panel's stored groups and the restored editors' shells start, each after its replayed buffer, and the stored
    /// buffers and layout are dropped.
    pub fn revive_terminals(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let editor_revives = std::mem::take(&mut self.terminal_view.revives);
        let Some(stored) = self.stored_buffer_state() else { return };
        let layout = self.workspace_storage.lock().unwrap().get(LAYOUT_INFO_KEY).and_then(|layout| serde_json::from_str::<Value>(layout).ok());
        {
            let mut storage = self.workspace_storage.lock().unwrap();
            storage.delete(BUFFER_STATE_KEY);
            storage.delete(LAYOUT_INFO_KEY);
        }
        if let Some(layout) = layout {
            self.recreate_terminal_groups(&stored, &layout, window, cx);
        }
        for revive in editor_revives {
            let id = revive.id;
            self.start_revived_terminal(revive, TerminalLocation::Editor, window, cx);
            self.terminal_view.editor_instances.push(id);
        }
        self.editors_changed(cx);
        self.sync_terminals_to_host();
    }

    /// terminalService.ts `_recreateTerminalGroups`: each stored tab comes back as a group of split panes, with its
    /// active pane, and the active tab's group is the active group.
    fn recreate_terminal_groups(&mut self, stored: &Value, layout: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let mut active_pane = None;
        for tab in layout["tabs"].as_array().into_iter().flatten() {
            let mut previous = None;
            let mut tab_active_pane = None;
            for terminal in tab["terminals"].as_array().into_iter().flatten() {
                let Some(revive) = self.terminal_revive(stored, &terminal["terminal"]) else { continue };
                let id = revive.id;
                self.start_revived_terminal(revive, TerminalLocation::Panel { split_from: previous }, window, cx);
                if terminal["terminal"] == tab["activePersistentProcessId"] {
                    tab_active_pane = Some(id);
                }
                previous = Some(id);
            }
            if let Some(id) = tab_active_pane {
                self.terminal_view.set_active(id);
            }
            if tab["isActive"] == true {
                active_pane = tab_active_pane.or(previous);
            }
        }
        if let Some(id) = active_pane {
            self.terminal_view.set_active(id);
        }
    }

    fn start_revived_terminal(&mut self, revive: TerminalRevive, location: TerminalLocation, window: &mut Window, cx: &mut Context<Self>) {
        self.add_terminal_with_id(revive.id, revive.launch, revive.size, location, window, cx);
        let colors = TerminalColors::new(&self.theme);
        let instance = self.terminal_view.instance_mut(revive.id).expect("the instance was just added");
        instance.process(revive.initial_text.as_bytes(), &colors);
    }
}

/// terminalEditorInput.ts `TerminalEditorInput.ID`.
pub(super) const TERMINAL_EDITOR_INPUT: &str = "workbench.editors.terminal";
/// terminalStorageKeys.ts `TerminalBufferState`.
const BUFFER_STATE_KEY: &str = "terminal.integrated.bufferState";
/// terminalStorageKeys.ts `TerminalLayoutInfo`.
const LAYOUT_INFO_KEY: &str = "terminal.integrated.layoutInfo";
/// terminal.ts `TitleEventSource.Api` and `.Process`.
const TITLE_SOURCE_API: u8 = 0;
const TITLE_SOURCE_PROCESS: u8 = 1;

/// A restored terminal editor waiting for a window to start its shell in.
pub(super) struct TerminalRevive {
    id: u32,
    launch: ShellLaunchConfig,
    size: (u16, u16),
    initial_text: String,
}

fn title_source(instance: &TerminalInstance) -> u8 {
    if instance.user_title.is_some() || instance.launch.name.is_some() { TITLE_SOURCE_API } else { TITLE_SOURCE_PROCESS }
}

#[cfg(test)]
mod tests;

/// `newWithProfile`'s `location` argument: an editor location (`TerminalLocation.Editor` or a `viewColumn`).
pub(super) fn profile_location_is_editor(args: &[Value]) -> bool {
    let location = args.first().map(|args| &args["location"]);
    location.is_some_and(|location| location.is_object() || *location == json!(2))
}