Skip to content

Visual Studio Code, rebuilt in Rust

Rust
14.0 KB
Raw Blame
use std::path::Path;
use std::sync::{Arc, Mutex};

use config::registry::Registry;
use config::service::Settings;
use exthost::scan::scan_extension;
use gpui::TestAppContext;

use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::load_theme;
use crate::workbench::Workbench;

#[gpui::test]
fn find_on_type_and_cursor_move_on_type_off_wait_for_enter(cx: &mut TestAppContext) {
    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-find-on-type-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    std::fs::write(dir.join("User/settings.json"), r#"{ "editor.find.findOnType": false, "editor.find.cursorMoveOnType": false }"#).unwrap();
    let file = dir.join("a.txt");
    std::fs::write(&file, "the cat\nand the dog").unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings.clone(), HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("keybindings.json"));
        workbench.open_file(file.clone(), true, window, cx);
        workbench
    });
    cx.run_until_parked();
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.editors.active_mut().unwrap().set_selections(vec![crate::editor::Selection::caret(crate::editor::Position::new(1, 0))]);
        workbench.execute_command("actions.find", vec![], window, cx)
    });
    cx.run_until_parked();
    let found = |cx: &mut gpui::VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let state = &workbench.find.controller.state;
            let head = workbench.editors.active().unwrap().selection().head;
            (state.search_string.clone(), state.matches_count, (head.line, head.column))
        })
    };

    assert_eq!(found(cx), ("and".into(), 1, (1, 0)), "seeded from the word at the cursor");
    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-a"));
    cx.simulate_input("dog");
    assert_eq!(found(cx), ("and".into(), 1, (1, 0)), "typing does not search");
    cx.simulate_keystrokes("enter");
    assert_eq!(found(cx), ("dog".into(), 1, (1, 11)), "Enter searches, then Find Next moves to the match");
    std::fs::remove_dir_all(&dir).unwrap();
}

#[gpui::test]
fn cursor_move_on_type_off_keeps_the_cursor_while_typing(cx: &mut TestAppContext) {
    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-cursor-move-on-type-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    std::fs::write(dir.join("User/settings.json"), r#"{ "editor.find.cursorMoveOnType": false }"#).unwrap();
    let file = dir.join("a.txt");
    std::fs::write(&file, "the cat\nand the dog").unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings.clone(), HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("keybindings.json"));
        workbench.open_file(file.clone(), true, window, cx);
        workbench
    });
    cx.run_until_parked();
    workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("actions.find", vec![], window, cx));
    cx.run_until_parked();
    cx.simulate_input("dog");
    let (count, head) = workbench.read_with(cx, |workbench, _| (workbench.find.controller.state.matches_count, workbench.editors.active().unwrap().selection().head));
    assert_eq!((count, head.line, head.column), (1, 0, 0));
    std::fs::remove_dir_all(&dir).unwrap();
}

#[gpui::test]
fn keys_typed_right_after_cmd_f_go_to_the_find_input(cx: &mut TestAppContext) {
    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-find-keys-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    let file = dir.join("a.txt");
    std::fs::write(&file, "Port notes\nthe cat and the dog").unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));
    // A host that is up, as in the app: no extension declares `onCommand:actions.find`.
    let (sender, host_receiver) = std::sync::mpsc::channel();
    let mut host = HostSync::new(sender);
    host.installed_extensions_registered = true;
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings.clone(), host, cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("keybindings.json"));
        workbench.open_file(file.clone(), true, window, cx);
        workbench
    });
    cx.run_until_parked();
    // The same dispatch as `--screenshot-keys` in main.rs: every key in one update, no frame in between.
    cx.update(|window, cx| {
        for key in ["cmd-f", "t", "h", "e"] {
            window.dispatch_keystroke(gpui::Keystroke::parse(key).unwrap(), cx);
        }
    });
    for message in host_receiver.try_iter().filter(|message| message.method == "$activateByEvent") {
        message.reply.unwrap().send(Ok(serde_json::Value::Null)).unwrap();
    }
    cx.run_until_parked();
    let (search, count, dirty) = workbench.read_with(cx, |workbench, _| {
        let state = &workbench.find.controller.state;
        (state.search_string.clone(), state.matches_count, workbench.editors.active().unwrap().is_dirty())
    });
    assert_eq!((search.as_str(), count, dirty), ("the", 2, false));
    std::fs::remove_dir_all(&dir).unwrap();
}

