Visual Studio Code, rebuilt in Rust
Rust
use std::path::Path;
use std::sync::mpsc::Receiver;
use gpui::{TestAppContext, VisualTestContext};
use serde_json::{Value, json};
use super::HistoryNavigator;
use crate::host_sync::{HostMessage, HostSync};
use crate::menus::{MenuAction, MenuId};
use crate::workbench::Workbench;
fn workbench_in<'a>(name: &str, cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, Receiver<HostMessage>, &'a mut VisualTestContext) {
let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
let 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 (sender, receiver) = std::sync::mpsc::channel();
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| {
let mut workbench = Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, HostSync::new(sender), cx);
workbench.set_default_keybindings(crate::keybindings::default_keybindings(&[]));
workbench.set_user_keybindings(Vec::new());
workbench
});
(workbench, receiver, cx)
}
fn register(handle: u64, root: &str) -> Vec<Value> {
let input = json!({ "scheme": "vscode-scm", "path": format!("git/scm{handle}/input") });
vec![json!(handle), Value::Null, json!("git"), json!("Git"), json!({ "scheme": "file", "path": root }), Value::Null, json!(false), input]
}
fn request(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext, method: &str, args: Vec<Value>) {
workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_scm_request(method, &args, window, cx)));
}
fn input(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> (String, (usize, usize)) {
workbench.read_with(cx, |workbench, _| (workbench.scm.input.value.clone(), workbench.scm.input.selection))
}
#[test]
fn the_history_navigator_keeps_unique_values_up_to_its_capacity() {
let mut history = HistoryNavigator::new(&["a".into(), "b".into(), "a".into()]);
assert_eq!(history.values, ["b", "a"]);
assert_eq!(history.replace_last("b"), "a");
assert_eq!(history.values, ["b"]);
for index in 0..150 {
history.add(index.to_string());
}
assert_eq!(history.values.len(), 100);
assert_eq!(history.values[0], "50");
assert!(history.is_at_end());
assert_eq!(history.previous(), "148");
assert_eq!(history.next(), "149");
assert_eq!(history.next(), "149");
}
#[gpui::test]
fn up_and_down_cycle_the_input_history_and_it_persists(cx: &mut TestAppContext) {
let (workbench, receiver, cx) = workbench_in("scm-input-history", cx);
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
workbench.update_in(cx, |workbench, window, cx| {
workbench.focus_scm_input(window, cx);
workbench.edit_scm_input(|input| input.set_value("fix bug".into()), window, cx);
});
// git clears the input after a commit: the message enters the history.
request(&workbench, cx, "$setInputBoxValue", vec![json!(0), json!("")]);
workbench.update_in(cx, |workbench, window, cx| workbench.edit_scm_input(|input| input.set_value("draft".into()), window, cx));
// The caret is at the end of "draft": Up is a caret move, Alt+Up always shows the previous value.
cx.simulate_keystrokes("alt-up");
cx.run_until_parked();
assert_eq!(input(&workbench, cx), ("fix bug".into(), (0, 0)));
let context = workbench.update_in(cx, |workbench, window, _| workbench.key_context(window));
assert_eq!((context.get("scmInputIsInFirstPosition"), context.get("scmInputIsInLastPosition")), (Some(&json!(true)), Some(&json!(false))));
cx.simulate_keystrokes("up");
cx.run_until_parked();
assert_eq!(input(&workbench, cx).0, "fix bug", "the first value stays");
workbench.update_in(cx, |workbench, window, cx| workbench.edit_scm_input(|input| input.select(7, 7), window, cx));
cx.simulate_keystrokes("down");
cx.run_until_parked();
assert_eq!(input(&workbench, cx), ("draft".into(), (5, 5)));
let changes: Vec<Value> = receiver.try_iter().filter(|message| message.method == "$onInputBoxValueChange").map(|message| message.args[1].clone()).collect();
assert_eq!(changes.last(), Some(&json!("draft")));
let stored = workbench.read_with(cx, |workbench, _| workbench.workspace_storage.lock().unwrap().get("scm.history").map(str::to_string));
let stored: Value = serde_json::from_str(&stored.unwrap()).unwrap();
assert_eq!(stored[0][0], "Git");
assert_eq!(stored[0][1]["path"], "/w/repo");
assert_eq!(stored[0][2], json!(["fix bug", "draft"]));
// `new SCMInput`: a repository registered again starts with the draft, and the host hears of it.
request(&workbench, cx, "$unregisterSourceControl", vec![json!(0)]);
request(&workbench, cx, "$registerSourceControl", register(1, "/w/repo"));
workbench.read_with(cx, |workbench, _| assert_eq!(workbench.scm.model.provider(1).unwrap().input.value, "draft"));
assert!(receiver.try_iter().any(|message| message.method == "$onInputBoxValueChange" && message.args == [json!(1), json!("draft")]));
}
#[gpui::test]
fn focus_next_input_and_resource_group_cycle(cx: &mut TestAppContext) {
let (workbench, _receiver, cx) = workbench_in("scm-focus-next", cx);
let raw = |handle: u64, path: &str| json!([handle, { "scheme": "file", "path": path }, [null, null], "Modified", false, false, "", null, null, null]);
request(&workbench, cx, "$registerSourceControl", register(0, "/w/alpha"));
request(&workbench, cx, "$registerSourceControl", register(1, "/w/beta"));
let groups = json!([[1, "index", "Staged Changes", { "hideWhenEmpty": true }, false], [2, "workingTree", "Changes", {}, false], [3, "merge", "Merge Changes", { "hideWhenEmpty": true }, false]]);
request(&workbench, cx, "$registerGroups", vec![json!(0), groups, json!([[1, [[0, 0, [raw(1, "/w/alpha/a")]]]], [2, [[0, 0, [raw(2, "/w/alpha/b")]]]]])]);
let run = |cx: &mut VisualTestContext, id: &str| workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(id, Vec::new(), window, cx)));
let state = |cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, _| (workbench.scm.focused, workbench.scm.input_focus.is_focused(window), workbench.scm.selected));
run(cx, "workbench.scm.action.focusNextInput");
assert_eq!(state(cx), (Some(0), true, None), "the focused repository's input first");
run(cx, "workbench.scm.action.focusNextInput");
assert_eq!(state(cx).0, Some(1));
run(cx, "workbench.scm.action.focusNextInput");
assert_eq!(state(cx).0, Some(0), "wraps");
run(cx, "workbench.scm.action.focusPreviousInput");
assert_eq!(state(cx).0, Some(1));
workbench.update_in(cx, |workbench, _, _| workbench.focus_scm_repository(Some(0)));
run(cx, "workbench.scm.action.focusNextResourceGroup");
assert_eq!(state(cx).2, Some((0, 1, None)), "the first shown group");
run(cx, "workbench.scm.action.focusNextResourceGroup");
assert_eq!(state(cx).2, Some((0, 2, None)));
run(cx, "workbench.scm.action.focusNextResourceGroup");
assert_eq!(state(cx).2, Some((0, 1, None)), "skips the empty merge group");
run(cx, "workbench.scm.action.focusPreviousResourceGroup");
assert_eq!(state(cx).2, Some((0, 2, None)));
}
#[gpui::test]
fn the_more_actions_menu_shows_view_and_sort(cx: &mut TestAppContext) {
let (workbench, _receiver, cx) = workbench_in("scm-more-actions", cx);
request(&workbench, cx, "$registerSourceControl", register(0, "/w/alpha"));
request(&workbench, cx, "$registerSourceControl", register(1, "/w/beta"));
let titles = |cx: &mut VisualTestContext| {
workbench.update_in(cx, |workbench, window, _| {
let mut context = workbench.key_context(window);
workbench.scm_view_context(&mut context);
let actions = super::flatten_submenus(workbench.menu_actions_outside(MenuId::ScmTitle, "navigation", &context));
actions.into_iter().filter_map(|action| match action {
MenuAction::Command { id, checked, enabled, .. } => Some((id, checked, enabled)),
_ => None,
}).collect::<Vec<_>>()
})
};
let actions = titles(cx);
let ids: Vec<&str> = actions.iter().map(|(id, ..)| id.as_str()).collect();
assert_eq!(ids, ["workbench.scm.action.setListViewMode", "workbench.scm.action.setTreeViewMode", "workbench.scm.action.setSortKey.name", "workbench.scm.action.setSortKey.path", "workbench.scm.action.setSortKey.status"]);
assert_eq!(actions[3], ("workbench.scm.action.setSortKey.path".into(), true, true));
// scmViewPane.ts `Menus.Repositories`: a toggle per repository, then the sort keys and selection modes.
let repositories = workbench.update_in(cx, |workbench, window, _| {
let mut context = workbench.key_context(window);
workbench.scm_view_context(&mut context);
workbench.menu_actions_outside(MenuId::ScmRepositories, "", &context)
});
let checked: Vec<(String, bool)> = repositories.into_iter().filter_map(|action| match action {
MenuAction::Command { id, checked, .. } => Some((id, checked)),
_ => None,
}).collect();
assert_eq!(checked[..3], [("workbench.scm.action.toggleRepositoryVisibility.scm0".into(), true), ("workbench.scm.action.toggleRepositoryVisibility.scm1".into(), true), ("workbench.scm.action.repositories.setSortKey.discoveryTime".into(), true)]);
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.scm.action.setTreeViewMode", Vec::new(), window, cx)));
let actions = titles(cx);
assert_eq!(actions[1], ("workbench.scm.action.setTreeViewMode".into(), true, true));
assert!(!actions[2].2, "sorting needs the list view mode");
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.scm.action.collapseAllRepositories", Vec::new(), window, cx)));
let context = workbench.update_in(cx, |workbench, window, _| {
let mut context = workbench.key_context(window);
workbench.scm_view_context(&mut context);
context
});
assert_eq!(context["scmViewAreAllRepositoriesCollapsed"], json!(true));
}
/// panecomposite.ts `getSecondaryActions`: Changes alone in Source Control (Graph hidden) puts the Views submenu and
/// a separator before its own "..." actions.
#[gpui::test]
fn a_merged_changes_view_shows_the_views_submenu_in_its_more_actions(cx: &mut TestAppContext) {
use crate::workbench::view_panes::{PaneContainer, SCM_CHANGES_VIEW, SCM_HISTORY_VIEW};
let (workbench, _receiver, cx) = workbench_in("scm-merged-more", cx);
cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
request(&workbench, cx, "$updateSourceControl", vec![json!(0), json!({ "hasHistoryProvider": true })]);
workbench.update_in(cx, |workbench, window, cx| {
workbench.toggle_view_visibility("scm", SCM_HISTORY_VIEW, cx);
drop(workbench.execute_command("workbench.view.scm", Vec::new(), window, cx));
workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
});
cx.run_until_parked();
workbench.update_in(cx, |workbench, window, cx| {
assert_eq!(workbench.panes(PaneContainer::Scm).view.as_ref().unwrap().ids(), [SCM_CHANGES_VIEW]);
let more = workbench.action_bar_focus(SCM_CHANGES_VIEW, "more", cx);
assert!(workbench.drawn_action_bar_items(SCM_CHANGES_VIEW).contains(&more), "the view's \"...\" draws");
window.focus(&more, cx);
});
cx.simulate_keystrokes("enter");
cx.simulate_event(gpui::KeyUpEvent { keystroke: gpui::Keystroke::parse("enter").unwrap() });
cx.run_until_parked();
let menu = workbench.read_with(cx, |workbench, _| workbench.context_menu.as_ref().expect("the \"...\" opens its menu").levels[0].actions.clone());
let MenuAction::Submenu { title, actions, .. } = &menu[0] else { panic!("the Views submenu comes first: {menu:?}") };
assert_eq!(title, "Views");
assert!(actions.iter().any(|action| matches!(action, MenuAction::Command { title, enabled: true, checked: false, .. } if title == "Graph")), "{actions:?}");
assert!(matches!(menu[1], MenuAction::Separator));
assert!(matches!(&menu[2], MenuAction::Command { id, .. } if id == "workbench.scm.action.setListViewMode"), "{menu:?}");
}
/// menuEntryActionViewItem.ts `SubmenuEntryActionViewItem`: a submenu in an inline group draws its icon, which opens
/// the submenu with the toolbar's arguments (git's `git.repositories.stash`, `$(plus)`).
#[gpui::test]
fn an_inline_submenu_opens_with_the_toolbar_arguments(cx: &mut TestAppContext) {
use crate::menus::{Entry, MenuItem};
let (workbench, _receiver, cx) = workbench_in("scm-inline-submenu", cx);
cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
workbench.update_in(cx, |workbench, window, cx| {
let submenu = MenuId::Api(0);
let item = |menu, entry, title: &str, group: &str| MenuItem { menu, entry, title: title.into(), group: group.into(), order: 0., when: None };
workbench.menus.push(item(MenuId::ScmTitle, Entry::Submenu { submenu, toggled: None }, "Stash", "navigation"));
workbench.menus.push(item(submenu, Entry::Command { id: "git.stash".into(), precondition: None, toggled: None, alt: None }, "Stash", ""));
workbench.submenu_icons.insert(submenu, crate::menus::CommandIcon::Codicon("plus".into()));
drop(workbench.execute_command("workbench.view.scm", Vec::new(), window, cx));
workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
});
cx.run_until_parked();
let button = cx.debug_bounds("submenu-button-Api(0)").expect("the submenu draws in the title").center();
cx.simulate_click(button, gpui::Modifiers::none());
cx.run_until_parked();
workbench.read_with(cx, |workbench, _| {
let menu = workbench.context_menu.as_ref().expect("the submenu opens");
assert!(matches!(&menu.levels[0].actions[..], [MenuAction::Command { id, .. }] if id == "git.stash"), "{:?}", menu.levels[0].actions);
assert_eq!(menu.args, [json!({ "$mid": 5, "handle": 0 })]);
});
}
#[gpui::test]
fn ref_changes_refresh_the_graph_or_mark_it_outdated_when_scrolled(cx: &mut TestAppContext) {
let (workbench, _receiver, cx) = workbench_in("scm-graph-ref-changes", cx);
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
let stale = Some((0, [Some(json!("stale")), None, None]));
let graph = |workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| (workbench.scm_graph.outdated, workbench.scm_graph.loaded_for.clone(), workbench.scm_graph_outdated_badge().is_some()));
let refs_changed = |silent: bool| vec![json!(0), json!({ "added": [], "modified": [], "removed": [], "silent": silent })];
request(&workbench, cx, "$updateSourceControl", vec![json!(0), json!({ "hasHistoryProvider": true })]);
// A collapsed Graph pane keeps the stale load: nothing reloads it behind the test's back.
workbench.update(cx, |workbench, cx| {
workbench.layout_view_panes(700., cx);
workbench.set_pane_expanded(crate::workbench::view_panes::PaneContainer::Scm, 1, false, cx);
workbench.scm_graph.loaded_for = stale.clone();
workbench.scm_graph.scroll.set_offset(gpui::point(gpui::px(0.), gpui::px(-40.)));
});
request(&workbench, cx, "$onDidChangeHistoryProviderHistoryItemRefs", vec![json!(1), refs_changed(false)[1].clone()]);
assert_eq!(graph(&workbench, cx), (false, stale.clone(), false), "another repository's refs leave the graph alone");
request(&workbench, cx, "$onDidChangeHistoryProviderHistoryItemRefs", refs_changed(true));
assert_eq!(graph(&workbench, cx), (true, stale.clone(), true), "a background change while scrolled shows Outdated");
request(&workbench, cx, "$onDidChangeHistoryProviderHistoryItemRefs", refs_changed(false));
let (outdated, loaded_for, badge) = graph(&workbench, cx);
assert!(!outdated && !badge && loaded_for != stale, "a foreground change refreshes the graph");
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.scm_graph.scroll.offset().y), gpui::px(0.));
workbench.update(cx, |workbench, _| workbench.scm_graph.loaded_for = stale.clone());
request(&workbench, cx, "$onDidChangeHistoryProviderHistoryItemRefs", refs_changed(true));
assert_eq!(graph(&workbench, cx).0, false, "at the top a background change refreshes too");
assert_ne!(graph(&workbench, cx).1, stale);
}
/// scmViewPane.ts `ResourceRenderer` and `onListContextMenu`: a tree mode folder shows
/// `MenuId.SCMResourceFolderContext`, run with the folder's resources (git's `git.stage` on a folder).
#[gpui::test]
fn a_folder_row_shows_the_resource_folder_menu_with_its_resources(cx: &mut TestAppContext) {
use crate::menus::{Entry, MenuItem};
let (workbench, _receiver, cx) = workbench_in("scm-resource-folder", cx);
cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
let raw = |handle: u64, path: &str| json!([handle, { "scheme": "file", "path": path }, [null, null], "Modified", false, false, "", null, null, null]);
let groups = json!([[2, "workingTree", "Changes", {}, false]]);
request(&workbench, cx, "$registerGroups", vec![json!(0), groups, json!([[2, [[0, 0, [raw(1, "/w/repo/src/a.ts"), raw(2, "/w/repo/c.ts"), raw(3, "/w/repo/src/b.ts")]]]]])]);
workbench.update_in(cx, |workbench, window, cx| {
let when = crate::contextkey::Expr::deserialize("scmProvider == git && scmResourceGroup == workingTree");
workbench.menus.push(MenuItem { menu: MenuId::ScmResourceFolderContext, entry: Entry::Command { id: "git.stage".into(), precondition: None, toggled: None, alt: None }, title: "Stage Changes".into(), group: "1_modification".into(), order: 0., when: when.clone() });
workbench.menus.push(MenuItem { menu: MenuId::ScmResourceFolderContext, entry: Entry::Command { id: "git.clean".into(), precondition: None, toggled: None, alt: None }, title: "Discard Changes".into(), group: "inline".into(), order: 1., when });
drop(workbench.execute_command("workbench.scm.action.setTreeViewMode", Vec::new(), window, cx));
drop(workbench.execute_command("workbench.view.scm", Vec::new(), window, cx));
workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
});
cx.run_until_parked();
let folder = cx.debug_bounds("scm-folder-0-2-src").expect("the tree shows the src folder").center();
cx.simulate_mouse_down(folder, gpui::MouseButton::Right, gpui::Modifiers::none());
cx.run_until_parked();
workbench.read_with(cx, |workbench, _| {
let menu = workbench.context_menu.as_ref().expect("the folder's context menu opens");
assert!(matches!(&menu.levels[0].actions[..], [MenuAction::Command { id, .. }] if id == "git.stage"), "{:?}", menu.levels[0].actions);
let resource = |handle: u64| json!({ "$mid": 3, "sourceControlHandle": 0, "groupHandle": 2, "handle": handle });
assert_eq!(menu.args, [resource(1), resource(3)]);
});
}
/// abstractTree.ts indent guides in the Changes view: the group's children draw its guide 16px in from the group
/// row, which modernUI padding.css insets with every row.
#[gpui::test]
fn the_changes_tree_draws_indent_guides(cx: &mut TestAppContext) {
let (workbench, _receiver, cx) = workbench_in("scm-folder-guides", cx);
cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
let raw = |handle: u64, path: &str| json!([handle, { "scheme": "file", "path": path }, [null, null], "Modified", false, false, "", null, null, null]);
let groups = json!([[2, "workingTree", "Changes", {}, false]]);
request(&workbench, cx, "$registerGroups", vec![json!(0), groups, json!([[2, [[0, 0, [raw(1, "/w/repo/src/a.ts"), raw(2, "/w/repo/c.ts")]]]]])]);
workbench.update_in(cx, |workbench, window, cx| {
drop(workbench.execute_command("workbench.scm.action.setTreeViewMode", Vec::new(), window, cx));
drop(workbench.execute_command("workbench.view.scm", Vec::new(), window, cx));
workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
});
cx.run_until_parked();
let group = cx.debug_bounds("scm-group-0-2").expect("the view shows the group");
let guide = cx.debug_bounds("tree-guide").expect("the group's children draw its guide");
assert_eq!(f32::from(guide.origin.x - group.origin.x), 16.);
let pane = cx.debug_bounds("scm-list").expect("the view draws its list");
assert_eq!(f32::from(group.origin.x - pane.origin.x), 4.);
}
/// scmViewPane.ts `onListContextMenu` and util.ts `collectContextMenuActions`: a repository, resource group or
/// resource row's menu drops the `inline` group its row shows as buttons.
#[gpui::test]
fn row_context_menus_leave_out_the_inline_group(cx: &mut TestAppContext) {
use crate::menus::{Entry, MenuItem};
let (workbench, _receiver, cx) = workbench_in("scm-row-menus", cx);
cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
request(&workbench, cx, "$registerSourceControl", register(1, "/w/other"));
let raw = json!([1, { "scheme": "file", "path": "/w/repo/a.ts" }, [null, null], "Modified", false, false, "", null, null, null]);
request(&workbench, cx, "$registerGroups", vec![json!(0), json!([[2, "workingTree", "Changes", {}, false]]), json!([[2, [[0, 0, [raw]]]]])]);
workbench.update_in(cx, |workbench, window, cx| {
for menu in [MenuId::ScmSourceControl, MenuId::ScmResourceGroupContext, MenuId::ScmResourceStateContext] {
for (id, group) in [("git.stage", "1_modification"), ("git.clean", "inline")] {
workbench.menus.push(MenuItem { menu, entry: Entry::Command { id: id.into(), precondition: None, toggled: None, alt: None }, title: id.into(), group: group.into(), order: 0., when: None });
}
}
drop(workbench.execute_command("workbench.view.scm", Vec::new(), window, cx));
workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
});
cx.run_until_parked();
for row in ["scm-repository-0", "scm-group-0-2", "scm-resource-0-2-1"] {
let center = cx.debug_bounds(row).unwrap_or_else(|| panic!("the view shows {row}")).center();
cx.simulate_mouse_down(center, gpui::MouseButton::Right, gpui::Modifiers::none());
cx.run_until_parked();
workbench.update(cx, |workbench, cx| {
cx.notify();
let menu = workbench.context_menu.take().unwrap_or_else(|| panic!("{row} opens its menu"));
let ids: Vec<&str> = menu.levels[0].actions.iter().filter_map(|action| match action {
MenuAction::Command { id, .. } => Some(id.as_str()),
_ => None,
}).collect();
assert!(ids.contains(&"git.stage") && !ids.contains(&"git.clean"), "{row}: {ids:?}");
});
}
}
/// scmViewPane.ts `ResourceRenderer` and `ResourceGroupRenderer`: a hovered row shows its `inline` actions, which run
/// on click.
#[gpui::test]
fn a_hovered_row_shows_its_inline_actions(cx: &mut TestAppContext) {
use crate::menus::{Entry, MenuItem};
let (workbench, _receiver, cx) = workbench_in("scm-row-inline", cx);
let ran = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
let raw = json!([1, { "scheme": "file", "path": "/w/repo/a.ts" }, [null, null], "Modified", false, false, "", null, null, null]);
request(&workbench, cx, "$registerGroups", vec![json!(0), json!([[2, "workingTree", "Changes", {}, false]]), json!([[2, [[0, 0, [raw]]]]])]);
workbench.update_in(cx, |workbench, window, cx| {
for (menu, id) in [(MenuId::ScmResourceGroupContext, "git.stageAll"), (MenuId::ScmResourceStateContext, "git.stage")] {
workbench.menus.push(MenuItem { menu, entry: Entry::Command { id: id.into(), precondition: None, toggled: None, alt: None }, title: id.into(), group: "inline".into(), order: 0., when: None });
let ran = ran.clone();
workbench.commands.register(id, move |_, _, _, _| {
ran.borrow_mut().push(id);
crate::commands::Outcome::done()
});
}
drop(workbench.execute_command("workbench.view.scm", Vec::new(), window, cx));
workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
});
cx.run_until_parked();
for (row, command, right) in [("scm-group-0-2", "git.stageAll", 4. + 19. + 6. + 11.), ("scm-resource-0-2-1", "git.stage", 8. + 11.)] {
let bounds = cx.debug_bounds(row).unwrap_or_else(|| panic!("the view shows {row}"));
// The 22px button's center: past the row's padding (4px on a group, 8px on a resource) and the group's count badge.
let button = gpui::point(bounds.right() - gpui::px(right), bounds.center().y);
cx.simulate_mouse_move(button, None, gpui::Modifiers::none());
cx.run_until_parked();
cx.simulate_click(button, gpui::Modifiers::none());
cx.run_until_parked();
assert_eq!(ran.borrow_mut().pop(), Some(command), "{row}: the hovered row's inline action runs on click");
}
}
/// scmViewPane.ts `ResourceGroupRenderer` and `ResourceRenderer`: the count badge 4px from the row's end, as
/// countBadge.css sizes it, and a resource's label hover as labels.ts titles it, its path then the decoration's tooltip.
#[gpui::test]
fn a_changes_row_draws_its_count_and_hovers_its_path(cx: &mut TestAppContext) {
let (workbench, _receiver, cx) = workbench_in("scm-row-count-hover", cx);
cx.simulate_resize(gpui::size(gpui::px(1024.), gpui::px(768.)));
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
let raw = json!([1, { "scheme": "file", "path": "/w/repo/a.ts" }, [null, null], "Modified", false, false, "", null, null, null]);
request(&workbench, cx, "$registerGroups", vec![json!(0), json!([[2, "workingTree", "Changes", {}, false]]), json!([[2, [[0, 0, [raw]]]]])]);
workbench.update_in(cx, |workbench, window, cx| {
let mut decorations = workbench.decorations.borrow_mut();
decorations.register(9);
let data = crate::decorations::DecorationData { weight: 0, bubble: false, tooltip: Some("Modified".into()), letter: Some("M".into()), color: None };
decorations.set(9, "/w/repo/a.ts", Some(data));
drop(decorations);
drop(workbench.execute_command("workbench.view.scm", Vec::new(), window, cx));
workbench.set_part_hidden(crate::workbench::layout::Part::SideBar, false, cx);
});
cx.run_until_parked();
let (row, badge) = (cx.debug_bounds("scm-group-0-2").unwrap(), cx.debug_bounds("scm-group-count-0-2").unwrap());
assert_eq!((f32::from(row.right() - badge.right()), f32::from(badge.size.width), f32::from(badge.size.height)), (4., 19., 19.));
let resource = cx.debug_bounds("scm-resource-0-2-1").unwrap();
cx.simulate_mouse_move(resource.center(), None, gpui::Modifiers::none());
cx.executor().advance_clock(std::time::Duration::from_millis(1500));
cx.run_until_parked();
assert_eq!(workbench.read_with(cx, |workbench, _| workbench.hovers.shown_text().map(str::to_owned)).as_deref(), Some("/w/repo/a.ts \u{2022} Modified"));
}
/// scmHistoryViewPane.ts `_onContextMenu`: each `scm/historyItemRef/context` command the item's refs show is a
/// submenu of those refs, grouped by category, and an entry runs the command with the ref id last.
#[gpui::test]
fn a_history_item_menu_offers_each_ref_action_per_ref(cx: &mut TestAppContext) {
use crate::menus::{Entry, MenuItem};
use crate::scm_history::{HistoryItem, HistoryItemRef, to_history_item_view_models};
let (workbench, _receiver, cx) = workbench_in("scm-history-item-refs", cx);
request(&workbench, cx, "$registerSourceControl", register(0, "/w/repo"));
let reference = |id: &str, name: &str, category: &str| HistoryItemRef { id: id.into(), name: name.into(), category: Some(category.into()), ..Default::default() };
let item = HistoryItem { id: "a1".into(), subject: "init".into(), references: vec![reference("refs/heads/main", "main", "branches"), reference("refs/tags/v1", "v1", "tags")], ..Default::default() };
let ran = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
workbench.update_in(cx, |workbench, window, cx| {
let command = |id: &str| Entry::Command { id: id.into(), precondition: None, toggled: None, alt: None };
workbench.menus.push(MenuItem { menu: MenuId::ScmHistoryItemRefContext, entry: command("git.graph.checkout"), title: "Checkout".into(), group: "1_checkout".into(), order: 1., when: None });
let when = crate::contextkey::Expr::deserialize("scmHistoryItemRef == 'refs/heads/main'");
workbench.menus.push(MenuItem { menu: MenuId::ScmHistoryItemRefContext, entry: command("git.graph.deleteBranch"), title: "Delete Branch".into(), group: "2_branch".into(), order: 2., when });
let ran = ran.clone();
workbench.commands.register("git.graph.checkout", move |_, args, _, _| {
ran.borrow_mut().push(args);
crate::commands::Outcome::done()
});
workbench.scm_graph.view_models = to_history_item_view_models(&[item], &Default::default(), None, None, None, false, false, None);
workbench.show_scm_history_item_menu(0, 0, gpui::point(gpui::px(10.), gpui::px(10.)), window, cx);
});
let args = workbench.read_with(cx, |workbench, _| {
let menu = workbench.context_menu.as_ref().expect("the history item's context menu opens");
let submenus: Vec<(String, Vec<String>)> = menu.levels[0]
.actions
.iter()
.filter_map(|action| match action {
MenuAction::Submenu { title, actions, .. } => Some((title.clone(), actions.iter().map(|action| format!("{action:?}")).collect())),
_ => None,
})
.collect();
let [(checkout, refs), (delete, branch)] = &submenus[..] else { panic!("{submenus:?}") };
assert_eq!((checkout.as_str(), delete.as_str()), ("Checkout", "Delete Branch"));
assert!(matches!(&refs[..], [main, separator, tag] if main.contains("\"git.graph.checkout.refs/heads/main\"") && separator == "Separator" && tag.contains("title: \"v1\"")), "{refs:?}");
assert!(matches!(&branch[..], [main] if main.contains("\"git.graph.deleteBranch.refs/heads/main\"")), "{branch:?}");
menu.args.clone()
});
workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("git.graph.checkout.refs/tags/v1", args.clone(), window, cx)));
assert_eq!(ran.borrow().as_slice(), [[args, vec![json!("refs/tags/v1")]].concat()]);
}
/// activity.ts `SCMActiveResourceContextKeyController`: git's editor title Open Changes shows while a group lists the
/// active editor's resource (`scmActiveResourceHasChanges`).
#[gpui::test]
fn the_active_resource_has_changes_while_a_group_lists_it(cx: &mut TestAppContext) {
let (workbench, _receiver, cx) = workbench_in("scm-active-resource", cx);
let dir = std::env::temp_dir().join(format!("code-gpui-scm-active-resource-repo-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("a.txt"), "a\n").unwrap();
let root = dir.to_string_lossy().to_string();
request(&workbench, cx, "$registerSourceControl", register(3, &root));
workbench.update_in(cx, |workbench, window, cx| workbench.open_file(dir.join("a.txt"), true, window, cx));
cx.run_until_parked();
let keys = |cx: &mut VisualTestContext| {
workbench.update_in(cx, |workbench, window, _| {
let context = workbench.key_context(window);
(context.get("scmActiveResourceHasChanges").cloned(), context.get("scmActiveResourceRepository").cloned())
})
};
assert_eq!(keys(cx), (Some(json!(false)), Some(json!("scm3"))));
let raw = json!([1, { "scheme": "file", "path": format!("{root}/a.txt") }, [null, null], "Modified", false, false, "", null, null, null]);
request(&workbench, cx, "$registerGroups", vec![json!(3), json!([[2, "workingTree", "Changes", {}, false]]), json!([[2, [[0, 0, [raw]]]]])]);
assert_eq!(keys(cx), (Some(json!(true)), Some(json!("scm3"))));
std::fs::remove_dir_all(dir).unwrap();
}