Visual Studio Code, rebuilt in Rust
Rust
use std::path::Path;
use exthost::scan::scan_extension;
use gpui::TestAppContext;
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::main_thread_quick_open::Owner;
use crate::quick_input::{Entry, Event};
use crate::menus::{MenuAction, MenuId};
use crate::theme::load_theme;
use crate::workbench::Workbench;
use crate::workbench::icon_select_box::IconTarget;
use crate::workbench::terminal_view::TerminalInput;
use super::{TERMINAL_EDITOR_SCHEME, terminal_editor_id};
fn menu_titles(workbench: &Workbench) -> Vec<String> {
let actions = &workbench.context_menu.as_ref().expect("a context menu is open").levels[0].actions;
actions.iter().filter_map(|action| if let MenuAction::Command { title, .. } = action { Some(title.clone()) } else { None }).collect()
}
#[gpui::test]
fn terminals_move_between_the_editor_area_and_the_panel(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let dir = std::env::temp_dir().join(format!("code-gpui-terminal-editor-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));
// terminalMenus.ts: an empty group's context menu creates a terminal editor in it.
let id = workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.show_empty_group_context_menu(workbench.editors.id, gpui::point(gpui::px(10.), gpui::px(10.)), window, cx);
assert!(menu_titles(workbench).contains(&"New Terminal".to_string()));
workbench.hide_context_menu(window, cx);
workbench.execute_command("workbench.action.createTerminalEditorSameGroup", Vec::new(), window, cx);
let id = workbench.active_terminal_editor().expect("the new terminal is the active editor");
assert_eq!(workbench.editors.active().unwrap().document().scheme, TERMINAL_EDITOR_SCHEME);
// terminalUri.ts `getTerminalUri`: a window without backups is an extension development window.
assert_eq!(workbench.editors.active().unwrap().document().uri_string(), format!("vscode-terminal:/ext-dev/{id}"));
assert!(workbench.terminal_view.groups.is_empty(), "an editor's terminal joins no panel group");
assert_eq!(workbench.terminal_view.active_instance_id(), Some(id));
id
});
workbench.update_in(cx, |workbench, window, cx| {
let context = workbench.key_context(window);
let actions = crate::menus::menu_actions(&workbench.menus, MenuId::EditorTitleContext, &context);
assert!(actions.iter().any(|action| matches!(action, MenuAction::Command { title, .. } if title == "Move Terminal into Panel")));
// The terminal editor is registered `exclusive`, so it cannot be reopened with another editor.
assert!(!actions.iter().any(|action| matches!(action, MenuAction::Command { title, .. } if title == "Reopen Editor With...")));
workbench.execute_command("workbench.action.terminal.moveToTerminalPanel", Vec::new(), window, cx);
assert!(workbench.editors.all_editors().all(|editor| terminal_editor_id(editor).is_none()));
assert_eq!(workbench.terminal_view.group_instances(), vec![vec![id]]);
assert!(workbench.terminal_view.instance(id).is_some(), "moving keeps the process");
workbench.execute_command("workbench.action.terminal.moveToEditor", Vec::new(), window, cx);
assert_eq!(workbench.active_terminal_editor(), Some(id));
assert!(workbench.terminal_view.groups.is_empty());
assert_eq!(workbench.host.terminal_tabs.len(), 1);
workbench.execute_command("workbench.action.closeActiveEditor", Vec::new(), window, cx);
});
cx.run_until_parked();
// TerminalEditorInput.dispose: closing the editor kills its terminal.
workbench.update(cx, |workbench, _| {
assert!(workbench.terminal_view.instance(id).is_none());
assert!(workbench.terminal_view.editor_instances.is_empty());
assert_eq!(workbench.terminal_view.active_editor, None);
});
}
#[gpui::test]
fn a_panel_terminal_moves_into_a_new_editor_window(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let dir = std::env::temp_dir().join(format!("code-gpui-terminal-new-window-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));
let id = workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.lifecycle.backups.home = Some(dir.join("Backups/1712000000123"));
workbench.execute_command("workbench.action.createTerminalEditorSameGroup", Vec::new(), window, cx);
let id = workbench.active_terminal_editor().unwrap();
// terminalUri.ts `getTerminalUri`: the workspace id is the window's backup folder.
assert_eq!(workbench.editors.active().unwrap().document().uri_string(), format!("vscode-terminal:/1712000000123/{id}"));
workbench.execute_command("workbench.action.terminal.moveToTerminalPanel", Vec::new(), window, cx);
workbench.execute_command("workbench.action.terminal.moveIntoNewWindow", Vec::new(), window, cx);
id
});
cx.run_until_parked();
assert_eq!(cx.windows().len(), 2);
workbench.update(cx, |workbench, _| {
assert!(workbench.terminal_view.groups.is_empty());
let part = workbench.auxiliary_windows.part_ids().next().expect("an editor window opened");
let groups = workbench.part_groups(part);
let tabs: Vec<Option<u32>> = workbench.editors.group_tabs(groups[0]).0.iter().map(|editor| terminal_editor_id(editor)).collect();
assert_eq!(tabs, [Some(id)]);
assert!(workbench.terminal_view.instance(id).is_some(), "moving keeps the process");
});
}
/// The icon-picker ui-pair: the reference's search input is 25px from border to border, the icons start below it.
#[gpui::test]
fn the_icon_picker_search_is_a_bare_input_box(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx));
cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.execute_command("workbench.action.createTerminalEditorSameGroup", Vec::new(), window, cx);
workbench.execute_command("workbench.action.terminal.changeIcon", Vec::new(), window, cx);
});
cx.run_until_parked();
assert_eq!(cx.debug_bounds("icon-select-search").expect("the picker shows its search").size.height, gpui::px(25.));
assert!(workbench.read_with(cx, |workbench, _| workbench.scrollable_drawn("icon-select-icons")), "icon-select-icons sits in a ScrollableElement");
// 2 + 3 + 18.2 (line-height 1.4 at 13px) + 3 = 26.2, which Chrome snaps to 26 at 2x; a line height ceiled to
// the device pixel made it 26.5 and moved the whole picker down.
assert_eq!(cx.debug_bounds("quick-input-title").expect("the picker has a title").size.height, gpui::px(26.));
// The icon name line is the workbench's 1.4em (18.2, edges snapped here to 18.5), not GPUI's 1.618 default (21)
// that put it 1.5px low.
workbench.update(cx, |workbench, cx| {
workbench.icon_select.picker.as_mut().unwrap().focus_next();
cx.notify();
});
cx.run_until_parked();
assert_eq!(cx.debug_bounds("icon-select-id-label").expect("the picker names the focused icon").size.height, gpui::px(18.5));
}
/// quickinput.test.ts "custom content is exclusive to QuickWidget and cleared when switching controls": a quick pick
/// shown over the icon picker's quick widget drops the widget's content.
#[gpui::test]
fn a_quick_pick_shown_over_the_icon_picker_drops_its_content(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx));
workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.execute_command("workbench.action.createTerminalEditorSameGroup", Vec::new(), window, cx);
workbench.execute_command("workbench.action.terminal.changeIcon", Vec::new(), window, cx);
});
cx.run_until_parked();
assert!(cx.debug_bounds("icon-select-search").is_some(), "the quick widget shows the icon picker");
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.showCommands", Vec::new(), window, cx)));
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.quick_inputs.current().is_some()), "the command palette shows");
assert!(cx.debug_bounds("icon-select-search").is_none(), "the quick pick drops the widget's content");
assert!(workbench.read_with(cx, |workbench, _| workbench.icon_select.picker.is_none()), "the widget's content is gone, not only hidden");
}
/// The tab-menu ui-pair: terminal.initialHint.contribution.ts keeps the hint once a prompt starts, also while the
/// context menu has the focus.
#[gpui::test]
fn the_initial_hint_stays_when_the_terminal_loses_focus(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx));
workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.execute_command("workbench.action.createTerminalEditorSameGroup", Vec::new(), window, cx);
// The hint names the Trigger Suggest keybinding.
workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), app_root.join("keybindings-unused.json"));
let id = workbench.active_terminal_editor().unwrap();
let colors = crate::terminal::colors::TerminalColors::new(&workbench.theme);
workbench.terminal_view.instance_mut(id).unwrap().process(b"\x1b]633;A\x07$ \x1b]633;B\x07", &colors);
});
cx.run_until_parked();
assert!(cx.debug_bounds("terminal-initial-hint").is_some(), "the started prompt shows the hint");
let elsewhere = workbench.update(cx, |_, cx| cx.focus_handle());
workbench.update_in(cx, |_, window, cx| window.focus(&elsewhere, cx));
cx.run_until_parked();
assert!(cx.debug_bounds("terminal-initial-hint").is_some(), "the hint stays without the focus");
// keybindingLabel.css: the first key has no left margin, so "^" follows "Show suggestions " directly; the
// last selector match is "Space", past the 24px "^" and the 2 + 2px between keys.
let link = cx.debug_bounds("terminal-initial-hint-suggest").expect("the hint offers suggestions");
let key = cx.debug_bounds("terminal-initial-hint-key").expect("the hint names the keybinding");
assert_eq!(key.origin.x, link.origin.x + link.size.width + gpui::px(28.));
assert_eq!(key.size.height, gpui::px(18.));
// One space between ". " and "Start typing to dismiss or ", as HTML collapses upstream's two.
let char_width = link.size.width / "Show suggestions ".len() as f32;
let after = cx.debug_bounds("terminal-initial-hint-suggest-after").expect("the hint is not compact");
let dont_show = cx.debug_bounds("terminal-initial-hint-disable").expect("the hint offers to stop");
let prose = dont_show.origin.x - (after.origin.x + after.size.width);
assert!((prose - char_width * "Start typing to dismiss or ".len() as f32).abs() < char_width / 2., "{prose:?} is one space too wide");
assert_eq!(dont_show.origin.y, link.origin.y, "the prose sits on the suggestion's line, not at the top of the keys");
// At about 530px the 563px line breaks inside the prose, as inline text does, not before "Start typing".
let hint = cx.debug_bounds("terminal-initial-hint").unwrap();
let viewport = cx.update(|window, _| window.viewport_size());
cx.simulate_resize(gpui::size(viewport.width - hint.size.width + gpui::px(534.), viewport.height));
cx.run_until_parked();
// The grid takes its new column count in that paint; the hint follows on the next frame.
cx.update(|window, _| window.refresh());
cx.run_until_parked();
let width = cx.debug_bounds("terminal-initial-hint").unwrap().size.width;
assert!(width > gpui::px(504.) && width < gpui::px(567.), "{width:?} is between the compact and the one-line hint");
let link = cx.debug_bounds("terminal-initial-hint-suggest").unwrap();
assert_eq!(cx.debug_bounds("terminal-initial-hint-disable").unwrap().origin.y, link.origin.y, "\"don't\" still fits the first line");
assert!(cx.debug_bounds("terminal-initial-hint-again").unwrap().origin.y > link.origin.y, "\"again.\" wraps");
}
/// The content-width ui-pair: a terminal tab's icon is a `predefined-file-icon`, a 13px glyph 3px into its box.
#[gpui::test]
fn a_terminal_editor_tab_draws_its_icon_as_a_predefined_file_icon(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let extensions = [scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap(), scan_extension(&app_root.join("extensions/theme-seti"), true).unwrap()];
let theme = load_theme(&extensions, "Dark Modern").unwrap();
let (workbench, cx) = cx.add_window_view(|_, cx| {
let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
workbench.file_icons = crate::file_icons::FileIconTheme::load(&extensions, "vs-seti").ok();
workbench
});
workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.execute_command("workbench.action.createTerminalEditorSameGroup", Vec::new(), window, cx);
});
cx.run_until_parked();
// The default profile's icon: `terminal` for zsh, `terminal-bash` for bash.
let icon_id = workbench.update(cx, |workbench, _| {
let id = workbench.active_terminal_editor().unwrap();
format!("codicon-{}", workbench.terminal_view.instance(id).unwrap().icon())
});
let icon = cx.debug_bounds(icon_id.leak()).expect("the tab shows the terminal icon");
assert_eq!(icon.size, gpui::size(gpui::px(13.), gpui::px(13.)));
let icon_box = cx.debug_bounds("predefined-file-icon").expect("the icon sits in its 16px box");
assert_eq!(icon.origin - icon_box.origin, gpui::point(gpui::px(3.), gpui::px(5.)), "3px in, floor((24 - 13) / 2) down");
}
#[gpui::test]
fn a_terminal_tab_changes_its_color_and_icon(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let dir = std::env::temp_dir().join(format!("code-gpui-terminal-editor-pickers-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));
let is_color_picker = |owner: &Owner| matches!(owner, Owner::Terminal(TerminalInput::Color { .. }));
workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.execute_command("workbench.action.createTerminalEditorSameGroup", Vec::new(), window, cx);
let id = workbench.active_terminal_editor().unwrap();
let context = workbench.key_context(window);
let titles: Vec<String> = crate::menus::menu_actions(&workbench.menus, MenuId::EditorTitleContext, &context)
.into_iter()
.filter_map(|action| if let MenuAction::Command { title, .. } = action { Some(title) } else { None })
.collect();
let start = titles.iter().position(|title| title == "Change Color...").expect("terminalMenus.ts EditorTitleContext");
assert_eq!(titles[start..start + 5], ["Change Color...", "Change Icon...", "Move Terminal into Panel", "Rename...", "Toggle Size to Content Width"]);
let tab_titles: Vec<String> = crate::menus::menu_actions(&workbench.menus, MenuId::TerminalTabContext, &context)
.into_iter()
.map(|action| if let MenuAction::Command { title, .. } = action { title } else { "-".into() })
.collect();
assert_eq!(tab_titles, ["Split Terminal", "Move Terminal into Editor Area", "Move Terminal into New Window", "-", "Change Color...", "Change Icon...", "Rename...", "Toggle Size to Content Width", "-", "Kill Terminal"]);
workbench.execute_command("workbench.action.terminal.changeColorActiveTab", Vec::new(), window, cx);
let picker = workbench.quick_inputs.find_id(is_color_picker).expect("the tab menu's Change Color opens the color picker");
workbench.terminal_input_event(picker, Event::Hide, window, cx);
workbench.flush_quick_input_events(window, cx);
assert!(workbench.quick_inputs.find_id(is_color_picker).is_none());
// terminalIcon.ts `getStandardColors`: the eight non-bright ANSI colors, then Reset to default.
workbench.execute_command("workbench.action.terminal.changeColor", Vec::new(), window, cx);
let picker = workbench.quick_inputs.find_id(is_color_picker).expect("the color picker shows");
let labels: Vec<String> = workbench.quick_inputs.get(picker).unwrap().items().iter().map(|entry| match entry {
Entry::Item(item) => item.label.clone(),
_ => "---".into(),
}).collect();
assert_eq!(labels, ["$(circle-filled) Black", "$(circle-filled) Red", "$(circle-filled) Green", "$(circle-filled) Yellow", "$(circle-filled) Blue", "$(circle-filled) Magenta", "$(circle-filled) Cyan", "$(circle-filled) White", "---", "Reset to default"]);
workbench.quick_inputs.get_mut(picker).unwrap().set_selected_items(&[1]);
workbench.terminal_input_event(picker, Event::Accept(false), window, cx);
assert_eq!(workbench.terminal_view.instance(id).unwrap().launch.color.as_deref(), Some("terminal.ansiRed"));
workbench.flush_quick_input_events(window, cx);
assert!(workbench.quick_inputs.find_id(is_color_picker).is_none());
// iconPicker.ts: the quick widget picks an icon, Reset to default drops it for the launch config's.
workbench.execute_command("workbench.action.terminal.changeIcon", Vec::new(), window, cx);
assert!(matches!(workbench.icon_select.picker.as_ref().map(|picker| &picker.target), Some(IconTarget::Terminal(target)) if *target == id));
workbench.select_icon(Some("rocket"), window, cx);
assert_eq!(workbench.terminal_view.instance(id).unwrap().icon(), "rocket");
assert!(workbench.icon_select.picker.is_none());
assert!(workbench.quick_inputs.find_id(|owner| matches!(owner, Owner::Terminal(TerminalInput::Icon))).is_none());
workbench.execute_command("workbench.action.terminal.changeIcon", Vec::new(), window, cx);
workbench.select_icon(None, window, cx);
let instance = workbench.terminal_view.instance(id).unwrap();
assert_eq!(instance.icon(), instance.launch.icon.as_deref().unwrap_or("terminal"));
// terminalInstance.ts `toggleSizeToContentWidth`: a 120 character line wrapped at 80 columns fixes 120.
let colors = crate::terminal::colors::TerminalColors::new(&workbench.theme);
workbench.terminal_view.instance_mut(id).unwrap().process("x".repeat(120).as_bytes(), &colors);
workbench.execute_command("workbench.action.terminal.sizeToContentWidth", Vec::new(), window, cx);
assert_eq!(workbench.terminal_view.instance(id).unwrap().fixed_cols, Some(120));
workbench.execute_command("workbench.action.terminal.sizeToContentWidth", Vec::new(), window, cx);
assert_eq!(workbench.terminal_view.instance(id).unwrap().fixed_cols, None);
});
}
#[gpui::test]
fn a_terminal_editor_revives_with_its_history_after_a_restart(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let dir = std::env::temp_dir().join(format!("code-gpui-terminal-editor-restore-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
let new_workbench = || {
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let (app_root, settings) = (app_root.clone(), settings.clone());
move |_: &mut gpui::Window, cx: &mut gpui::Context<Workbench>| Workbench::new(theme, app_root, None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx)
};
let screen = |workbench: &Workbench, id: u32| {
use ghostty_vt::{Column, Line, Point};
let term = &workbench.terminal_view.instance(id).unwrap().term;
(0..term.screen_lines() as i32).map(|line| (0..term.columns()).map(|column| term.cell(Point::new(Line(line), Column(column))).c).collect::<String>().trim_end().to_owned()).collect::<Vec<_>>()
};
// terminalService.ts `_onWillShutdown`: the editor's terminal and its buffer are stored on quit.
let (first, first_cx) = cx.add_window_view(new_workbench());
let storage = first.update_in(first_cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.execute_command("workbench.action.createTerminalEditorSameGroup", Vec::new(), window, cx);
let id = workbench.active_terminal_editor().unwrap();
let colors = crate::terminal::colors::TerminalColors::new(&workbench.theme);
let instance = workbench.terminal_view.instance_mut(id).unwrap();
instance.process(b"$ echo restored-text\r\nrestored-text\r\n$ ", &colors);
instance.launch.color = Some("terminal.ansiRed".into());
workbench.save_editor_part_state();
workbench.persist_terminal_state();
workbench.workspace_storage.clone()
});
// terminalEditorSerializer.ts `deserialize` and ptyService.ts `_reviveTerminalProcess` on the next start.
let (second, second_cx) = cx.add_window_view(new_workbench());
second.update_in(second_cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.workspace_storage = storage;
workbench.restore_editor_part_state();
workbench.revive_terminals(window, cx);
let id = workbench.active_terminal_editor().expect("the terminal editor is restored");
assert_eq!(workbench.terminal_view.instance(id).unwrap().launch.color.as_deref(), Some("terminal.ansiRed"));
assert_eq!(screen(workbench, id)[..5], ["$ echo restored-text", "restored-text", "$", " * History restored", ""]);
assert!(workbench.workspace_storage.lock().unwrap().get("terminal.integrated.bufferState").is_none(), "the buffers are revived once");
});
}
/// terminalService.ts `_saveState` and `_recreateTerminalGroups`: the panel's groups and split panes come back after a
/// restart with their history, the active group and each group's active pane as they were.
#[gpui::test]
fn panel_terminals_revive_in_their_groups_after_a_restart(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let dir = std::env::temp_dir().join(format!("code-gpui-terminal-panel-restore-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
let new_workbench = || {
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let (app_root, settings) = (app_root.clone(), settings.clone());
move |_: &mut gpui::Window, cx: &mut gpui::Context<Workbench>| Workbench::new(theme, app_root, None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx)
};
let first_line = |workbench: &Workbench, id: u32| {
use ghostty_vt::{Column, Line, Point};
let term = &workbench.terminal_view.instance(id).unwrap().term;
(0..8).map(|column| term.cell(Point::new(Line(0), Column(column))).c).collect::<String>()
};
let (first, first_cx) = cx.add_window_view(new_workbench());
let storage = first.update_in(first_cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.execute_command("workbench.action.terminal.new", Vec::new(), window, cx);
workbench.execute_command("workbench.action.terminal.new", Vec::new(), window, cx);
workbench.execute_command("workbench.action.terminal.split", Vec::new(), window, cx);
let groups = workbench.terminal_view.group_instances();
let [single, split] = [groups[0].clone(), groups[1].clone()];
assert_eq!(split.len(), 2);
let colors = crate::terminal::colors::TerminalColors::new(&workbench.theme);
for (id, text) in [(single[0], "single-1"), (split[0], "split-l1"), (split[1], "split-r1")] {
workbench.terminal_view.instance_mut(id).unwrap().process(format!("\x1b[H\x1b[2J{text}\r\n").as_bytes(), &colors);
}
// The left pane of the split group is active, then the single terminal's group.
workbench.terminal_view.set_active(split[0]);
workbench.terminal_view.set_active(single[0]);
workbench.persist_terminal_state();
workbench.workspace_storage.clone()
});
let (second, second_cx) = cx.add_window_view(new_workbench());
second.update_in(second_cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
workbench.workspace_storage = storage;
workbench.revive_terminals(window, cx);
let groups = workbench.terminal_view.group_instances();
let lines: Vec<Vec<String>> = groups.iter().map(|group| group.iter().map(|id| first_line(workbench, *id)).collect()).collect();
assert_eq!(lines, [vec!["single-1"], vec!["split-l1", "split-r1"]]);
assert_eq!(workbench.terminal_view.group_active_instance_id(), Some(groups[0][0]), "the active group is the single terminal's");
workbench.terminal_view.active_group = 1;
assert_eq!(workbench.terminal_view.group_active_instance_id(), Some(groups[1][0]), "the split group's active pane is its left one");
let storage = workbench.workspace_storage.lock().unwrap();
assert!(storage.get("terminal.integrated.bufferState").is_none() && storage.get("terminal.integrated.layoutInfo").is_none(), "the terminals are revived once");
});
}
/// terminalProfileQuickpick.ts's contributed section and terminalService.ts `createContributedTerminalProfile`: the
/// pick activates the extension, asks its registered provider, and the terminal it creates opens where it was asked.
#[gpui::test]
fn a_contributed_profile_is_picked_and_created_by_its_provider(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "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, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
let is_profile_picker = |owner: &Owner| matches!(owner, Owner::Terminal(TerminalInput::Profiles { .. }));
let profiles = serde_json::json!([
{ "id": "ext.shell", "title": "Ext Shell", "icon": "rocket" },
{ "id": "ext.themed", "title": "Themed", "icon": { "light": "l.svg", "dark": "d.svg" } },
]);
workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
let description = serde_json::json!({ "contributes": { "terminal": { "profiles": profiles } } });
workbench.extensions.push(exthost::scan::ScannedExtension { id: "Pub.ext".into(), location: app_root.clone(), description });
let register = exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadTerminalService", method: "$registerProfileProvider".into(), args: vec![serde_json::json!("ext.shell"), serde_json::json!("Pub.ext")] };
drop(workbench.handle_terminal_request(register, window, cx));
workbench.execute_command("workbench.action.terminal.newWithProfile", Vec::new(), window, cx);
let picker = workbench.quick_inputs.find_id(is_profile_picker).expect("the profile picker shows");
let items = workbench.quick_inputs.get(picker).unwrap().items().to_vec();
let contributed = items.iter().position(|entry| matches!(entry, Entry::Separator(Some(label)) if label == "contributed")).expect("a contributed section");
// An icon of `{ light, dark }` strings is no URI, so `hasValidTerminalIcon` drops that profile.
let Entry::Item(item) = &items[contributed + 1] else { panic!("the contributed profile follows its separator") };
assert_eq!(item.label, "$(rocket) Ext Shell");
assert!(!items.iter().any(|entry| matches!(entry, Entry::Item(item) if item.label.contains("Themed"))));
workbench.quick_inputs.get_mut(picker).unwrap().set_selected_items(&[item.handle]);
workbench.terminal_input_event(picker, Event::Accept(false), window, cx);
});
cx.run_until_parked();
let activation = messages.try_iter().find(|message| message.method == "$activateByEvent" && message.args[0] == "onTerminalProfile:ext.shell").expect("the extension activates");
let _ = activation.reply.expect("a call").send(Ok(serde_json::Value::Null));
cx.run_until_parked();
let create = messages.try_iter().find(|message| message.method == "$createContributedProfileTerminal").expect("the provider is asked");
assert_eq!(create.args, [serde_json::json!("ext.shell"), serde_json::json!({ "icon": "rocket", "location": 1 })]);
// extHostTerminalService.ts `createTerminalFromOptions` answers with `$createTerminal`, here in the editor area.
workbench.update_in(cx, |workbench, window, cx| {
let config = serde_json::json!({ "name": "Ext Shell", "isExtensionCustomPtyTerminal": true, "location": 2 });
let request = exthost::session::ForwardedRequest { req: 2, proxy: "MainThreadTerminalService", method: "$createTerminal".into(), args: vec![serde_json::json!("ext-1"), config] };
drop(workbench.handle_terminal_request(request, window, cx));
let id = workbench.active_terminal_editor().expect("TerminalLocation.Editor opens a terminal editor");
assert!(workbench.terminal_view.groups.is_empty());
assert_eq!(workbench.terminal_view.instance(id).unwrap().launch.ext_host_terminal_id.as_deref(), Some("ext-1"));
});
}
/// terminalActions.ts `NewWithProfile` with `{ profileName, location }`: the named profile opens where asked, no
/// picker; an unknown name is an error.
#[gpui::test]
fn new_with_profile_creates_the_named_profile(cx: &mut TestAppContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
let (sender, _messages) = std::sync::mpsc::channel();
let dir = std::env::temp_dir().join(format!("code-gpui-new-with-profile-{}", std::process::id()));
let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(sender), cx));
workbench.update_in(cx, |workbench, window, cx| {
workbench.auxiliary_windows.main_window = Some(window.window_handle());
let profiles = serde_json::json!({ "Named": { "path": "/bin/cat", "color": "terminal.ansiRed" } });
workbench.settings.lock().unwrap().update_value_derived("terminal.integrated.profiles.osx", Some(&profiles)).unwrap();
let outcome = workbench.execute_command("workbench.action.terminal.newWithProfile", vec![serde_json::json!({ "profileName": "Missing" })], window, cx);
assert!(matches!(&outcome, crate::commands::Outcome::Ready(Err(error)) if error.to_string().contains("Could not find terminal profile")));
workbench.execute_command("workbench.action.terminal.newWithProfile", vec![serde_json::json!({ "profileName": "Named", "location": "editor" })], window, cx);
assert!(workbench.quick_inputs.find_id(|owner| matches!(owner, Owner::Terminal(TerminalInput::Profiles { .. }))).is_none(), "no picker");
let id = workbench.active_terminal_editor().expect("location editor opens a terminal editor");
let launch = &workbench.terminal_view.instance(id).unwrap().launch;
assert_eq!((launch.executable.as_path(), launch.color.as_deref()), (Path::new("/bin/cat"), Some("terminal.ansiRed")));
});
let _ = std::fs::remove_dir_all(dir);
}