Skip to content

Visual Studio Code, rebuilt in Rust

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

use config::registry::Registry;
use config::service::Settings;
use exthost::scan::scan_extension;
use gpui::TestAppContext;
use serde_json::{Value, json};

use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::{color_themes, load_theme};
use crate::workbench::Workbench;

fn rows(workbench: &Workbench, _: &gpui::App) -> Vec<String> {
    let input = workbench.quick_inputs.current().expect("a visible quick input");
    let mut rows = Vec::new();
    for row in input.order.iter().map(|row| &input.rows[*row]) {
        let separator = row.separator.as_ref().map(|label| format!("--{label}--")).unwrap_or_default();
        let description = row.item.description.as_ref().map(|description| format!(" ({description})")).unwrap_or_default();
        rows.push(format!("{separator}{}{description}", row.item.label));
    }
    rows
}

#[gpui::test]
fn the_picker_previews_the_focused_theme_writes_the_accepted_one_and_escape_restores(cx: &mut TestAppContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let mut extensions = Vec::new();
    for entry in std::fs::read_dir(app_root.join("extensions")).unwrap() {
        let path = entry.unwrap().path();
        if path.file_name().unwrap().to_string_lossy().starts_with("theme-") {
            extensions.push(scan_extension(&path, true).unwrap());
        }
    }
    let theme = load_theme(&extensions, "Dark 2026").unwrap();
    let dir = std::env::temp_dir().join(format!("code-gpui-themes-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));
    let (sender, messages) = std::sync::mpsc::channel();
    let (workbench, cx) = cx.add_window_view(|_, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings.clone(), HostSync::new(sender), cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("User/keybindings.json"));
        workbench.color_themes = color_themes(&extensions).unwrap();
        workbench
    });
    cx.run_until_parked();
    let theme_id = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.theme.settings_id.clone());
    let sent = || messages.try_iter().filter(|message| !["$activateByEvent", "$initializeIsConnectionMetered"].contains(&message.method)).map(|message| (message.method, message.args)).collect::<Vec<(&str, Vec<Value>)>>();
    let user_settings = || std::fs::read_to_string(dir.join("User/settings.json")).ok();

    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-k secondary-t"));
    assert_eq!(
        workbench.read_with(cx, rows),
        [
            "--light themes--Light 2026 (Default Light)",
            "Light (Visual Studio) (Visual Studio Light)",
            "Light Modern",
            "Light+",
            "Quiet Light",
            "Solarized Light",
            "--dark themes--Dark 2026 (Default Dark)",
            "Abyss",
            "Dark (Visual Studio) (Visual Studio Dark)",
            "Dark Modern",
            "Dark+",
            "Kimbie Dark",
            "Monokai",
            "Monokai Dimmed",
            "Red",
            "Solarized Dark",
            "Tomorrow Night Blue",
            "--high contrast themes--Dark High Contrast (Default High Contrast)",
            "Light High Contrast (Default High Contrast Light)",
        ]
    );
    let (placeholder, active) = workbench.read_with(cx, |workbench, _| {
        let input = workbench.quick_inputs.current().unwrap();
        (input.placeholder.clone(), input.active_handles())
    });
    assert_eq!(placeholder.as_deref(), Some("Select Color Theme (detect system color mode disabled)"));
    assert_eq!(active, [6], "the current theme is focused");

    cx.simulate_keystrokes("down");
    cx.executor().advance_clock(Duration::from_millis(199));
    cx.run_until_parked();
    assert_eq!(theme_id(cx), "Dark 2026", "the preview waits 200ms");
    cx.executor().advance_clock(Duration::from_millis(1));
    cx.run_until_parked();
    assert_eq!(theme_id(cx), "Abyss");
    assert_eq!(sent(), [("$onColorThemeChange", vec![json!("dark")]), ("$acceptSyntaxHighlightingThemeChanged", vec![])]);
    assert_eq!(user_settings(), None, "a preview writes nothing");

    cx.simulate_keystrokes("escape");
    assert_eq!(theme_id(cx), "Dark 2026");
    assert_eq!(sent(), [("$onColorThemeChange", vec![json!("dark")]), ("$acceptSyntaxHighlightingThemeChanged", vec![])]);
    assert_eq!(user_settings(), None, "restoring the current theme writes nothing");

    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-k secondary-t"));
    cx.simulate_input("quiet");
    cx.simulate_keystrokes("enter");
    cx.run_until_parked();
    assert_eq!(theme_id(cx), "Quiet Light");
    assert!(workbench.read_with(cx, |workbench, _| workbench.quick_inputs.current().is_none()));
    let written: Value = serde_json::from_str(&user_settings().unwrap()).unwrap();
    assert_eq!(written, json!({ "workbench.colorTheme": "Quiet Light" }));
    let methods: Vec<&str> = sent().into_iter().map(|(method, _)| method).collect();
    assert_eq!(methods, ["$onColorThemeChange", "$acceptSyntaxHighlightingThemeChanged", "$acceptConfigurationChanged"]);

    // Picking the default again removes the user value (`updateValue` without a target).
    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-k secondary-t"));
    cx.simulate_input("dark 2026");
    cx.simulate_keystrokes("enter");
    assert_eq!(theme_id(cx), "Dark 2026");
    assert_eq!(serde_json::from_str::<Value>(&user_settings().unwrap()).unwrap(), json!({}));
}

