Skip to content

Visual Studio Code, rebuilt in Rust

Rust
16.7 KB
Raw Blame
use std::path::{Path, PathBuf};

use exthost::scan::scan_extension;
use gpui::{AnyWindowHandle, TestAppContext, VisualTestContext};

use super::super::editor_groups::MAIN_PART;
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::menus::{Entry, MenuId, MenuItem};
use crate::theme::load_theme;
use crate::workbench::Workbench;

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-auxiliary-{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").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 run(workbench: &gpui::Entity<Workbench>, command: &str, cx: &mut VisualTestContext) {
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(command, vec![], window, cx)));
    cx.run_until_parked();
}

/// Each part's groups with their tab names, the main part first.
fn parts(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<Vec<Vec<String>>> {
    workbench.read_with(cx, |workbench, _| {
        let ids: Vec<u32> = std::iter::once(MAIN_PART).chain(workbench.auxiliary_windows.part_ids()).collect();
        let names = |group: u32| workbench.editors.group_tabs(group).0.iter().map(|editor| editor.document().name()).collect();
        ids.into_iter().map(|part| workbench.part_groups(part).into_iter().map(names).collect()).collect()
    })
}

fn editor_window(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> AnyWindowHandle {
    let part = workbench.read_with(cx, |workbench, _| workbench.auxiliary_windows.part_ids().next().unwrap());
    workbench.read_with(cx, |workbench, _| workbench.auxiliary_windows.windows.iter().find(|window| window.part == part).unwrap().handle.unwrap().into())
}

#[gpui::test]
fn move_editor_into_new_window_opens_a_part_with_the_editor(cx: &mut TestAppContext) {
    let (_dir, workbench, cx) = workbench_with("move", &["a.txt", "b.txt"], cx);
    run(&workbench, "workbench.action.moveEditorToNewWindow", cx);
    assert_eq!(parts(&workbench, cx), vec![vec![vec!["a.txt".to_string()]], vec![vec!["b.txt".to_string()]]]);
    assert_eq!(cx.windows().len(), 2);
    let (active_part, columns) = workbench.read_with(cx, |workbench, _| (workbench.editor_groups.active_part(), workbench.groups_in_grid_order().len()));
    assert_ne!(active_part, MAIN_PART);
    assert_eq!(columns, 2);
    // The editor window's keys reach the workbench: Cmd+W closes its last editor, and the window with it.
    let handle = editor_window(&workbench, cx);
    let mut window_cx = VisualTestContext::from_window(handle, cx);
    window_cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-w"));
    window_cx.run_until_parked();
    assert_eq!(parts(&workbench, cx), vec![vec![vec!["a.txt".to_string()]]]);
    assert_eq!(cx.windows().len(), 1);
}

/// VS Code 1.147.0 draws a new empty editor window's group 16px up (`focus_scrolled`) until the group gets an editor.
#[gpui::test]
fn a_new_empty_editor_window_draws_its_group_16px_up_until_it_gets_an_editor(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_with("empty-window", &["a.txt"], cx);
    run(&workbench, "workbench.action.newEmptyEditorWindow", cx);
    let part = workbench.read_with(cx, |workbench, _| workbench.auxiliary_windows.part_ids().next().unwrap());
    let scroll = |cx: &mut VisualTestContext| workbench.update(cx, |workbench, _| workbench.refresh_focus_scroll(part));
    assert_eq!(scroll(cx), 16.);
    workbench.update_in(cx, |workbench, window, cx| workbench.open_file(dir.join("a.txt"), true, window, cx));
    cx.run_until_parked();
    assert_eq!(scroll(cx), 0.);
    run(&workbench, "workbench.action.closeActiveEditor", cx);
    assert_eq!(scroll(cx), 0.);
}

/// Toggle Window Compact Mode relayouts the window, which clamps the 16px focus scroll back to 0.
#[gpui::test]
fn compact_mode_ends_the_new_empty_editor_windows_focus_scroll(cx: &mut TestAppContext) {
    let (_dir, workbench, cx) = workbench_with("empty-compact", &["a.txt"], cx);
    run(&workbench, "workbench.action.newEmptyEditorWindow", cx);
    let part = workbench.read_with(cx, |workbench, _| workbench.auxiliary_windows.part_ids().next().unwrap());
    let scroll = |cx: &mut VisualTestContext| workbench.update(cx, |workbench, _| workbench.refresh_focus_scroll(part));
    assert_eq!(scroll(cx), 16.);
    workbench.update(cx, |workbench, _| workbench.set_compact(part, false));
    assert_eq!(scroll(cx), 16.);
    workbench.update(cx, |workbench, _| workbench.set_compact(part, true));
    assert_eq!(scroll(cx), 0.);
}

#[gpui::test]
fn closing_an_editor_window_moves_its_dirty_editors_to_the_main_window(cx: &mut TestAppContext) {
    let (_dir, workbench, cx) = workbench_with("close", &["a.txt", "b.txt"], cx);
    run(&workbench, "workbench.action.copyEditorGroupToNewWindow", cx);
    assert_eq!(parts(&workbench, cx), vec![vec![vec!["a.txt".to_string(), "b.txt".to_string()]], vec![vec!["a.txt".to_string(), "b.txt".to_string()]]]);
    run(&workbench, "workbench.action.closeActiveEditor", cx);
    run(&workbench, "workbench.action.files.newUntitledFile", cx);
    workbench.update(cx, |workbench, _| workbench.editors.active_mut().unwrap().type_text("draft"));
    assert_eq!(parts(&workbench, cx)[1], vec![vec!["a.txt".to_string(), "Untitled-1".to_string()]]);
    let part = workbench.read_with(cx, |workbench, _| workbench.editor_groups.active_part());
    workbench.update(cx, |workbench, cx| workbench.close_auxiliary_window(part, cx));
    cx.run_until_parked();
    // auxiliaryEditorPart.ts `doClose(true)`: the saved editor closes, the untitled one moves.
    assert_eq!(parts(&workbench, cx), vec![vec![vec!["a.txt".to_string(), "b.txt".to_string(), "Untitled-1".to_string()]]]);
    assert_eq!(cx.windows().len(), 1);
}

#[gpui::test]
fn a_tab_dropped_on_the_main_part_leaves_the_editor_window(cx: &mut TestAppContext) {
    let (_dir, workbench, cx) = workbench_with("drop", &["a.txt", "b.txt"], cx);
    run(&workbench, "workbench.action.moveEditorToNewWindow", cx);
    workbench.update_in(cx, |workbench, window, cx| {
        let source = workbench.editors.id;
        let target = workbench.part_active_group(MAIN_PART).unwrap();
        let dragged = workbench.dragged_tab(source, 0, cx);
        workbench.move_dragged_tab(&dragged, target, None, window, cx);
    });
    cx.run_until_parked();
    assert_eq!(parts(&workbench, cx), vec![vec![vec!["a.txt".to_string(), "b.txt".to_string()]]]);
    assert_eq!(cx.windows().len(), 1);
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.editor_groups.active_part()), MAIN_PART);
}