/// findController.ts: each code editor has its own controller and widget. A widget opened in one group stays open
/// and drawn there while another group has the focus and its own widget closed; the histories are the window's.
#[gpui::test]
fn each_group_keeps_its_own_find_widget_and_shares_the_history(cx: &mut TestAppContext) {
    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!("vsrustium-find-per-group-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    let file = dir.join("a.txt");
    std::fs::write(&file, "the cat\nand the dog").unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings.clone(), HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("keybindings.json"));
        workbench.open_file(file.clone(), true, window, cx);
        workbench
    });
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.splitEditor", vec![], window, cx)));
    cx.run_until_parked();
    let (left, right, right_id) = workbench.read_with(cx, |workbench, _| {
        let groups = workbench.groups_in_grid_order();
        (groups[0], groups[1], workbench.editors.active().unwrap().model_id)
    });
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.editors.id), right);
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("actions.find", vec![], window, cx)));
    cx.run_until_parked();
    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-a"));
    cx.simulate_input("dog");
    cx.executor().advance_clock(std::time::Duration::from_millis(500));
    cx.run_until_parked();

    workbench.update_in(cx, |workbench, window, cx| workbench.focus_group(left, window, cx));
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    let (left_find, right_find) = workbench.update(cx, |workbench, _| {
        let state = |workbench: &Workbench| (workbench.find.controller.state.is_revealed, workbench.find.controller.state.search_string.clone(), workbench.find.controller.state.matches_count);
        let right_find = workbench.with_group(right, |workbench| state(workbench));
        (state(workbench), right_find)
    });
    assert!(!left_find.0, "the focused group's editor has its own find widget, closed: {left_find:?}");
    assert_eq!(right_find, (true, "dog".to_string(), 1), "the other group's widget stays open");
    let area = cx.debug_bounds(format!("text-area-{right_id}").leak()).unwrap();
    let find = cx.debug_bounds("find-widget").expect("the unfocused group draws its find widget");
    assert!(find.left() >= area.left() && find.right() <= area.right(), "the find widget {find:?} is over the right group's editor {area:?}");
    let history = workbench.read_with(cx, |workbench, _| workbench.find.find_history.elements().to_vec());
    assert_eq!(history, ["dog"], "the find history is the window's, shared by every code editor's widget");

    // `FindModelBoundToEditorModel` listens to its model: an edit in the left editor finds again in the right one.
    cx.simulate_input("dog ");
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    let right_matches = workbench.update(cx, |workbench, _| workbench.with_group(right, |workbench| workbench.find.controller.model.as_ref().unwrap().matches.len()));
    assert_eq!(right_matches, 2, "the right editor's widget found the typed dog");
    std::fs::remove_dir_all(&dir).unwrap();
}

fn open_find<'a>(cx: &'a mut TestAppContext, name: &str, text: &str) -> (gpui::Entity<Workbench>, &'a mut gpui::VisualTestContext, std::path::PathBuf) {
    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.join("User")).unwrap();
    let file = dir.join("a.txt");
    std::fs::write(&file, text).unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings.clone(), HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("keybindings.json"));
        workbench.open_file(file.clone(), true, window, cx);
        workbench
    });
    cx.run_until_parked();
    (workbench, cx, dir)
}

/// findWidget.ts: Ctrl+Enter breaks the find input's line (`_onFindInputKeyDown`), the input and the widget grow
/// (`flexibleHeight`, `_getHeight`), and Up in a multi-line input moves its caret, not through the history.
#[gpui::test]
fn the_find_input_takes_several_lines(cx: &mut TestAppContext) {
    let (workbench, cx, dir) = open_find(cx, "find-multiline", "ab\ncd\nab\ncd\n");
    workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("actions.find", vec![], window, cx));
    cx.run_until_parked();
    cx.simulate_input("ab");
    cx.simulate_keystrokes("ctrl-enter");
    cx.simulate_input("cd");
    let state = |cx: &mut gpui::VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let find = &workbench.find;
            (find.controller.state.search_string.clone(), find.controller.state.matches_count, find.find_input.selection, workbench.find_widget_height(), workbench.editors.viewport.top_whitespace)
        })
    };
    assert_eq!(state(cx), ("ab\ncd".into(), 2, (5, 5), 52., 52.));
    cx.simulate_keystrokes("up");
    assert_eq!(state(cx).2, (2, 2), "the caret goes to the line above");
    for _ in 0..7 {
        cx.simulate_keystrokes("ctrl-enter");
    }
    assert_eq!(state(cx).3, 4. + 118. + 2. + 4., "the input stops growing at `flexibleMaxHeight`");
    std::fs::remove_dir_all(&dir).unwrap();
}

/// Cmd+E over two lines of a CRLF file: the state keeps the model's "\r\n", the input shows the textarea's "\n"
/// (`_onStateChanged` sets `textarea.value`).
#[gpui::test]
fn the_find_input_shows_a_crlf_seed_with_lf(cx: &mut TestAppContext) {
    let (workbench, cx, dir) = open_find(cx, "find-crlf", "ab\r\ncd\r\nab\r\ncd\r\n");
    let selection = crate::editor::Selection { anchor: crate::editor::Position::new(2, 0), head: crate::editor::Position::new(3, 2) };
    workbench.update(cx, |workbench, _| workbench.editors.active_mut().unwrap().set_selections(vec![selection]));
    workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("actions.findWithSelection", vec![], window, cx));
    cx.run_until_parked();
    let find = workbench.read_with(cx, |workbench, _| (workbench.find.controller.state.search_string.clone(), workbench.find.find_input.value.clone()));
    assert_eq!(find, ("ab\r\ncd".into(), "ab\ncd".into()));
    std::fs::remove_dir_all(&dir).unwrap();
}