Skip to content

Visual Studio Code, rebuilt in Rust

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

use exthost::scan::scan_extension;
use gpui::{TestAppContext, VisualTestContext};
use serde_json::{Value, json};

use crate::editor::injected_text::{InjectedText, InjectionOwner, WrapWidth};
use crate::editor::{Position, Selection};
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::load_theme;
use crate::workbench::Workbench;

fn workbench_in<'a>(name: &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();
    std::fs::write(dir.join("far.js"), "one\ntwo\nthree").unwrap();
    let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx));
    (dir, workbench, cx)
}

fn open(workbench: &gpui::Entity<Workbench>, args: Vec<Value>, cx: &mut VisualTestContext) -> Result<Value, Value> {
    workbench.update_in(cx, |workbench, window, cx| workbench.api_open_editor(&args, window, cx))
}

fn file_uri(path: &Path) -> Value {
    crate::editor::uri_value("file", path)
}

#[gpui::test]
fn workbench_open_shows_files_and_untitled_files_and_rejects_other_strings(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("workbench-open", cx);
    let selection = json!({ "startLineNumber": 2, "startColumn": 1, "endLineNumber": 2, "endColumn": 4 });
    assert_eq!(open(&workbench, vec![file_uri(&dir.join("far.js")), json!([1, { "selection": selection }])], cx), Ok(Value::Null));
    let selection = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selection());
    assert_eq!(selection, Selection { anchor: Position { line: 1, column: 0 }, head: Position { line: 1, column: 3 } });

    // commands.test.ts #138925: an untitled resource with a path is dirty from the start.
    let untitled = json!({ "scheme": "untitled", "path": dir.join("untitled-file.txt").to_string_lossy() });
    assert_eq!(open(&workbench, vec![untitled], cx), Ok(Value::Null));
    let (name, dirty) = workbench.read_with(cx, |workbench, _| {
        let editor = workbench.editors.active().unwrap();
        (editor.document().name(), editor.is_dirty())
    });
    assert_eq!((name.as_str(), dirty), ("untitled-file.txt", true));
    // untitledTextEditorModel.ts `revert`: emptied and clean, never read from or written to its file; the input closes.
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.files.revert", Vec::new(), window, cx)));
    let names = workbench.read_with(cx, |workbench, _| workbench.editors.editors.iter().map(|editor| editor.document().name()).collect::<Vec<_>>());
    assert_eq!(names, ["far.js"]);
    assert!(!dir.join("untitled-file.txt").exists());

    assert!(open(&workbench, vec![json!("file:///some/path/not/http")], cx).is_err());
    assert_eq!(open(&workbench, vec![json!({ "scheme": "command", "path": "workbench.action.quit" })], cx), Ok(Value::Null));
    std::fs::remove_dir_all(dir).unwrap();
}

#[gpui::test]
fn workbench_open_reads_a_line_fragment_as_the_selection(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("workbench-open-fragment", cx);
    // markdown-language-features documentLink.test.ts `Should navigate to fragment by line`: `vscode.open` of `#L2`.
    let uri = json!({ "scheme": "file", "path": dir.join("far.js").to_string_lossy(), "fragment": "L3" });
    let outcome = workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("_workbench.open", vec![uri, Value::Null], window, cx));
    assert!(matches!(outcome, crate::commands::Outcome::Ready(Ok(_))));
    let selection = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().selection());
    assert_eq!(selection.head, Position { line: 2, column: 0 });
    std::fs::remove_dir_all(dir).unwrap();
}