#[gpui::test]
fn editor_windows_come_back_with_their_editors(cx: &mut TestAppContext) {
    let (_dir, workbench, cx) = workbench_with("restore", &["a.txt", "b.txt"], cx);
    run(&workbench, "workbench.action.moveEditorToNewWindow", cx);
    run(&workbench, "workbench.action.splitEditorDown", cx);
    let storage = workbench.read_with(cx, |workbench, _| workbench.workspace_storage.clone());
    let state = workbench.read_with(cx, |workbench, _| workbench.stored_editor_parts_state()).unwrap();
    assert_eq!(state["auxiliary"][0]["state"]["serializedGrid"]["root"]["data"].as_array().unwrap().len(), 2);
    assert_eq!(state["mru"], serde_json::json!([1, 0]));
    // A second window on the same workspace storage restores the part.
    let (_dir, restored, cx) = workbench_with("restored", &["a.txt"], &mut cx.cx);
    restored.update(cx, |workbench, cx| {
        workbench.workspace_storage = storage;
        workbench.restore_auxiliary_windows(cx);
    });
    cx.run_until_parked();
    assert_eq!(parts(&restored, cx)[1], vec![vec!["b.txt".to_string()], vec!["b.txt".to_string()]]);
    assert_ne!(restored.read_with(cx, |workbench, _| workbench.editor_groups.active_part()), MAIN_PART);
}