/// themes.contribution.ts `SelectFileIconThemeCommandId`: None and the installed file icon themes, previews that
/// Escape undoes, and the accepted theme written to `workbench.iconTheme` (`null` for None).
#[gpui::test]
fn the_file_icon_theme_picker_previews_writes_and_restores(cx: &mut TestAppContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let extensions: Vec<_> = ["theme-seti", "theme-defaults", "theme-modern-icons"].iter().map(|name| scan_extension(&app_root.join("extensions").join(name), true).unwrap()).collect();
    let theme = load_theme(&extensions, "Dark 2026").unwrap();
    let dir = std::env::temp_dir().join(format!("code-gpui-icon-themes-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(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, Languages::new(&[]), settings.clone(), HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("User/keybindings.json"));
        workbench.file_icons = crate::file_icons::FileIconTheme::load(&extensions, "vs-seti").ok();
        workbench.extensions = extensions.clone();
        workbench
    });
    cx.run_until_parked();
    let icon_theme = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.file_icons.as_ref().map(|theme| theme.id.clone()));
    let user_settings = || std::fs::read_to_string(dir.join("User/settings.json")).ok();
    let run = |cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.selectIconTheme", Vec::new(), window, cx)));

    run(cx);
    let rows = workbench.read_with(cx, rows);
    assert_eq!(rows[..2], ["--file icon themes--None (Disable File Icons)".to_string(), "Minimal (Visual Studio Code) (vs-minimal)".into()]);
    assert!(rows.contains(&"Seti (Visual Studio Code) (vs-seti)".to_string()), "{rows:?}");
    let active = workbench.read_with(cx, |workbench, _| workbench.quick_inputs.current().unwrap().active_handles());
    let seti = rows.iter().position(|row| row.starts_with("Seti")).unwrap() as i64;
    assert_eq!(active, [seti], "the current theme is focused");

    cx.simulate_keystrokes(&vec!["up"; seti as usize].join(" "));
    cx.executor().advance_clock(Duration::from_millis(200));
    cx.run_until_parked();
    assert_eq!(icon_theme(cx), None, "None previews without icons");
    cx.simulate_keystrokes("escape");
    assert_eq!(icon_theme(cx).as_deref(), Some("vs-seti"));
    assert_eq!(user_settings(), None);

    run(cx);
    cx.simulate_input("minimal");
    cx.simulate_keystrokes("enter");
    cx.run_until_parked();
    assert_eq!(icon_theme(cx).as_deref(), Some("vs-minimal"), "a commented theme file loads");
    assert_eq!(serde_json::from_str::<Value>(&user_settings().unwrap()).unwrap(), json!({ "workbench.iconTheme": "vs-minimal" }));

    run(cx);
    cx.simulate_input("none");
    cx.simulate_keystrokes("enter");
    assert_eq!(icon_theme(cx), None);
    assert_eq!(serde_json::from_str::<Value>(&user_settings().unwrap()).unwrap(), json!({ "workbench.iconTheme": null }));
}