#[gpui::test]
fn decoration_types_set_and_remove_editor_decorations(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("decorations", cx);
    open(&workbench, vec![file_uri(&dir.join("far.js"))], cx).unwrap();
    let id = workbench.read_with(cx, |workbench, _| crate::host_sync::snapshot_id(workbench.editors.active().unwrap()));
    let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", method, &args, window, cx));
    let options = json!({ "isWholeLine": true, "backgroundColor": { "id": "merge.currentHeaderBackground" }, "after": { "contentText": " (Current Change)" } });
    request("$registerTextEditorDecorationType", vec![json!("vscode.merge-conflict"), json!("TextEditorDecorationType1"), options], cx).unwrap();
    request("$trySetDecorationsFast", vec![json!(id), json!("TextEditorDecorationType1"), json!([2, 1, 2, 4])], cx).unwrap();
    let decorations = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().text_decorations.clone());
    assert_eq!((decorations.len(), decorations[0].start, decorations[0].end), (1, Position::new(1, 0), Position::new(1, 3)));
    // The `after` text is an inline span: it takes room after "two" instead of being drawn over the line.
    let content = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().injected_text_on(1).to_vec());
    let after = InjectedText { position: Position::new(1, 3), columns: 17., content: " (Current Change)".into(), wrap: WrapWidth::Chars, owner: InjectionOwner::DecorationContent, id: 1, at_range_start: false };
    assert_eq!(content, [after]);
    // A second set replaces the type's decorations; removing the type clears them.
    request("$trySetDecorations", vec![json!(id), json!("TextEditorDecorationType1"), json!([])], cx).unwrap();
    assert!(workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().text_decorations.is_empty()));
    request("$trySetDecorationsFast", vec![json!(id), json!("TextEditorDecorationType1"), json!([1, 1, 1, 2])], cx).unwrap();
    request("$removeTextEditorDecorationType", vec![json!("TextEditorDecorationType1")], cx).unwrap();
    assert!(workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().text_decorations.is_empty()));
    assert!(workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().injected_text.is_empty()));
    std::fs::remove_dir_all(dir).unwrap();
}

/// abstractCodeEditorService.ts `_collectOutlineSettingsCSSText`: a CSS outline is drawn outside the range's box,
/// `outlineWidth` wide on each side, where a border would sit inside it.
#[gpui::test]
fn a_decoration_outline_is_drawn_outside_its_range(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("decoration-outline", cx);
    open(&workbench, vec![file_uri(&dir.join("far.js"))], cx).unwrap();
    let id = workbench.read_with(cx, |workbench, _| crate::host_sync::snapshot_id(workbench.editors.active().unwrap()));
    let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", method, &args, window, cx));
    let options = json!({ "outlineColor": "#ff0000", "outlineStyle": "solid", "outlineWidth": "2px" });
    request("$registerTextEditorDecorationType", vec![json!("test"), json!("TextEditorDecorationType1"), options], cx).unwrap();
    request("$trySetDecorationsFast", vec![json!(id), json!("TextEditorDecorationType1"), json!([3, 2, 3, 5])], cx).unwrap();
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    let (line_height, char_width) = workbench.update_in(cx, |workbench, window, _| {
        let metrics = workbench.editor_metrics(workbench.editors.active().unwrap(), window);
        (metrics.line_height, metrics.char_width)
    });
    let outline = cx.debug_bounds("text-decoration-outline-2").expect("the outline is drawn");
    // GPUI rounds the layout to whole pixels.
    assert_eq!((f32::from(outline.size.width), f32::from(outline.size.height)), ((3. * char_width + 4.).round(), line_height + 4.));
    std::fs::remove_dir_all(dir).unwrap();
}