fn run_in(handle: AnyWindowHandle, workbench: &gpui::Entity<Workbench>, command: &str, cx: &mut VisualTestContext) {
    handle.update(cx, |_, window, cx| workbench.update(cx, |workbench, cx| drop(workbench.execute_command(command, vec![], window, cx)))).unwrap();
    cx.run_until_parked();
}

#[gpui::test]
fn a_compact_editor_window_splits_into_the_main_window_and_leaves_compact_mode_for_a_second_editor(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_with("compact", &["a.txt", "b.txt"], cx);
    run(&workbench, "workbench.action.moveEditorToNewWindow", cx);
    let handle = editor_window(&workbench, cx);
    let part = workbench.read_with(cx, |workbench, _| workbench.auxiliary_windows.part_ids().next().unwrap());
    let compact = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.is_compact_part(part));
    run_in(handle, &workbench, "workbench.action.toggleCompactAuxiliaryWindow", cx);
    assert!(compact(cx));
    assert_eq!(workbench.update(cx, |workbench, _| workbench.auxiliary_parts_state()).unwrap()["auxiliary"][0]["compact"], true);
    // `getAddGroupLocation`: the split's group goes beside the main part's active group.
    run_in(handle, &workbench, "workbench.action.splitEditorRight", cx);
    assert_eq!(parts(&workbench, cx), vec![vec![vec!["a.txt".to_string()], vec!["b.txt".to_string()]], vec![vec!["b.txt".to_string()]]]);
    assert!(compact(cx));
    // A second editor shown in the window's group ends compact mode.
    workbench.update_in(cx, |workbench, window, cx| {
        let group = workbench.part_active_group(part).unwrap();
        workbench.focus_group(group, window, cx);
        workbench.open_file(dir.join("a.txt"), true, window, cx);
    });
    cx.run_until_parked();
    assert_eq!(parts(&workbench, cx)[1], vec![vec!["b.txt".to_string(), "a.txt".to_string()]]);
    assert!(!compact(cx));
}

/// navigationActions.ts `findVisibleNeighbour`: F6 in an editor window goes between its editor and its own status bar,
/// and that bar keeps its own entry focus (statusbarPart.ts `createAuxiliaryStatusbarPart`).
#[gpui::test]
fn f6_in_an_editor_window_reaches_its_own_status_bar(cx: &mut TestAppContext) {
    use super::super::part_navigation::FocusPart;
    let (_dir, workbench, cx) = workbench_with("f6", &["a.txt", "b.txt"], cx);
    run(&workbench, "workbench.action.moveEditorToNewWindow", cx);
    let handle = editor_window(&workbench, cx);
    let mut window_cx = VisualTestContext::from_window(handle, cx);
    let main = cx.update(|window, _| window.window_handle());
    // `update_in` picks the window the workbench last drew in, so each read names its window.
    let state = |handle: AnyWindowHandle, cx: &mut VisualTestContext| {
        cx.run_until_parked();
        handle.update(cx, |_, window, cx| {
            let cx: &gpui::App = cx;
            let workbench = workbench.read(cx);
            (workbench.focused_part(window, cx), workbench.status_entry_focus.get(&window.window_handle().window_id()).cloned())
        }).unwrap()
    };
    let drawn_in = |handle: AnyWindowHandle, cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| workbench.status_entry_bounds.borrow().iter().filter(|(drawn_in, ..)| *drawn_in == handle.window_id()).map(|(_, id, _)| id.clone()).collect::<Vec<_>>())
    };
    handle.update(&mut window_cx, |_, window, cx| workbench.update(cx, |workbench, cx| workbench.focus_group(workbench.editors.id, window, cx))).unwrap();

    window_cx.simulate_keystrokes("f6");
    assert_eq!(state(handle, &mut window_cx), (Some(FocusPart::StatusBar), None));
    window_cx.simulate_keystrokes("home");
    let entries = drawn_in(handle, &mut window_cx);
    assert!(!entries.is_empty());
    assert_eq!(state(handle, &mut window_cx), (Some(FocusPart::StatusBar), Some(entries[0].clone())), "the editor window's own first entry");
    assert_eq!(state(main, cx).1, None, "the main window's bar has no entry focus");
    main.update(cx, |_, window, cx| window.focus(&workbench.read(cx).status_bar_focus.clone(), cx)).unwrap();
    cx.simulate_keystrokes("end");
    assert_eq!(state(main, cx).1, drawn_in(main, cx).last().cloned());
    assert_eq!(state(handle, &mut window_cx).1, Some(entries[0].clone()), "the main window's focus leaves the editor window's");
    window_cx.simulate_keystrokes("f6");
    assert_eq!(state(handle, &mut window_cx).0, Some(FocusPart::Editor));
}

