Visual Studio Code, rebuilt in Rust
Rust
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use config::registry::Registry;
use config::service::Settings;
use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};
use exthost::scan::scan_extension;
use exthost::session::ForwardedRequest;
use gpui::{AppContext, TestAppContext, VisualTestContext};
use serde_json::json;
use crate::debug::session::Session;
use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::quick_input::Event;
use crate::theme::load_theme;
use crate::workbench::Workbench;
fn empty_window(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, gpui::AnyWindowHandle) {
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 settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), std::env::temp_dir().join("vsrustium-switch-window-user"), None)));
let (workbench, vcx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root, None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));
vcx.run_until_parked();
(workbench, vcx.update(|window, _| window.window_handle()))
}
/// rawDebugSession.ts `launchVsCode`: js-debug's `launchVSCode` opens an extension development window with the
/// debug flags, and the adapter hears it opened.
#[gpui::test]
fn launch_vs_code_opens_an_extension_development_window_with_the_debug_flags(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, host) = std::sync::mpsc::channel();
let (workbench, vcx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root, None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
let request = json!({ "type": "request", "seq": 3, "command": "launchVSCode", "arguments": {
"args": [{ "prefix": "--debugId=s" }, { "prefix": "--inspect-brk-extensions=9229" }, { "prefix": "--extensionDevelopmentPath=", "path": { "$mid": 1, "scheme": "file", "path": "/tmp/ext" } }],
"env": { "A": "1" },
} });
workbench.update_in(vcx, |workbench, window, cx| {
workbench.debug.sessions.push(Session::new("s".into(), 1, json!({ "name": "Run Extension", "type": "pwa-extensionHost", "request": "launch" }), json!({}), None, json!({})));
drop(workbench.handle_debug_request(ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), request] }, window, cx));
});
vcx.run_until_parked();
let response = host.try_iter().find(|message| message.method == "$sendDAMessage").expect("the response").args[1].clone();
assert_eq!((response["command"].clone(), response["success"].clone()), (json!("launchVSCode"), json!(true)));
let opened: Vec<_> = vcx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.read_with(vcx, |workbench, _| workbench.development.clone().map(|development| (development.extension_path, workbench.extension_host_debug.clone()))).ok().flatten()).collect();
let env = [("A".to_owned(), "1".to_owned())].into_iter().collect();
assert_eq!(opened, [(std::path::absolute("/tmp/ext").unwrap(), ExtensionHostDebug { port: Some(9229), break_on_start: true, debug_id: Some("s".into()), env })]);
}
/// debugService.ts `onDidEndAdapter` (#3905): the end of a 'Run Without Debugging' extension host session closes its
/// development window, and only that one.
#[gpui::test]
fn the_end_of_a_run_without_debugging_session_closes_its_extension_development_window(cx: &mut TestAppContext) {
let (workbench, window) = empty_window(cx);
let development = |debug_id: &str| crate::WindowRequest { development: Some(ExtensionDevelopment { extension_path: "/tmp/ext".into(), tests_path: None }), host_debug: ExtensionHostDebug { debug_id: Some(debug_id.into()), ..Default::default() }, ..Default::default() };
cx.update(|cx| {
open_request_window(development("s"), cx);
open_request_window(development("another"), cx);
});
let vcx = &mut VisualTestContext::from_window(window, cx);
workbench.update_in(vcx, |workbench, window, cx| {
let mut session = Session::new("s".into(), 1, json!({ "name": "Run Extension", "type": "extensionHost", "request": "launch", "noDebug": true }), json!({}), None, json!({}));
session.initialized = true;
workbench.debug.sessions.push(session);
workbench.session_ended("s", window, cx);
let mut debugged = Session::new("another".into(), 2, json!({ "name": "Run Extension", "type": "extensionHost", "request": "launch" }), json!({}), None, json!({}));
debugged.initialized = true;
workbench.debug.sessions.push(debugged);
workbench.session_ended("another", window, cx);
});
vcx.run_until_parked();
let debug_ids: Vec<_> = vcx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.read_with(vcx, |workbench, _| workbench.extension_host_debug.debug_id.clone()).ok()).collect();
assert_eq!(debug_ids, [None, Some("another".to_owned())], "the debugging window and the other session's window stay");
}
/// nativeExtensionService.ts `_onExtensionHostExit`: an extension development window closes with its host, but not for
/// the exit of a host a restart replaced.
#[gpui::test]
fn an_extension_development_window_closes_when_its_current_host_exits(cx: &mut TestAppContext) {
let (workbench, window) = empty_window(cx);
let vcx = &mut VisualTestContext::from_window(window, cx);
let replaced = workbench.update(vcx, |workbench, cx| {
workbench.extension_development = true;
let replaced = workbench.extension_host_started(cx);
workbench.extension_host_started(cx);
replaced
});
workbench.update_in(vcx, |workbench, window, cx| workbench.extension_host_exited(replaced, window, cx));
vcx.run_until_parked();
assert_eq!(vcx.windows().len(), 1, "a replaced host's exit leaves the window open");
workbench.update_in(vcx, |workbench, window, cx| workbench.extension_host_exited(replaced + 1, window, cx));
vcx.run_until_parked();
assert_eq!(vcx.windows().len(), 0);
}
/// localProcessExtensionHost.ts `attachSession` and debugService.ts `onAttachSession`: a debugged extension host's
/// start has the session that launched it attach to its inspector port on a new adapter.
#[gpui::test]
fn a_debugged_extension_host_start_attaches_its_session(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, host) = std::sync::mpsc::channel();
let (workbench, vcx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root, None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));
workbench.update(vcx, |workbench, cx| {
workbench.debug.sessions.push(Session::new("s".into(), 7, json!({ "name": "Run Extension", "type": "pwa-extensionHost", "request": "launch" }), json!({}), None, json!({})));
let host_debug = ExtensionHostDebug { port: Some(9229), break_on_start: true, debug_id: Some("s".into()), env: Default::default() };
workbench.extension_host_debug = host_debug;
workbench.extension_host_started(cx);
});
vcx.run_until_parked();
let messages: Vec<_> = host.try_iter().filter(|message| message.method.ends_with("DASession")).map(|message| (message.method, message.args[0].clone())).collect();
let (handle, configuration) = workbench.read_with(vcx, |workbench, _| {
let session = workbench.debug.session("s").unwrap();
(session.handle, session.configuration.clone())
});
assert_eq!(messages, [("$stopDASession", json!(7)), ("$startDASession", json!(handle))]);
assert_ne!(handle, 7);
assert_eq!((configuration["request"].clone(), configuration["port"].clone()), (json!("attach"), json!(9229)));
}
/// `open_window_or_log` for a test: an empty workbench window with the request's files.
pub(crate) fn open_request_window(request: crate::WindowRequest, cx: &mut gpui::App) {
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 opened = cx.open_window(gpui::WindowOptions::default(), |window, cx| {
cx.new(|cx| {
let mut workbench = Workbench::new(theme, app_root, request.workspace, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
workbench.open_command_line_files(request.files, None, window, cx);
workbench.extension_development = request.development.is_some();
workbench.development = request.development;
workbench.extension_host_debug = request.host_debug;
workbench
})
});
opened.unwrap();
}
/// windowActions.ts `BaseSwitchWindow`: each window with its close button, the next window active, and a row's
/// button closes that window.
#[gpui::test]
fn switch_window_lists_the_windows_and_closes_one_from_its_row(cx: &mut TestAppContext) {
empty_window(cx);
let (current, current_window) = empty_window(cx);
let (_, last_window) = empty_window(cx);
let vcx = &mut VisualTestContext::from_window(current_window, cx);
current.update_in(vcx, |workbench, window, cx| _ = workbench.execute_command("workbench.action.switchWindow", vec![], window, cx));
vcx.run_until_parked();
let (rows, active, id) = current.read_with(vcx, |workbench, _| {
let input = workbench.quick_inputs.current().expect("the window picker");
let rows: Vec<(Option<String>, Option<String>)> = input.order.iter().map(|row| &input.rows[*row].item).map(|item| (item.description.clone(), item.buttons[0].codicon.clone())).collect();
(rows, input.active_handles(), input.id)
});
assert_eq!(rows, [(None, Some("remove-close".into())), (Some("Current Window".into()), Some("window-active".into())), (None, Some("remove-close".into()))]);
assert_eq!(active, [2]);
current.update_in(vcx, |workbench, window, cx| workbench.switch_window_event(id, Event::TriggerItemButton(2, 0, None), window, cx));
vcx.run_until_parked();
let rows = current.read_with(vcx, |workbench, _| workbench.quick_inputs.current().map(|input| input.order.len()));
assert_eq!(rows, Some(2), "`context.removeItem` drops the closed window's row");
let open: Vec<_> = vcx.windows().into_iter().map(|window| window.window_id()).collect();
assert!(!open.contains(&last_window.window_id()), "the last window closed");
assert_eq!(open.len(), 2);
}
/// windowsMainService.ts `open` with `window.openFilesInNewWindow` `off`: a file from the command line or Finder opens
/// in the window whose folder holds it (`findWindowOnFile`), the nearest folder first, not in the last active window.
#[gpui::test]
fn a_file_opens_in_the_window_whose_folder_holds_it(cx: &mut TestAppContext) {
let dir = std::env::temp_dir().join(format!("vsrustium-window-on-file-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("project/sub")).unwrap();
std::fs::write(dir.join("project/top.txt"), "").unwrap();
std::fs::write(dir.join("project/sub/deep.txt"), "").unwrap();
empty_window(cx);
for folder in ["project", "project/sub"] {
cx.update(|cx| open_request_window(crate::WindowRequest { workspace: Some(config::workspace::Workspace::open(dir.join(folder))), ..Default::default() }, cx));
}
let top = dir.join("PROJECT/top.txt").to_string_lossy().into_owned();
cx.update(|cx| super::start_open_window(vec![String::new(), top], "/".into(), false, false, cx));
cx.update(|cx| crate::workbench::url_handler::open_system_urls(vec![format!("file://{}", dir.join("project/sub/deep.txt").display())], cx));
cx.run_until_parked();
let opened: Vec<(Option<PathBuf>, Option<String>)> = cx.update(|cx| {
let workbenches = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.entity(cx).ok());
workbenches.map(|workbench| workbench.read(cx)).map(|workbench| (workbench.workspace().map(|workspace| workspace.folders[0].path.clone()), workbench.editors.active().map(|editor| editor.document().path.file_name().unwrap().to_string_lossy().into_owned()))).collect()
});
assert_eq!(opened, [(None, None), (Some(dir.join("project")), Some("top.txt".into())), (Some(dir.join("project/sub")), Some("deep.txt".into()))]);
std::fs::remove_dir_all(dir).unwrap();
}
/// Chromium keeps a Linux window's z-order level: the toggle sets `isWindowAlwaysOnTop` and toggles it back.
#[cfg(target_os = "linux")]
#[gpui::test]
fn always_on_top_toggles_the_context_key_on_linux(cx: &mut TestAppContext) {
let (workbench, window) = empty_window(cx);
let on_top = |cx: &mut TestAppContext| window.update(cx, |_, window, _| super::is_always_on_top(window)).unwrap();
let toggle = |cx: &mut TestAppContext| window.update(cx, |_, window, cx| workbench.update(cx, |workbench, cx| _ = workbench.execute_command("workbench.action.toggleWindowAlwaysOnTop", vec![], window, cx))).unwrap();
assert!(!on_top(cx));
toggle(cx);
assert!(on_top(cx));
toggle(cx);
assert!(!on_top(cx));
}