/// mainThreadEditor.ts `setConfiguration`: the code editor takes the extension's cursorStyle and lineNumbers
/// (`updateOptions`), and `_updatePropertiesNow` sends the changed options back once.
#[gpui::test]
fn set_options_apply_the_cursor_style_and_line_numbers(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-set-options-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("far.js"), "one\ntwo").unwrap();
    let (sender, messages) = std::sync::mpsc::channel();
    let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
    open(&workbench, vec![file_uri(&dir.join("far.js"))], cx).unwrap();
    let id = workbench.read_with(cx, |workbench, _| crate::host_sync::snapshot_id(workbench.editors.active().unwrap()));
    let added: Vec<Value> = messages.try_iter().filter(|message| message.method == "$acceptDocumentsAndEditorsDelta").map(|message| message.args[0]["addedEditors"][0]["options"].clone()).collect();
    assert_eq!((&added[0]["cursorStyle"], &added[0]["lineNumbers"]), (&json!(1), &json!(1)));

    let set = |options: Value, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", "$trySetOptions", &[json!(id), options], window, cx));
    assert_eq!(set(json!({ "cursorStyle": 2, "lineNumbers": 2 }), cx), Ok(Value::Null));
    let line_numbers = workbench.read_with(cx, |workbench, _| workbench.line_numbers(workbench.editors.active().unwrap()));
    assert_eq!(line_numbers, crate::workbench::editor_view::LineNumbers::Relative);
    let sent: Vec<Value> = messages.try_iter().filter(|message| message.method == "$acceptEditorPropertiesChanged").map(|message| message.args[1]["options"].clone()).collect();
    assert_eq!(sent.len(), 1);
    assert_eq!((&sent[0]["cursorStyle"], &sent[0]["lineNumbers"]), (&json!(2), &json!(2)));
    // An unchanged configuration sends nothing.
    set(json!({ "cursorStyle": 2, "lineNumbers": 2 }), cx).unwrap();
    assert_eq!(messages.try_iter().filter(|message| message.method == "$acceptEditorPropertiesChanged").count(), 0);

    // `zenMode.hideLineNumbers` turns the drawn line numbers off, and the host hears it.
    let zen_line_numbers = |cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, cx| workbench.toggle_zen_mode(false, window, cx));
        messages.try_iter().filter(|message| message.method == "$acceptEditorPropertiesChanged").map(|message| message.args[1]["options"]["lineNumbers"].clone()).collect::<Vec<_>>()
    };
    assert_eq!(zen_line_numbers(cx), [json!(0)]);
    assert_eq!(zen_line_numbers(cx), [json!(2)]);
    std::fs::remove_dir_all(dir).unwrap();
}

#[gpui::test]
fn text_editor_show_and_hide_open_and_close_the_editor(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("show-hide-editor", cx);
    std::fs::write(dir.join("near.js"), "four").unwrap();
    open(&workbench, vec![file_uri(&dir.join("far.js"))], cx).unwrap();
    let id = workbench.read_with(cx, |workbench, _| crate::host_sync::snapshot_id(workbench.editors.active().unwrap()));
    let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", method, &args, window, cx));
    // extHostTextEditor.ts `show(column)`: the editor's document opens in that column.
    assert_eq!(request("$tryShowEditor", vec![json!(id), json!(1)], cx), Ok(Value::Null));
    let (groups, active) = workbench.read_with(cx, |workbench, _| (workbench.groups_in_grid_order().len(), workbench.editors.active().unwrap().document().name()));
    assert_eq!((groups, active.as_str()), (2, "far.js"));
    // `hide()` closes the editor in its group; an unknown id is no error.
    let id = workbench.read_with(cx, |workbench, _| crate::host_sync::snapshot_id(workbench.editors.active().unwrap()));
    assert_eq!(request("$tryHideEditor", vec![json!(id)], cx), Ok(Value::Null));
    // The emptied second group closes too (`workbench.editor.closeEmptyGroups`).
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.groups_in_grid_order().len()), 1);
    assert_eq!(request("$tryHideEditor", vec![json!("unknown")], cx), Ok(Value::Null));
    std::fs::remove_dir_all(dir).unwrap();
}