/// themes.contribution.ts `SelectProductIconThemeCommandId`: Default and the installed product icon themes; the
/// accepted theme is written to `workbench.productIconTheme` and draws its glyphs.
#[gpui::test]
fn the_product_icon_theme_picker_writes_the_accepted_theme(cx: &mut TestAppContext) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let extensions = vec![scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap(), scan_extension(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../port/fixtures/extensions/product-icons"), false).unwrap()];
    let theme = load_theme(&extensions, "Dark 2026").unwrap();
    let dir = std::env::temp_dir().join(format!("code-gpui-product-icon-themes-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    let settings = Arc::new(Mutex::new(Settings::load(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, Languages::new(&[]), settings.clone(), HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("User/keybindings.json"));
        workbench.extensions = extensions.clone();
        workbench
    });
    cx.run_until_parked();
    let product_icons = |cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.product_icons.as_ref().map(|theme| theme.settings_id.clone()));
    let run = |cx: &mut gpui::VisualTestContext| workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.selectProductIconTheme", Vec::new(), window, cx)));

    run(cx);
    assert_eq!(workbench.read_with(cx, rows), ["--product icon themes--Default", "Fixture Icons (fixture-icons)"]);
    cx.simulate_keystrokes("down enter");
    cx.run_until_parked();
    assert_eq!(product_icons(cx).as_deref(), Some("fixture-icons"));
    let user_settings = std::fs::read_to_string(dir.join("User/settings.json")).unwrap();
    assert_eq!(serde_json::from_str::<Value>(&user_settings).unwrap(), json!({ "workbench.productIconTheme": "fixture-icons" }));

    run(cx);
    cx.simulate_keystrokes("up enter");
    assert_eq!(product_icons(cx), None);
}

// themeConfiguration.ts `getColorThemeSettingId` and workbenchThemeService.ts `onDidChangeColorScheme`.
#[gpui::test]
fn the_host_color_scheme_picks_the_preferred_theme_setting(cx: &mut TestAppContext) {
    use super::{HostColorScheme, SettingTarget, color_theme_setting_id};
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let mut extensions = Vec::new();
    for name in ["theme-defaults", "theme-solarized-dark", "theme-solarized-light"] {
        extensions.push(scan_extension(&app_root.join("extensions").join(name), true).unwrap());
    }
    let dir = std::env::temp_dir().join(format!("code-gpui-host-scheme-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    let user = r#"{ "window.autoDetectColorScheme": true, "workbench.preferredLightColorTheme": "Solarized Light", "workbench.preferredDarkColorTheme": "Solarized Dark" }"#;
    std::fs::write(dir.join("User/settings.json"), user).unwrap();
    let settings = Settings::load(Registry::with_extensions(&[]), dir.join("User"), None);
    let scheme = |dark, high_contrast| HostColorScheme { dark, high_contrast };
    assert_eq!(color_theme_setting_id(&settings, scheme(true, false)), "workbench.preferredDarkColorTheme");
    assert_eq!(color_theme_setting_id(&settings, scheme(false, false)), "workbench.preferredLightColorTheme");
    // window.autoDetectHighContrast is on by default and wins over the color scheme.
    assert_eq!(color_theme_setting_id(&settings, scheme(true, true)), "workbench.preferredHighContrastColorTheme");
    assert_eq!(color_theme_setting_id(&settings, scheme(false, true)), "workbench.preferredHighContrastLightColorTheme");

    let theme = load_theme(&extensions, "Dark Modern").unwrap();
    let settings = Arc::new(Mutex::new(settings));
    let (sender, _messages) = std::sync::mpsc::channel();
    let (workbench, cx) = cx.add_window_view(|_, cx| {
        let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings.clone(), HostSync::new(sender), cx);
        workbench.color_themes = color_themes(&extensions).unwrap();
        workbench
    });
    workbench.update(cx, |workbench, cx| {
        workbench.host_colors = scheme(false, false);
        workbench.restore_color_theme(cx);
        assert_eq!(workbench.theme.settings_id, "Solarized Light");
        workbench.host_colors = scheme(true, false);
        workbench.restore_color_theme(cx);
        assert_eq!(workbench.theme.settings_id, "Solarized Dark");
        // A pick writes the setting the scheme reads.
        workbench.set_color_theme("Dark Modern", SettingTarget::Auto, cx);
    });
    let written: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("User/settings.json")).unwrap()).unwrap();
    assert_eq!(written["workbench.preferredDarkColorTheme"], "Dark Modern");
    assert_eq!(written.get("workbench.colorTheme"), None);
}

