Visual Studio Code, rebuilt in Rust
Rust
use std::path::{Path, PathBuf};
use exthost::scan::scan_extension;
use gpui::{MouseButton, TestAppContext, VisualTestContext, point, px};
use serde_json::json;
use crate::editor::{Position, Selection};
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::menus::MenuAction;
use crate::theme::load_theme;
use crate::workbench::Workbench;
use crate::workbench::editor_view::MouseDown;
fn workbench_with<'a>(name: &str, files: &[&str], cx: &'a mut TestAppContext) -> (PathBuf, gpui::Entity<Workbench>, &'a mut VisualTestContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
let theme = load_theme(&[themes], "Dark Modern").unwrap();
let dir = std::env::temp_dir().join(format!("code-gpui-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let paths: Vec<PathBuf> = files.iter().map(|file| dir.join(file)).collect();
for path in &paths {
std::fs::write(path, "hello world\nsecond line").unwrap();
}
let keybindings = dir.join("keybindings.json");
let (workbench, cx) = cx.add_window_view(|window, 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.skip_dialogs = true;
workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), keybindings);
for path in &paths {
workbench.open_file(path.clone(), true, window, cx);
}
workbench
});
cx.run_until_parked();
(dir, workbench, cx)
}
fn menu_titles(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<String> {
workbench.read_with(cx, |workbench, _| {
let menu = workbench.context_menu.as_ref().expect("a context menu shows");
menu.levels[0].actions
.iter()
.map(|action| match action {
MenuAction::Command { title, enabled: true, .. } => title.clone(),
MenuAction::Command { title, .. } => format!("({title})"),
MenuAction::Submenu { title, .. } => format!("{title} >"),
_ => "---".into(),
})
.collect()
})
}
fn open_names(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<String> {
workbench.read_with(cx, |workbench, _| workbench.editors.editors.iter().map(|editor| editor.document().name()).collect())
}
#[gpui::test]
fn the_editor_menu_moves_the_cursor_to_the_pointer_unless_a_selection_holds_it(cx: &mut TestAppContext) {
let (_dir, workbench, cx) = workbench_with("editor-menu", &["a.txt"], cx);
let pointer = point(px(400.), px(200.));
workbench.update_in(cx, |workbench, window, cx| workbench.show_editor_context_menu(1, 3.2, pointer, window, cx));
assert_eq!(menu_titles(&workbench, cx), ["(Go to Definition)", "(Go to Declaration)", "(Go to Type Definition)", "(Go to Implementations)", "(Go to References)", "Peek >", "---", "Change All Occurrences", "Refactor...", "---", "Cut", "Copy", "Paste", "---", "Command Palette..."]);
let selections = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selections.clone());
assert_eq!(selections(cx), [Selection::caret(Position::new(1, 3))]);
cx.simulate_keystrokes("escape");
let selected = Selection { anchor: Position::new(0, 0), head: Position::new(0, 5) };
workbench.update(cx, |workbench, _| workbench.editors.active_mut().unwrap().selections = vec![selected]);
workbench.update_in(cx, |workbench, window, cx| workbench.show_editor_context_menu(0, 5.0, pointer, window, cx));
assert_eq!(selections(cx), [selected]);
assert!(workbench.update_in(cx, |workbench, window, _| workbench.context_menu.is_some() && !workbench.editor_focus.is_focused(window)));
cx.simulate_keystrokes("escape");
assert!(workbench.update_in(cx, |workbench, window, _| workbench.context_menu.is_none() && workbench.editor_focus.is_focused(window)));
}
#[gpui::test]
fn the_tab_menu_closes_around_the_right_clicked_editor(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("tab-menu", &["a.txt", "b.txt", "c.txt", "d.txt"], cx);
let pointer = super::point_anchor(point(px(200.), px(50.)));
workbench.update_in(cx, |workbench, window, cx| workbench.show_tab_context_menu(1, pointer, window, cx));
assert_eq!(menu_titles(&workbench, cx), ["Close", "Close Others", "Close to the Right", "Close Saved", "Close All", "---", "Copy Path", "Copy Relative Path", "---", "Reopen Editor With...", "---", "Reveal in Finder", "Reveal in Explorer View", "---", "(Keep Open)", "Pin", "---", "Split Right", "Split & Move >", "---", "Move into New Window", "Copy into New Window"]);
cx.simulate_keystrokes("escape");
workbench.update_in(cx, |workbench, window, cx| workbench.show_tab_context_menu(3, pointer, window, cx));
assert_eq!(menu_titles(&workbench, cx)[2], "(Close to the Right)");
cx.simulate_keystrokes("escape");
let run = |command: &str, editor_index: usize, cx: &mut VisualTestContext| {
let args = vec![json!({ "scheme": "file", "path": "" }), json!({ "groupId": 0, "editorIndex": editor_index })];
workbench.update_in(cx, |workbench, window, cx| workbench.execute_command(command, args, window, cx));
cx.run_until_parked();
};
run("workbench.action.closeEditorsToTheRight", 2, cx);
assert_eq!(open_names(&workbench, cx), ["a.txt", "b.txt", "c.txt"]);
run("workbench.action.closeActiveEditor", 0, cx);
assert_eq!(open_names(&workbench, cx), ["b.txt", "c.txt"]);
run("workbench.action.closeOtherEditors", 1, cx);
assert_eq!(open_names(&workbench, cx), ["c.txt"]);
// Close Saved leaves a dirty editor; Close All asks for it (Don't Save while dialogs are skipped).
workbench.update_in(cx, |workbench, window, cx| {
workbench.open_file(dir.join("a.txt"), true, window, cx);
window.focus(&workbench.editor_focus, cx);
});
cx.simulate_input("x");
run("workbench.action.closeUnmodifiedEditors", 0, cx);
assert_eq!(open_names(&workbench, cx), ["a.txt"]);
run("workbench.action.closeEditorsInGroup", 0, cx);
assert!(open_names(&workbench, cx).is_empty());
assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "hello world\nsecond line");
}
/// editor.contribution.ts: the editor title's `...` and the empty group's context menu.
#[gpui::test]
fn the_title_more_menu_and_the_empty_group_menu_show_their_items(cx: &mut TestAppContext) {
let (_dir, workbench, cx) = workbench_with("title-more", &["a.txt"], cx);
let anchor = gpui::Bounds::new(point(px(900.), px(40.)), gpui::size(px(22.), px(22.)));
workbench.update_in(cx, |workbench, window, cx| workbench.show_editor_title_menu(anchor, false, window, cx));
assert_eq!(menu_titles(&workbench, cx), ["Show Opened Editors", "---", "Close All", "Close Saved", "---", "Enable Preview Editors", "---", "Lock Group", "---", "Configure Editors"]);
let group = workbench.read_with(cx, |workbench, _| workbench.editor_group_id());
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.editor_groups.title_menu_group), Some(group));
cx.simulate_keystrokes("escape");
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.closeEditorsInGroup", vec![], window, cx)));
cx.run_until_parked();
workbench.update_in(cx, |workbench, window, cx| workbench.show_empty_group_context_menu(group, point(px(400.), px(300.)), window, cx));
assert_eq!(menu_titles(&workbench, cx), ["New Text File", "Open File...", "---", "New Terminal", "---", "Split Up", "Split Down", "Split Left", "Split Right", "---", "New Window", "---", "Lock Group"]);
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.editor_groups.title_menu_group), None);
}
/// multiEditorTabsControl.ts and editor.contribution.ts: a right press in the tab bar off a tab shows
/// `MenuId.EditorTabsBarContext`; its Tab Bar submenu checks the `workbench.editor.showTabs` value.
#[gpui::test]
fn the_tab_bar_menu_switches_the_tabs_mode(cx: &mut TestAppContext) {
let (_dir, workbench, cx) = workbench_with("tabs-bar-menu", &["a.txt"], cx);
cx.update(|window, _| window.refresh());
cx.run_until_parked();
let strip = cx.debug_bounds("editor-tab-strip").expect("the tab strip");
let tab_close = cx.debug_bounds("tab-action-0").expect("the tab's close action");
cx.simulate_mouse_down(point(tab_close.right() + px(40.), strip.center().y), gpui::MouseButton::Right, gpui::Modifiers::none());
assert_eq!(menu_titles(&workbench, cx), ["New Text File", "Open File...", "---", "New Terminal", "---", "Split Up", "Split Down", "Split Left", "Split Right", "---", "Move into New Window", "Copy into New Window", "---", "Tab Bar >", "Editor Actions Position >", "---", "Configure Tabs"]);
let tab_bar = workbench.read_with(cx, |workbench, _| match &workbench.context_menu.as_ref().unwrap().levels[0].actions[13] {
MenuAction::Submenu { actions, .. } => actions.clone(),
other => panic!("Tab Bar is a submenu: {other:?}"),
});
let checked: Vec<_> = tab_bar.iter().map(|action| match action {
MenuAction::Command { id, title, checked, .. } => (id.as_str(), title.as_str(), *checked),
other => panic!("{other:?}"),
}).collect();
assert_eq!(checked, [("workbench.action.showMultipleEditorTabs", "Multiple Tabs", true), ("workbench.action.showEditorTab", "Single Tab", false), ("workbench.action.hideEditorTabs", "Hidden", false)]);
}
/// editorCommands.ts: Pin Editor sticks the editor (Cmd+K Shift+Enter toggles it), the group's mass closes leave it,
/// Cmd+W opens the next non-sticky editor instead (`preventPinnedEditorClose`), Close Pinned Editor closes it.
#[gpui::test]
fn pinned_editors_go_first_and_survive_the_mass_closes(cx: &mut TestAppContext) {
let (_dir, workbench, cx) = workbench_with("pinned-tabs", &["a.txt", "b.txt", "c.txt"], cx);
let sticky = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.editors.iter().map(|editor| editor.sticky).collect::<Vec<_>>());
let active = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().document().name());
workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.editor_focus, cx));
cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-k shift-enter"));
assert_eq!(open_names(&workbench, cx), ["c.txt", "a.txt", "b.txt"]);
assert_eq!(sticky(cx), [true, false, false]);
workbench.update_in(cx, |workbench, window, cx| workbench.show_tab_context_menu(0, super::point_anchor(point(px(200.), px(50.))), window, cx));
assert!(menu_titles(&workbench, cx).contains(&"Unpin".to_string()));
cx.simulate_keystrokes("escape");
cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-w"));
assert_eq!(open_names(&workbench, cx).len(), 3, "the keyboard does not close a sticky editor");
assert_eq!(active(cx), "b.txt", "the most recent non-sticky editor opens instead");
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.closeEditorsInGroup", vec![], window, cx)));
cx.run_until_parked();
assert_eq!(open_names(&workbench, cx), ["c.txt"]);
workbench.update_in(cx, |workbench, window, cx| {
window.focus(&workbench.editor_focus, cx);
drop(workbench.execute_command("workbench.action.closeAllEditors", vec![], window, cx));
});
cx.run_until_parked();
assert_eq!(open_names(&workbench, cx), ["c.txt"]);
workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.editor_focus, cx));
cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-k shift-enter"));
assert_eq!(sticky(cx), [false], "the chord unpins a pinned editor");
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.pinEditor", vec![], window, cx)));
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.closeActivePinnedEditor", vec![], window, cx)));
cx.run_until_parked();
assert!(open_names(&workbench, cx).is_empty());
}
#[gpui::test]
fn the_host_moves_and_closes_tabs_by_their_ids(cx: &mut TestAppContext) {
let (_dir, workbench, cx) = workbench_with("editor-tabs", &["a.txt", "b.txt", "c.txt"], cx);
let request = |method: &str, args: Vec<serde_json::Value>, cx: &mut VisualTestContext| {
let request = exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadEditorTabs", method: method.into(), args };
let outcome = workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(request, window, cx));
let crate::commands::Outcome::Ready(result) = outcome else { panic!("{method} waits") };
result
};
let id = |name: &str, cx: &mut VisualTestContext| {
workbench.read_with(cx, |workbench, _| crate::host_sync::tab_id(0, workbench.editors.editors.iter().find(|editor| editor.document().name() == name).unwrap()))
};
let a = id("a.txt", cx);
// An index past the tabs moves the tab last, and the move pins it.
assert_eq!(request("$moveTab", vec![json!(a), json!(7), json!(0)], cx), Ok(json!(null)));
assert_eq!(open_names(&workbench, cx), ["b.txt", "c.txt", "a.txt"]);
assert!(workbench.read_with(cx, |workbench, _| !workbench.editors.editors[2].preview));
assert!(request("$moveTab", vec![json!("missing"), json!(0), json!(0)], cx).is_err());
// A view column past the last group adds a group beside it (`columnToEditorGroup`), and the tab moves there.
let group_names = |cx: &mut VisualTestContext| {
workbench.read_with(cx, |workbench, _| {
let groups = workbench.groups_in_grid_order();
groups.iter().map(|group| workbench.editors.group_tabs(*group).0.iter().map(|editor| editor.document().name()).collect::<Vec<_>>()).collect::<Vec<_>>()
})
};
let c = id("c.txt", cx);
assert_eq!(request("$moveTab", vec![json!(c), json!(0), json!(1)], cx), Ok(json!(null)));
assert_eq!(group_names(cx), [vec!["b.txt", "a.txt"], vec!["c.txt"]]);
let (second, c) = workbench.read_with(cx, |workbench, _| {
let second = workbench.groups_in_grid_order()[1];
(second, crate::host_sync::tab_id(second, &workbench.editors.group_tabs(second).0[0]))
});
assert_ne!(second, 0);
// Back into the first group at index 1: the host's index, not after the active tab; the emptied group closes.
assert_eq!(request("$moveTab", vec![json!(c), json!(1), json!(0)], cx), Ok(json!(null)));
assert_eq!(group_names(cx), [vec!["b.txt", "c.txt", "a.txt"]]);
let b = id("b.txt", cx);
assert_eq!(request("$closeTab", vec![json!([b, a])], cx), Ok(json!(true)));
assert_eq!(open_names(&workbench, cx), ["c.txt"]);
assert_eq!(request("$closeGroup", vec![json!([0])], cx), Ok(json!(true)));
assert!(open_names(&workbench, cx).is_empty());
}
/// mainThreadEditorTabs.ts `$closeTab` and `$closeGroup` close in every group they name, not only the first.
#[gpui::test]
fn the_host_closes_tabs_and_groups_in_every_named_group(cx: &mut TestAppContext) {
let (_dir, workbench, cx) = workbench_with("editor-tabs-groups", &["a.txt", "b.txt", "c.txt", "d.txt"], cx);
let request = |method: &str, args: Vec<serde_json::Value>, cx: &mut VisualTestContext| {
let request = exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadEditorTabs", method: method.into(), args };
let outcome = workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(request, window, cx));
let crate::commands::Outcome::Ready(result) = outcome else { panic!("{method} waits") };
result
};
let id = |name: &str, cx: &mut VisualTestContext| {
workbench.read_with(cx, |workbench, _| {
let group = workbench.groups_in_grid_order().into_iter().find(|group| workbench.editors.group_tabs(*group).0.iter().any(|editor| editor.document().name() == name)).unwrap();
crate::host_sync::tab_id(group, workbench.editors.group_tabs(group).0.iter().find(|editor| editor.document().name() == name).unwrap())
})
};
let group_names = |cx: &mut VisualTestContext| {
workbench.read_with(cx, |workbench, _| {
let groups = workbench.groups_in_grid_order();
groups.iter().map(|group| workbench.editors.group_tabs(*group).0.iter().map(|editor| editor.document().name()).collect::<Vec<_>>()).collect::<Vec<_>>()
})
};
for name in ["c.txt", "d.txt"] {
let tab = id(name, cx);
assert_eq!(request("$moveTab", vec![json!(tab), json!(9), json!(1)], cx), Ok(json!(null)));
}
assert_eq!(group_names(cx), [vec!["a.txt", "b.txt"], vec!["c.txt", "d.txt"]]);
let (a, c) = (id("a.txt", cx), id("c.txt", cx));
assert_eq!(request("$closeTab", vec![json!([a, c])], cx), Ok(json!(true)));
assert_eq!(group_names(cx), [vec!["b.txt"], vec!["d.txt"]]);
let groups = workbench.read_with(cx, |workbench, _| workbench.groups_in_grid_order());
assert_eq!(request("$closeGroup", vec![json!(groups)], cx), Ok(json!(true)));
assert!(open_names(&workbench, cx).is_empty());
}
#[gpui::test]
fn shift_f10_shows_the_editor_menu_below_the_cursor_without_moving_it(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("show-context-menu", &["a.txt"], cx);
let cursor = Selection::caret(Position::new(1, 3));
workbench.update(cx, |workbench, _| workbench.editors.active_mut().unwrap().set_selections(vec![cursor]));
workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("editor.action.showContextMenu", vec![], window, cx));
assert_eq!(menu_titles(&workbench, cx), ["(Go to Definition)", "(Go to Declaration)", "(Go to Type Definition)", "(Go to Implementations)", "(Go to References)", "Peek >", "---", "Change All Occurrences", "Refactor...", "---", "Cut", "Copy", "Paste", "---", "Command Palette..."]);
let (origin, anchor, selections) = workbench.update_in(cx, |workbench, window, _| (workbench.context_menu.as_ref().unwrap().levels[0].origin, workbench.cursor_anchor(window).unwrap(), workbench.editors.active().unwrap().selections.clone()));
assert_eq!(selections, [cursor]);
assert!(origin.x >= anchor.x - px(1.) && origin.y >= anchor.y - px(1.), "{origin:?} at {anchor:?}");
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn the_line_number_menu_selects_the_line_and_shows_contributed_items(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("line-number-menu", &["a.txt"], cx);
let extension = exthost::scan::ScannedExtension {
id: "test.lines".into(),
location: dir.clone(),
description: json!({ "contributes": {
"commands": [{ "command": "lines.copy", "title": "Copy Line Link" }, { "command": "lines.other", "title": "Other Line" }],
"menus": { "editor/lineNumber/context": [{ "command": "lines.copy", "when": "editorLineNumber == 2" }, { "command": "lines.other", "when": "editorLineNumber == 1" }] }
} }),
};
workbench.update(cx, |workbench, _| workbench.menus.extend(crate::menus::extension_menus(&[extension])));
let pointer = point(px(30.), px(100.));
workbench.update_in(cx, |workbench, window, cx| workbench.show_line_number_context_menu(1, pointer, true, window, cx));
assert_eq!(menu_titles(&workbench, cx), ["Copy Line Link"]);
let selections = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selections.clone());
assert_eq!(selections, [Selection { anchor: Position::new(1, 0), head: Position::new(1, 11) }]);
cx.simulate_keystrokes("escape");
std::fs::remove_dir_all(dir).unwrap();
}
/// floatingMenu.ts: the floating toolbar shows the `editor/content` items whose `when` holds, from an extension with
/// the `contribEditorContentMenu` proposal.
#[gpui::test]
fn the_floating_menu_shows_contributed_editor_content_items(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("floating-menu", &["a.txt"], cx);
let extension = exthost::scan::ScannedExtension {
id: "test.content".into(),
location: dir.clone(),
description: json!({ "enabledApiProposals": ["contribEditorContentMenu"], "contributes": {
"commands": [{ "command": "content.txt", "title": "Text Action" }, { "command": "content.md", "title": "Markdown Action" }],
"menus": { "editor/content": [{ "command": "content.txt", "when": "resourceExtname == .txt" }, { "command": "content.md", "when": "resourceExtname == .md" }] }
} }),
};
workbench.update(cx, |workbench, _| workbench.menus.extend(crate::menus::extension_menus(&[extension])));
let commands = workbench.update_in(cx, |workbench, window, _| {
workbench.floating_menu_actions(workbench.editors.active().unwrap(), window).into_iter().map(|action| action.command).collect::<Vec<_>>()
});
assert_eq!(commands, ["content.txt"]);
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn a_press_below_the_last_line_puts_the_cursor_at_its_end(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("press-below", &["a.txt"], cx);
let lines = cx.debug_bounds("editor-view-lines").expect("the text area shows");
let line_height = workbench.read_with(cx, |workbench, _| workbench.editors.viewport.line_height);
let selections = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selections.clone());
cx.simulate_click(point(lines.origin.x + px(16.), lines.origin.y + px(line_height / 2.)), gpui::Modifiers::none());
assert_eq!(selections(cx), [Selection::caret(Position::new(0, 2))], "a press on a line stays on it");
cx.simulate_click(point(lines.origin.x + px(16.), lines.origin.y + px(line_height * 5.)), gpui::Modifiers::none());
assert_eq!(selections(cx), [Selection::caret(Position::new(1, 11))]);
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn gutter_presses_select_whole_lines_and_drags_extend_them(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("gutter-select", &["a.txt"], cx);
workbench.update(cx, |workbench, _| {
let edit = (Position::new(0, 0), Position::new(1, 11), "one\ntwo\nthree\nfour".to_string(), false);
workbench.editors.active_mut().unwrap().execute_edits(vec![edit], None, crate::editor::EditReason::Unknown("test"));
});
let selections = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selections.clone());
let none = gpui::Modifiers::none();
workbench.update(cx, |workbench, cx| workbench.gutter_line_select(1, none, false, true, cx));
assert_eq!(selections(cx), [Selection { anchor: Position::new(1, 0), head: Position::new(2, 0) }]);
workbench.update(cx, |workbench, cx| workbench.gutter_line_select(3, none, true, true, cx));
assert_eq!(selections(cx), [Selection { anchor: Position::new(1, 0), head: Position::new(3, 4) }], "the last line ends at its end");
workbench.update(cx, |workbench, cx| workbench.gutter_line_select(0, none, true, true, cx));
assert_eq!(selections(cx), [Selection { anchor: Position::new(2, 0), head: Position::new(0, 0) }], "above, from the entering line's end");
let alt = gpui::Modifiers { alt: true, ..none };
workbench.update(cx, |workbench, cx| workbench.gutter_line_select(3, alt, false, true, cx));
assert_eq!(selections(cx).len(), 2, "Alt adds a cursor selecting the line");
let shift = gpui::Modifiers { shift: true, ..none };
workbench.update(cx, |workbench, cx| {
workbench.editors.active_mut().unwrap().set_selections(vec![Selection::caret(Position::new(0, 2))]);
workbench.gutter_line_select(2, shift, true, true, cx);
});
assert_eq!(selections(cx), [Selection { anchor: Position::new(0, 2), head: Position::new(3, 0) }], "Shift extends from the cursor");
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn text_clicks_select_words_lines_and_everything_and_drags_go_on_by_them(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("text-click-select", &["a.txt"], cx);
let selections = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selections.clone());
let press = |line: usize, visible: f32, count: usize, cx: &mut VisualTestContext| {
workbench.update(cx, |workbench, cx| {
workbench.selecting_text = Some(MouseDown { count, on_gutter: false });
workbench.click_text(line, visible, gpui::Modifiers::none(), false, count, cx);
});
};
let drag = |line: usize, visible: f32, cx: &mut VisualTestContext| workbench.update(cx, |workbench, cx| workbench.drag_select(line, visible, gpui::Modifiers::none(), cx));
press(0, 2., 4, cx);
assert_eq!(selections(cx), [Selection { anchor: Position::new(0, 0), head: Position::new(1, 11) }], "four clicks select everything");
press(0, 7., 2, cx);
assert_eq!(selections(cx), [Selection { anchor: Position::new(0, 6), head: Position::new(0, 11) }]);
drag(1, 1., cx);
assert_eq!(selections(cx), [Selection { anchor: Position::new(0, 6), head: Position::new(1, 6) }], "a double click's drag goes by words");
press(1, 2., 3, cx);
drag(0, 2., cx);
assert_eq!(selections(cx), [Selection { anchor: Position::new(1, 11), head: Position::new(0, 0) }], "a triple click's drag goes by lines");
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn a_selecting_drag_below_the_editor_scrolls_and_selects_to_the_bottom_line(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("drag-scroll", &["a.txt"], cx);
workbench.update(cx, |workbench, _| {
let text = (0..300).map(|line| format!("line {line}")).collect::<Vec<_>>().join("\n");
let edit = (Position::new(0, 0), Position::new(1, 11), text, false);
workbench.editors.active_mut().unwrap().execute_edits(vec![edit], None, crate::editor::EditReason::Unknown("test"));
});
cx.run_until_parked();
let viewport = workbench.read_with(cx, |workbench, _| workbench.editors.viewport);
assert!(viewport.height > 0., "the editor laid out");
workbench.update(cx, |workbench, cx| {
workbench.selecting_text = Some(MouseDown { count: 1, on_gutter: false });
workbench.click_text(0, 0., gpui::Modifiers::none(), false, 1, cx);
let below = point(px(3. * viewport.char_width), px(viewport.height + 50.));
workbench.drag_select_moved(point(px(0.), px(0.)), viewport.height, (0., viewport.width), below, gpui::Modifiers::none(), cx);
});
std::thread::sleep(std::time::Duration::from_millis(50));
assert!(workbench.update(cx, |workbench, cx| workbench.drag_scroll_frame(cx)));
workbench.read_with(cx, |workbench, _| {
let editor = workbench.editors.active().unwrap();
let bottom = editor.visible_lines(viewport).end - 1;
assert!(editor.scroll.top > 0., "the drag scrolls down");
// The bottom line takes the pointer's column only when it shows above the horizontal scrollbar.
let shown = editor.view_line_at(editor.scroll.top + viewport.height - crate::editor::HORIZONTAL_SCROLLBAR_HEIGHT - 0.1, viewport) == bottom;
let column = if shown { 3 } else { format!("line {bottom}").len() };
assert_eq!(editor.selections, [Selection { anchor: Position::new(0, 0), head: Position::new(bottom, column) }], "to the bottom line");
});
workbench.update(cx, |workbench, cx| {
workbench.selecting_text = None;
assert!(!workbench.drag_scroll_frame(cx), "a release ends the scrolling");
});
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn a_drag_into_the_vertical_scrollbar_without_the_minimap_scrolls_right(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("drag-scroll-right", &["a.txt"], cx);
std::fs::create_dir_all(dir.join("User")).unwrap();
let settings = config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None);
workbench.update(cx, |workbench, _| {
*workbench.settings.lock().unwrap() = settings;
workbench.update_setting("editor.minimap.enabled", json!(false));
let edit = (Position::new(0, 0), Position::new(1, 11), "x".repeat(2000), false);
workbench.editors.active_mut().unwrap().execute_edits(vec![edit], None, crate::editor::EditReason::Unknown("test"));
});
cx.run_until_parked();
workbench.update(cx, |_, cx| cx.notify());
cx.run_until_parked();
let bounds = workbench.read_with(cx, |workbench, _| workbench.text_area_bounds.get());
let y = px(bounds.top() + 5.);
cx.simulate_mouse_down(point(px(bounds.left() + 100.), y), MouseButton::Left, gpui::Modifiers::none());
cx.run_until_parked();
// mouseHandler.ts `_getPositionOutsideEditor`: past `width - verticalScrollbarWidth` is 'right' when the minimap is hidden.
cx.simulate_mouse_move(point(px(bounds.right() - 5.), y), Some(MouseButton::Left), gpui::Modifiers::none());
assert!(workbench.read_with(cx, |workbench, _| workbench.drag_scrolling.is_some()), "the first move into the scrollbar starts the drag scrolling");
std::thread::sleep(std::time::Duration::from_millis(50));
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().scroll.left) > 0., "it scrolls right");
cx.simulate_mouse_up(point(px(bounds.right() - 5.), y), MouseButton::Left, gpui::Modifiers::none());
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn a_drag_below_a_comment_reply_editor_scrolls_it(cx: &mut TestAppContext) {
let text: String = (1..=60).map(|line| format!("line {line}\n")).collect();
let (workbench, cx, _, dir) = crate::workbench::goto_symbol::tests::open(cx, "drag-scroll-embedded", &text);
let resource = json!({ "scheme": "file", "path": dir.join("a.txt").to_string_lossy() });
let request = |method: &str, args: Vec<serde_json::Value>, cx: &mut VisualTestContext| {
workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_comments_request(method, &args, window, cx)));
};
request("$registerCommentController", vec![json!(1), json!("review"), json!("Review"), json!("test.ext")], cx);
let range = json!({ "startLineNumber": 20, "startColumn": 1, "endLineNumber": 20, "endColumn": 8 });
request("$createCommentThread", vec![json!(1), json!(7), json!("t"), resource.clone(), range, json!([]), json!({ "value": "test.ext" }), json!(false)], cx);
let comment = json!({ "uniqueIdInThread": 1, "body": "Looks good", "userName": "Ann" });
request("$updateCommentThread", vec![json!(1), json!(7), json!("t"), resource, json!({ "comments": [comment], "collapseState": 1 })], cx);
cx.run_until_parked();
workbench.update_in(cx, |workbench, window, cx| workbench.expand_comment_reply(1, 7, window, cx));
cx.run_until_parked();
let reply = (1..=30).map(|line| format!("reply {line}")).collect::<Vec<_>>().join("\n");
let reply_id = workbench.update(cx, |workbench, cx| {
let editor = workbench.editors.active_mut().unwrap();
assert_eq!(editor.document().scheme, crate::workbench::comments::INPUT_SCHEME, "the reply editor has the focus");
editor.execute_edits(vec![(Position::new(0, 0), Position::new(0, 0), reply, false)], None, crate::editor::EditReason::Unknown("test"));
editor.selections = vec![Selection::caret(Position::new(0, 0))];
editor.scroll.top = 0.;
cx.notify();
editor.model_id
});
cx.run_until_parked();
let bounds = cx.debug_bounds(Box::leak(format!("text-area-{reply_id}").into_boxed_str())).expect("the reply editor is drawn");
let x = bounds.left() + px(60.);
cx.simulate_mouse_down(point(x, bounds.top() + px(5.)), MouseButton::Left, gpui::Modifiers::none());
cx.run_until_parked();
// The move passes over the text editor's line 38, past the reply's 30 lines: its rows leave the gesture alone.
cx.simulate_mouse_move(point(x, bounds.bottom() + px(40.)), Some(MouseButton::Left), gpui::Modifiers::none());
assert!(workbench.read_with(cx, |workbench, _| workbench.drag_scrolling.is_some()), "mouseHandler.ts runs in every code editor");
std::thread::sleep(std::time::Duration::from_millis(50));
cx.run_until_parked();
assert!(workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().scroll.top) > 0., "the reply editor scrolls");
cx.simulate_mouse_up(point(x, bounds.bottom() + px(40.)), MouseButton::Left, gpui::Modifiers::none());
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn the_bottom_edge_hit_test_leaves_out_the_horizontal_scrollbar(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("drag-scroll-edge", &["a.txt"], cx);
workbench.update(cx, |workbench, _| {
let text = (0..300).map(|line| format!("line {line}")).collect::<Vec<_>>().join("\n");
let edit = (Position::new(0, 0), Position::new(1, 11), text, false);
workbench.editors.active_mut().unwrap().execute_edits(vec![edit], None, crate::editor::EditReason::Unknown("test"));
});
cx.run_until_parked();
workbench.update(cx, |workbench, _| {
let viewport = workbench.editors.viewport;
// The bottom line shows 5px, under the 12px of the horizontal scrollbar.
let top = 180. + (5. - viewport.height).rem_euclid(viewport.line_height);
let editor = workbench.editors.active_mut().unwrap();
editor.set_scroll(top, 0., viewport);
let bottom = editor.visible_lines(viewport).end - 1;
// dragScrolling.ts hit tests `editorPos.height - horizontalScrollbarHeight - 0.1`, the line above the bottom one.
assert_eq!(workbench.vertical_drag_edge(false, 3.), (Position::new(bottom, format!("line {bottom}").len()), 3.));
});
std::fs::remove_dir_all(dir).unwrap();
}
#[gpui::test]
fn the_scrollbar_menu_writes_the_minimap_settings(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("scrollbar-menu", &["a.txt"], cx);
std::fs::create_dir_all(dir.join("User")).unwrap();
let settings = config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None);
workbench.update(cx, |workbench, _| *workbench.settings.lock().unwrap() = settings);
let pointer = point(px(700.), px(100.));
let checked = |cx: &mut VisualTestContext| {
workbench.read_with(cx, |workbench, _| {
let menu = workbench.context_menu.as_ref().expect("a context menu shows");
menu.levels[0].actions.iter().filter_map(|action| if let MenuAction::Command { title, checked: true, .. } = action { Some(title.clone()) } else { None }).collect::<Vec<_>>()
})
};
workbench.update_in(cx, |workbench, window, cx| workbench.show_scrollbar_context_menu(pointer, window, cx));
assert_eq!(menu_titles(&workbench, cx), ["Minimap", "---", "Render Characters", "Vertical size >", "Slider >", "Side >"]);
assert_eq!(checked(cx), ["Minimap", "Render Characters"]);
let submenus = workbench.read_with(cx, |workbench, _| {
let menu = workbench.context_menu.as_ref().unwrap();
let submenus = menu.levels[0].actions.iter().filter_map(|action| if let MenuAction::Submenu { actions, .. } = action { Some(actions.clone()) } else { None });
submenus.collect::<Vec<_>>()
});
let item = |action: &MenuAction| if let MenuAction::Command { id, title, checked, .. } = action { (id.clone(), title.clone(), *checked) } else { unreachable!() };
let items: Vec<Vec<(String, String, bool)>> = submenus.iter().map(|actions| actions.iter().map(item).collect()).collect();
let shown: Vec<Vec<(&str, bool)>> = items.iter().map(|actions| actions.iter().map(|(_, title, checked)| (title.as_str(), *checked)).collect()).collect();
assert_eq!(shown, [vec![("Proportional", true), ("Fill", false), ("Fit", false)], vec![("Mouse Over", true), ("Always", false)], vec![("Right", true), ("Left", false)]]);
let id = items[0][1].0.clone();
cx.simulate_keystrokes("escape");
workbench.update_in(cx, |workbench, window, cx| workbench.execute_command(&id, vec![], window, cx));
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.setting("editor.minimap.size")), json!("fill"));
workbench.update(cx, |workbench, _| workbench.update_setting("editor.minimap.enabled", json!(false)));
workbench.update_in(cx, |workbench, window, cx| workbench.show_scrollbar_context_menu(pointer, window, cx));
assert_eq!(menu_titles(&workbench, cx), ["Minimap", "---", "(Render Characters)", "(Vertical size)", "(Slider)", "(Side)"]);
assert_eq!(checked(cx), ["Render Characters"], "disabled, still checked as upstream");
cx.simulate_keystrokes("escape");
std::fs::remove_dir_all(dir).unwrap();
}
/// editorScrollbar.ts `listenOnDomNode: viewDomNode`: the minimap and the scrollbar track are the editor too, the
/// scrollbars stay shown over them and hide once the pointer leaves the editor.
#[gpui::test]
fn the_scrollbars_stay_shown_over_the_minimap_and_the_track(cx: &mut TestAppContext) {
let (dir, workbench, cx) = workbench_with("scrollbars-minimap", &["a.txt"], cx);
workbench.update(cx, |workbench, _| {
let text: String = (1..=300).map(|line| format!("line {line}\n")).collect();
let edit = (Position::new(0, 0), Position::new(1, 11), text, false);
workbench.editors.active_mut().unwrap().execute_edits(vec![edit], None, crate::editor::EditReason::Unknown("test"));
});
cx.run_until_parked();
workbench.update(cx, |_, cx| cx.notify());
cx.run_until_parked();
let (bounds, minimap_width) = workbench.read_with(cx, |workbench, _| (workbench.text_area_bounds.get(), workbench.minimap.info.as_ref().unwrap().0.width as f32));
let y = px(bounds.top() + 100.);
let shown = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.scrollbars.shown);
cx.simulate_mouse_move(point(px(bounds.left() + 100.), y), None, gpui::Modifiers::none());
assert!(shown(cx), "over the text");
cx.simulate_mouse_move(point(px(bounds.right() - crate::editor::VERTICAL_SCROLLBAR_WIDTH - minimap_width / 2.), y), None, gpui::Modifiers::none());
assert!(shown(cx), "over the minimap");
cx.simulate_mouse_move(point(px(bounds.right() - 5.), y), None, gpui::Modifiers::none());
assert!(shown(cx), "over the vertical scrollbar");
cx.executor().advance_clock(std::time::Duration::from_secs(1));
assert!(shown(cx), "no timeout hides them while the pointer is over the editor");
cx.simulate_mouse_move(point(px(bounds.left() - 20.), y), None, gpui::Modifiers::none());
assert!(!shown(cx), "leaving the editor hides them");
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.showCommands", Vec::new(), window, cx)));
cx.run_until_parked();
let palette = workbench.read_with(cx, |workbench, _| workbench.list_scroller(crate::workbench::list_scroll::ListId::QuickInput).bounds());
assert!(bounds.contains(&palette.center().map(f32::from)), "the palette covers the editor: {palette:?}");
cx.simulate_mouse_move(palette.center(), None, gpui::Modifiers::none());
assert!(!shown(cx), "the palette over the editor hides them");
std::fs::remove_dir_all(dir).unwrap();
}