#[gpui::test]
fn view_columns_pick_or_add_groups_in_grid_order(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("view-columns", cx);
    let show = |position: i64, cx: &mut VisualTestContext| {
        let uri = file_uri(&dir.join("far.js"));
        workbench.update_in(cx, |workbench, window, cx| workbench.try_show_text_document(&uri, &json!({ "position": position }), window, cx)).unwrap();
        workbench.read_with(cx, |workbench, _| (workbench.groups_in_grid_order().len(), workbench.groups_in_grid_order().iter().position(|group| *group == workbench.editors.id).unwrap()))
    };
    // window.test.ts `editor, assign and check view columns`: One, Two and Three are the first three groups.
    assert_eq!(show(0, cx), (1, 0));
    assert_eq!(show(1, cx), (2, 1));
    assert_eq!(show(2, cx), (3, 2));
    assert_eq!(show(0, cx), (3, 0));
    // ACTIVE keeps the group, SIDE takes the neighbour to the right.
    assert_eq!(show(-1, cx), (3, 0));
    assert_eq!(show(-2, cx), (3, 1));
    std::fs::remove_dir_all(dir).unwrap();
}

#[gpui::test]
fn workbench_open_reads_a_provider_resource_through_the_host(cx: &mut TestAppContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
    let (sender, messages) = std::sync::mpsc::channel();
    let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
    let uri = json!({ "scheme": "fake-fs", "path": "/a/b.txt" });
    let outcome = workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("_workbench.open", vec![uri.clone()], window, cx));
    let crate::commands::Outcome::Pending(mut opened) = outcome else { panic!("the open waits for the provider") };
    let asked = messages.try_iter().find(|message| message.method == "resolveTextContent").expect("asked the host");
    assert_eq!(asked.args, [uri.clone()]);
    let _ = asked.reply.expect("a call").send(Ok(json!(b"from the provider".to_vec())));
    cx.run_until_parked();
    assert_eq!(opened.try_recv().unwrap(), Some(Ok(Value::Null)));
    let text = workbench.read_with(cx, |workbench, _| workbench.editors.active().map(|editor| editor.document().lines.join("\n")));
    assert_eq!(text.as_deref(), Some("from the provider"));

    // mainThreadDocumentContentProviders.ts `$onVirtualDocumentChange`: computeMoreMinimalEdits keeps "from the " untouched.
    _ = messages.try_iter().count();
    workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadDocumentContentProviders", "$onVirtualDocumentChange", &[uri.clone(), json!("from the server")], window, cx)).unwrap();
    let changed = messages.try_iter().find(|message| message.method == "$acceptModelChanged").expect("the host hears the change");
    let offsets: Vec<u64> = changed.args[1]["changes"].as_array().unwrap().iter().map(|change| change["rangeOffset"].as_u64().unwrap()).collect();
    assert!(!offsets.is_empty() && offsets.iter().all(|&offset| offset >= 9), "changes at {offsets:?}");
    let text = workbench.read_with(cx, |workbench, _| workbench.editors.active().map(|editor| editor.document().lines.join("\n")));
    assert_eq!(text.as_deref(), Some("from the server"));
}

#[gpui::test]
fn workbench_open_opens_in_the_given_column(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("workbench-open-column", cx);
    let uri = file_uri(&dir.join("far.js"));
    let outcome = workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("_workbench.open", vec![uri, json!([1, {}])], window, cx));
    assert!(matches!(outcome, crate::commands::Outcome::Ready(Ok(_))));
    let (columns, active) = workbench.read_with(cx, |workbench, _| (workbench.editors.column_ids(), workbench.editors.id));
    assert_eq!((columns.len(), columns[1]), (2, active), "ViewColumn.Two is the second group");
    std::fs::remove_dir_all(dir).unwrap();
}

/// mainThreadLanguages.ts `$tokensAtPosition`: without a grammar the line is one Other token; a model that is not
/// open has none.
#[gpui::test]
fn tokens_at_position_answers_the_token_of_an_open_model(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("tokens-at-position", cx);
    let uri = file_uri(&dir.join("far.js"));
    let position = json!({ "lineNumber": 2, "column": 2 });
    let ask = |cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadLanguages", "$tokensAtPosition", &[uri.clone(), position.clone()], window, cx));
    assert_eq!(ask(cx), Ok(Value::Null));
    assert_eq!(open(&workbench, vec![uri.clone()], cx), Ok(Value::Null));
    assert_eq!(ask(cx), Ok(json!({ "type": 0, "range": { "startLineNumber": 2, "startColumn": 1, "endLineNumber": 2, "endColumn": 4 } })));
    std::fs::remove_dir_all(dir).unwrap();
}