/// Where the last frame drew: the bounds of every debug selector, then of every hitbox and icon sprite.
/// The test platform's text system draws no glyphs: text shows through the hitboxes of its rows and buttons.
fn drawn_layout(cx: &mut gpui::VisualTestContext) -> (Vec<String>, Vec<String>) {
    let mut selectors: Vec<String> = cx.all_debug_bounds().into_iter().map(|(selector, bounds)| format!("{selector} {bounds:?}")).collect();
    selectors.sort();
    let mut boxes = cx.read_rendered_frame(|scene, hitboxes| {
        let mut boxes = Vec::new();
        for hitbox in hitboxes {
            boxes.push(format!("hitbox y {} x {} {}x{}", hitbox.origin.y, hitbox.origin.x, hitbox.size.width, hitbox.size.height));
        }
        for bounds in scene.monochrome_sprites.iter().map(|sprite| sprite.bounds).chain(scene.polychrome_sprites.iter().map(|sprite| sprite.bounds)) {
            boxes.push(format!("icon y {} x {} {}x{} (device px)", bounds.origin.y.0, bounds.origin.x.0, bounds.size.width.0, bounds.size.height.0));
        }
        boxes
    });
    boxes.sort();
    (selectors, boxes)
}

/// The entries of `a` not in `b`, as a multiset.
fn missing_from(a: &[String], b: &[String]) -> Vec<String> {
    let mut rest = b.to_vec();
    let mut missing = Vec::new();
    for entry in a {
        match rest.iter().position(|other| other == entry) {
            Some(index) => drop(rest.swap_remove(index)),
            None => missing.push(entry.clone()),
        }
    }
    missing
}

/// A window on a folder with two open files, the panel and a toast with two buttons, under Dark Modern, and the
/// temporary directory it reads.
fn laid_out_workbench(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut gpui::VisualTestContext, std::path::PathBuf) {
    use crate::notifications::{Action, Notification, Run, Severity};
    use config::workspace::Workspace;
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let mut extensions = Vec::new();
    for entry in std::fs::read_dir(app_root.join("extensions")).unwrap() {
        let path = entry.unwrap().path();
        if path.file_name().unwrap().to_string_lossy().starts_with("theme-") {
            extensions.push(scan_extension(&path, true).unwrap());
        }
    }
    let dir = std::env::temp_dir().join(format!("code-gpui-theme-layout-{}-{:?}", std::process::id(), std::thread::current().id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("folder")).unwrap();
    let files = [dir.join("folder/a.txt"), dir.join("folder/b.txt")];
    for file in &files {
        std::fs::write(file, "hello world\nsecond line").unwrap();
    }
    let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));
    let theme = load_theme(&extensions, "Dark Modern").unwrap();
    let (workbench, cx) = cx.add_window_view(|window, cx| {
        let workspace = Some(Workspace::folder(dir.join("folder")));
        let mut workbench = Workbench::new(theme, app_root.clone(), workspace, Languages::new(&[]), settings.clone(), HostSync::new(std::sync::mpsc::channel().0), cx);
        workbench.skip_dialogs = true;
        workbench.color_themes = color_themes(&extensions).unwrap();
        for file in &files {
            workbench.open_file(file.clone(), true, window, cx);
        }
        workbench
    });
    cx.run_until_parked();
    workbench.update_in(cx, |workbench, window, cx| {
        drop(workbench.execute_command("workbench.action.togglePanel", Vec::new(), window, cx));
        let action = |label: &str| Action { id: label.into(), label: label.into(), run: Run::Command(String::new(), Vec::new()) };
        let mut notification = Notification::new(Severity::Info, "message");
        notification.primary = vec![action("Yes"), action("No")];
        drop(workbench.notify(notification));
    });
    cx.run_until_parked();
    (workbench, cx, dir)
}