/// titlebarPart.ts: an editor window's title bar has its own toolbars, each one tab stop before its editor part.
#[gpui::test]
fn an_editor_windows_title_bar_toolbars_are_its_own_tab_stops(cx: &mut TestAppContext) {
    let (_dir, workbench, cx) = workbench_with("title-toolbars", &["a.txt", "b.txt"], cx);
    run(&workbench, "workbench.action.moveEditorToNewWindow", cx);
    let handle = editor_window(&workbench, cx);
    let mut window_cx = VisualTestContext::from_window(handle, cx);
    let main = cx.update(|window, _| window.window_handle());
    let part = workbench.read_with(cx, |workbench, _| workbench.auxiliary_windows.part_ids().next().unwrap());
    // `update_in` picks the window the workbench last drew in, so each read names its window.
    let focus = |handle: AnyWindowHandle, cx: &mut VisualTestContext| {
        cx.run_until_parked();
        handle.update(cx, |_, window, cx| {
            let workbench = workbench.read(cx);
            (workbench.focused_action_bar(window), workbench.editor_tab_focus.is_focused(window))
        }).unwrap()
    };
    let [_, _, actions] = handle.update(&mut window_cx, |_, window, cx| workbench.read(cx).title_bar_toolbars(window)).unwrap();
    assert_ne!(actions, "title-actions", "the editor window's toolbar is not the main window's");

    handle.update(&mut window_cx, |_, window, cx| workbench.update(cx, |workbench, cx| assert!(workbench.focus_action_bar(actions, window, cx)))).unwrap();
    assert_eq!(focus(handle, &mut window_cx), (Some(actions), false));
    assert_eq!(focus(main, cx).0, None, "the main window's title bar keeps no focus");
    window_cx.simulate_keystrokes("tab");
    assert_eq!(focus(handle, &mut window_cx), (None, true), "Tab goes on to the editor window's active tab");
    window_cx.simulate_keystrokes("shift-tab");
    assert_eq!(focus(handle, &mut window_cx), (Some(actions), false), "Shift+Tab from the tab comes back");
    // The toolbar's first item is Turn On Compact Mode, which runs on Enter.
    window_cx.simulate_keystrokes("home enter");
    window_cx.simulate_event(gpui::KeyUpEvent { keystroke: gpui::Keystroke::parse("enter").unwrap() });
    window_cx.run_until_parked();
    assert!(workbench.read_with(cx, |workbench, _| workbench.is_compact_part(part)));
}

/// titlebarPart.ts `globalActionsEnabled`: an editor window's title bar shows `MenuId.TitleBar`'s actions until it
/// turns compact.
#[gpui::test]
fn an_editor_windows_title_bar_shows_the_global_actions_until_compact(cx: &mut TestAppContext) {
    let (_dir, workbench, cx) = workbench_with("title-global", &["a.txt", "b.txt"], cx);
    workbench.update(cx, |workbench, _| {
        for (id, group) in [("port.lead", "0_leading"), ("port.nav", "navigation")] {
            let entry = Entry::Command { id: id.into(), precondition: None, toggled: None, alt: None };
            workbench.menus.push(MenuItem { menu: MenuId::TitleBar, entry, title: id.into(), group: group.into(), order: 1., when: None });
        }
    });
    run(&workbench, "workbench.action.moveEditorToNewWindow", cx);
    let handle = editor_window(&workbench, cx);
    let mut window_cx = VisualTestContext::from_window(handle, cx);
    let drawn = |cx: &mut VisualTestContext| ["title-bar-action-port.lead", "title-bar-action-port.nav"].map(|selector| cx.debug_bounds(selector).is_some());

    window_cx.run_until_parked();
    assert_eq!(drawn(&mut window_cx), [true; 2]);
    handle.update(&mut window_cx, |_, window, cx| workbench.update(cx, |workbench, cx| drop(workbench.execute_command("workbench.action.enableCompactAuxiliaryWindow", vec![], window, cx)))).unwrap();
    window_cx.run_until_parked();
    assert_eq!(drawn(&mut window_cx), [false; 2]);
}