/// mainThreadLanguages.ts `$computeFullSyntaxHighlighting`: a language by its name, tokens with one style merged,
/// a token per newline; an unknown language is one plain token.
#[gpui::test]
fn full_syntax_highlighting_tokenizes_with_the_theme(cx: &mut TestAppContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
    let languages = Languages::new(&exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap());
    let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, languages, crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx));
    let ask = |source: &str, language: &str, cx: &mut VisualTestContext| {
        let args = [json!(source), json!(language)];
        workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadLanguages", "$computeFullSyntaxHighlighting", &args, window, cx)).unwrap()
    };
    let result = ask("let x\nx", "TypeScript", cx);
    let tokens: Vec<(u64, u64)> = result["tokens"].as_array().unwrap().iter().map(|token| (token["length"].as_u64().unwrap(), token["foreground"].as_u64().unwrap())).collect();
    let color = |index: u64| result["colorMap"][index as usize].as_str().unwrap().to_owned();
    assert_eq!(tokens.iter().map(|(length, _)| length).sum::<u64>(), 7);
    assert_eq!(tokens[0].0, 3, "`let`");
    assert_eq!(color(tokens[0].1), "#569cd6ff");
    assert_eq!(tokens[tokens.len() - 2], (1, 0), "the newline");
    assert_eq!(result["colorMap"][0], "");
    assert_eq!(ask("ab", "no-such-language", cx)["tokens"], json!([{ "length": 2, "foreground": 0, "fontStyle": 0 }]));
}

#[gpui::test]
fn workspace_encodings_read_files_encoding_of_the_resource_language(cx: &mut TestAppContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
    let dir = std::env::temp_dir().join(format!("code-gpui-encoding-language-{}", 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#"{ "[plaintext]": { "files.encoding": "iso88591", "files.autoGuessEncoding": true } }"#).unwrap();
    std::fs::write(dir.join("server.log"), "log").unwrap();
    let settings = config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None);
    let settings = std::sync::Arc::new(std::sync::Mutex::new(settings));
    let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));
    let ask = |method: &str, path: &Path, cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.resolve_text_file_encoding(method, &file_uri(path), &Value::Null, &Value::Null));
    let text = dir.join("notes.txt");
    assert_eq!(ask("$resolveDecoding", &text, cx), json!({ "preferredEncoding": "iso88591", "guessEncoding": true, "candidateGuessEncodings": [] }));
    assert_eq!(ask("$resolveEncoding", &text, cx), json!({ "encoding": "iso88591", "addBOM": false }));
    let log = dir.join("server.log");
    assert_eq!(ask("$resolveEncoding", &log, cx)["encoding"], "utf8", "no language matches the path");
    assert_eq!(open(&workbench, vec![file_uri(&log)], cx), Ok(Value::Null));
    assert_eq!(ask("$resolveEncoding", &log, cx)["encoding"], "iso88591", "the open model is plaintext");
    std::fs::remove_dir_all(dir).unwrap();
}

#[gpui::test]
fn the_extension_host_reads_default_settings_from_the_workbench(cx: &mut TestAppContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
    let settings = config::service::Settings::load(config::registry::Registry::with_extensions(&[]), PathBuf::from("/nonexistent/User"), None);
    let settings = std::sync::Arc::new(std::sync::Mutex::new(settings));
    let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));
    let ask = |path: &str, cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.default_settings_content(&json!({ "scheme": "vscode", "authority": "defaultsettings", "path": path })));
    assert!(ask("/defaultSettings.jsonc", cx).as_str().unwrap().starts_with('{'));
    assert!(ask("/keybindings.json", cx).as_str().unwrap().starts_with("// Override key bindings"));
    assert_eq!(ask("/missing.json", cx), Value::Null);
}