/// What `after` draws elsewhere than `before`, empty when nothing moved.
fn moved(before: &(Vec<String>, Vec<String>), after: &(Vec<String>, Vec<String>)) -> String {
    let gone = [missing_from(&before.0, &after.0), missing_from(&before.1, &after.1)].concat();
    let new = [missing_from(&after.0, &before.0), missing_from(&after.1, &before.1)].concat();
    if gone.is_empty() && new.is_empty() {
        return String::new();
    }
    format!("\n  was {gone:?}\n  now {new:?}")
}

// Upstream's parts keep their size and place across non-high-contrast themes: a border color a theme leaves
// undefined still lays out, or is drawn as an outline that takes no space (workbench/browser/media/part.css).
#[gpui::test]
fn switching_the_color_theme_moves_nothing(cx: &mut TestAppContext) {
    use super::SettingTarget;
    let (workbench, cx, dir) = laid_out_workbench(cx);
    let dark_modern = drawn_layout(cx);
    assert!(dark_modern.1.len() > 50, "{:?}", dark_modern.1);
    let themes = workbench.read_with(cx, |workbench, _| workbench.color_themes.iter().filter(|theme| !theme.kind.is_high_contrast()).map(|theme| theme.settings_id.clone()).collect::<Vec<_>>());
    let mut moves = Vec::new();
    for theme in themes.iter().chain(["Dark Modern".to_string()].iter()) {
        workbench.update(cx, |workbench, cx| workbench.set_color_theme(theme, SettingTarget::Preview, cx));
        cx.run_until_parked();
        let diff = moved(&dark_modern, &drawn_layout(cx));
        if !diff.is_empty() {
            moves.push(format!("{theme}:{diff}"));
        }
    }
    assert!(moves.is_empty(), "{}", moves.join("\n"));
    std::fs::remove_dir_all(dir).unwrap();
}

// Third-party themes define borders no built-in one does. Upstream lays out only these when defined:
// window.activeBorder insets the grid (layout.ts), contrastBorder and contrastActiveBorder add high contrast borders.
#[gpui::test]
fn defining_a_border_color_moves_nothing(cx: &mut TestAppContext) {
    let (workbench, cx, dir) = laid_out_workbench(cx);
    let undefined = drawn_layout(cx);
    let mut moves = Vec::new();
    for key in include_str!("../../webview/color_ids.txt").lines().filter(|id| id.to_lowercase().ends_with("border")) {
        if matches!(key, "contrastBorder" | "contrastActiveBorder" | "window.activeBorder" | "window.inactiveBorder") {
            continue;
        }
        let colors = Value::Object([(key.to_string(), json!("#ff00ff"))].into_iter().collect());
        workbench.update(cx, |workbench, cx| {
            workbench.theme.set_customizations(&colors, &Value::Null);
            cx.notify();
        });
        cx.run_until_parked();
        let diff = moved(&undefined, &drawn_layout(cx));
        if !diff.is_empty() {
            moves.push(format!("{key}:{diff}"));
        }
    }
    assert!(moves.is_empty(), "{}", moves.join("\n"));
    std::fs::remove_dir_all(dir).unwrap();
}