/// mainThreadDocuments.ts \`$trySaveDocument\` awaits \`textFileService.save\`: an untitled document's answer comes once
/// the save dialog picked its file and the text is written.
#[gpui::test]
fn save_document_answers_after_the_save_dialog(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-save-after-dialog-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
    drop(settings.lock().unwrap().update_value("files.simpleDialog.enable", Some(&json!(true)), config::service::Target::User, None, &[]).unwrap());
    let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));
    let (requests, received) = futures::channel::mpsc::unbounded();
    workbench.update_in(cx, |_, window, cx| crate::workbench::extension_host_restart::serve_main_thread_requests(received, window, cx));
    let uri = workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadDocuments", "$tryCreateDocument", &[json!({ "content": "hello" })], window, cx)).unwrap();

    let (reply, answer) = std::sync::mpsc::channel();
    requests.unbounded_send(crate::main_thread::HostRequest { proxy: "MainThreadDocuments", method: "$trySaveDocument".into(), args: vec![uri], reply }).unwrap();
    cx.run_until_parked();
    assert!(answer.try_recv().is_err(), "no answer while the save dialog is open");
    let target = dir.join("saved.txt");
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.with_current_quick_input(window, cx, |input| input.edit_input(|input_box| input_box.set_value(target.to_string_lossy().into_owned())));
        _ = workbench.execute_command("workbench.action.acceptSelectedQuickOpenItem", vec![], window, cx);
    });
    cx.run_until_parked();
    assert_eq!(answer.try_recv().unwrap(), Ok(json!(true)));
    assert_eq!(std::fs::read_to_string(&target).unwrap(), "hello");
    std::fs::remove_dir_all(dir).unwrap();
}

/// mainThreadDocuments.ts `_handleAsResourceInput`: `openTextDocument(uri, { encoding })` of an open, clean model of
/// an extension's file system provider decodes the bytes the provider reads again (textFileEditorModel.ts `setEncodingInternal`).
#[gpui::test]
fn open_document_with_an_encoding_decodes_a_provider_model_again(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("provider-encoding", cx);
    let uri = json!({ "scheme": "fake-fs", "path": "/a/latin.txt" });
    let bytes = json!(b"caf\xe9".to_vec());
    let open = |encoding: Value, cx: &mut VisualTestContext| workbench.update(cx, |workbench, cx| workbench.try_open_document(&uri, &json!({ "encoding": encoding }), &bytes, false, cx));
    open(json!("utf8"), cx).unwrap();
    open(json!("iso88591"), cx).unwrap();
    let document = workbench.read_with(cx, |workbench, _| workbench.editors.model("fake-fs", Path::new("/a/latin.txt")).map(|model| (model.document().lines.join("\n"), model.document().encoding.clone())));
    assert_eq!(document, Some(("café".to_string(), "iso88591".to_string())));
    std::fs::remove_dir_all(dir).unwrap();
}

/// uriIdentityService.ts `asCanonicalUri` keeps the casing opened first in any group: `openTextDocument` of another
/// casing resolves to the model whose only editor is in another group.
#[gpui::test]
fn open_document_in_another_casing_finds_the_model_in_another_group(cx: &mut TestAppContext) {
    let (dir, workbench, cx) = workbench_in("casing-other-group", cx);
    assert_eq!(open(&workbench, vec![file_uri(&dir.join("far.js"))], cx), Ok(Value::Null));
    crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);
    let opened = workbench.update(cx, |workbench, cx| workbench.try_open_document(&file_uri(&dir.join("FAR.js")), &json!({}), &Value::Null, true, cx));
    assert_eq!(opened.unwrap()["path"], json!(dir.join("far.js").to_string_lossy()));
    std::fs::remove_dir_all(dir).unwrap();
}