Visual Studio Code, rebuilt in Rust
Rust
//! The native app: the workbench, themed from the built-in theme files, over the running extension host.
//! Usage: vsrustium [folder or .code-workspace file [file]] [--theme <settings id>] [--user-data-dir <dir>] [--screenshot <png>]
//! [--screenshot-keys "<keystroke> ..."] [--screenshot-input <steps>] [--node] [--export-default-keybindings [<folder>]]
//! [--extensionDevelopmentPath=<dir> [--extensionTestsPath=<path>]]: the app exits with the test runner's code.
// A GUI binary as Electron's, so a start from Explorer opens no console; cli::route_stdio_to_console finds the terminal's.
#![cfg_attr(windows, windows_subsystem = "windows")]
#[cfg_attr(not(test), expect(dead_code, reason = "the code action menu of milestone 13 is its first desktop caller"))]
mod action_list;
mod app_icon;
mod accessibility_signals;
mod anything_quick_access;
mod argv;
mod cli;
mod cli_process;
mod backups;
mod brackets;
mod bulk_edit_preview;
mod clipboard;
mod codicons;
// wu's gpui_platform `current_headless_renderer` is Metal only, None elsewhere.
#[cfg(all(test, target_os = "macos"))]
mod corner_lab;
#[cfg(test)]
mod retained_check;
mod command_palette;
mod commands;
mod custom_tree;
mod decorations;
mod contextkey;
mod debug;
mod default_settings;
mod diff_editor;
mod dialog;
mod file_dialog;
mod editor;
mod editor_grid;
mod navigation;
mod editor_history;
mod explorer;
mod extension_enablement;
mod extension_host_start;
mod extension_point_messages;
mod extension_recommendations;
mod extensions_model;
mod file_actions;
mod file_icons;
mod product_icons;
mod filters;
mod history;
mod fuzzy_scorer;
mod hierarchy_model;
mod host_sync;
mod input_box;
mod keybinding_editing;
mod keybindings;
mod keybindings_editor;
mod keyboard_layout;
mod keyboard_mapper;
mod system_wide_keybindings;
mod language_feature_debounce;
mod language_features;
mod languages;
mod launch;
mod diagnostics;
mod list_tree;
mod link_computer;
mod local_history;
mod main_thread;
mod main_thread_commands;
mod main_thread_github;
mod main_thread_errors;
mod main_thread_message;
mod main_thread_output;
mod main_thread_progress;
mod main_thread_quick_open;
mod main_thread_status_bar;
mod markdown;
mod markers;
mod markers_filter;
mod menus;
mod merge_editor;
mod multi_diff_editor;
mod nls;
mod outline_model;
mod metered_connection;
mod notebook;
mod notifications;
mod output;
mod perf;
mod power;
// The process explorer (milestone 19 handoff) is its first caller; until then only its tests build it.
mod ps;
mod product;
mod update;
mod profile_template;
mod timer;
mod walkthroughs;
mod policy;
mod quick_input;
mod recently_opened;
mod references_model;
mod search_editor;
mod scm;
mod scm_history;
mod search_model;
mod semantic_tokens;
mod default_document_colors;
mod ghost_text;
mod language_detection;
mod encoding_guess;
mod settings_editor;
#[cfg(unix)]
mod shell_env;
mod settings_import;
mod smart_snippet_inserter;
mod snippets;
mod split_view;
mod symbol_kinds;
mod suggest;
mod symbol_icons;
mod syntax;
mod tasks;
mod terminal;
mod testing;
mod testing_coverage;
mod tf_idf;
mod theme;
mod timeline;
mod trusted_domains;
mod undo_redo;
mod untitled;
mod variables;
mod webview;
mod uri;
mod user_data_profile;
#[cfg(target_os = "windows")]
mod win32;
mod windows_state;
mod workbench;
mod workspace_trust;
#[cfg(target_os = "linux")]
mod x11;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use config::configuration::Overrides;
use config::registry::Registry;
use config::service::Settings;
use config::workspace::Workspace;
use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};
use exthost::extension_management::{UserExtensions, add_user_extensions};
use exthost::main_thread_storage::MainThreadStorage;
use exthost::scan::{ScannedExtension, scan_builtin_extensions};
use exthost::session::SessionPaths;
use exthost::Runtime;
use gpui::{App, Bounds, Keystroke, TitlebarOptions, Window, WindowBounds, WindowOptions, point, prelude::*, px, size};
use gpui_platform::application;
use serde_json::json;
use anyhow::Context as _;
use extension_host_start::{HostLaunch, HostProcess, HostStart};
use languages::Languages;
use theme::load_theme;
use workbench::Workbench;
fn main() -> anyhow::Result<()> {
perf::mark("code/didStartMain");
// electron_main_win.cc: `base::RouteStdioToConsole` unless the CLI started the app with ELECTRON_NO_ATTACH_CONSOLE.
#[cfg(windows)]
if std::env::var_os("ELECTRON_RUN_AS_NODE").is_some() || std::env::var_os("ELECTRON_NO_ATTACH_CONSOLE").is_none() {
cli::route_stdio_to_console();
}
let args: Vec<String> = std::env::args().collect();
if args.get(1).is_some_and(|arg| arg == update::install::APPLY_UPDATE) {
return update::install::apply_update(&args[2..]);
}
let runtime = if args.iter().any(|arg| arg == "--node") { Runtime::Node } else { Runtime::Bun };
let flag_value = |flag: &str| args.iter().position(|arg| arg == flag).and_then(|i| args.get(i + 1)).cloned();
let user_data = match flag_value("--user-data-dir") {
Some(dir) => PathBuf::from(dir),
None => default_user_data()?,
};
std::fs::create_dir_all(&user_data).with_context(|| format!("creating {}", user_data.display()))?;
// Packaged (product::BUNDLED_APP) the app files sit beside the binary's folder; run from the
// checkout they are the VS Code tree (VSCODE_SRC, native/vscode_src.rs).
#[cfg(target_os = "macos")]
let bundled = std::env::current_exe()?.parent().and_then(|macos| macos.parent()).map(|contents| contents.join("Resources/app"));
#[cfg(any(target_os = "linux", target_os = "windows"))]
let bundled = std::env::current_exe()?.parent().map(|root| root.join("resources/app"));
let bundled = bundled.filter(|app| app.join("product.json").is_file());
// process.ts `cwd()`: cli.rs passes its folder in `VSCODE_CWD`, `open` starts the app in `/`.
let working_dir = match std::env::var_os("VSCODE_CWD") {
Some(cwd) => PathBuf::from(cwd),
None => std::env::current_dir()?,
};
let app_root = bundled.unwrap_or_else(|| std::env::var_os("VSCODE_SRC").map_or_else(|| PathBuf::from(env!("VSCODE_SRC")), PathBuf::from));
product::load(&app_root, product::is_bundled(&app_root));
if product::is_stable() {
config::registry::use_stable_quality();
}
encoding_guess::set_app_root(&app_root);
// code.sh runs the binary with `ELECTRON_RUN_AS_NODE=1` for cli.js.
if std::env::var_os("ELECTRON_RUN_AS_NODE").is_some() {
std::process::exit(cli::main(args, &user_data, &working_dir, &app_root));
}
if args.iter().any(|arg| arg == "--version" || arg == "-v") {
println!("{}", cli::version_message());
return Ok(());
}
let socket = launch::socket_path(&user_data);
if args.iter().any(|arg| arg == "--status" || arg == "-s") {
diagnostics::print_status(&socket);
return Ok(());
}
if launch::send_to_running_instance(&socket, &args, &working_dir) {
return Ok(());
}
let launches = launch::listen(&socket);
let screenshot = flag_value("--screenshot").map(PathBuf::from);
let screenshot_input = flag_value("--screenshot-input").unwrap_or_default();
// Typed before the capture, as port/tools/ref-screenshot types KEYS into the reference.
let screenshot_keys: Vec<Keystroke> = flag_value("--screenshot-keys").unwrap_or_default().split_whitespace().map(parse_keystroke).collect::<Result<_, _>>()?;
// argvHelper.ts `parseMainProcessArgv`: an invalid `--goto` ends the start.
let parsed = match argv::parse_and_validate(&args[1..]) {
Ok((parsed, _)) => parsed,
Err(error) => anyhow::bail!(error),
};
let positional = &parsed.positional;
// windowsMainService.ts keeps the path as given (no realpath), so /var stays /var on macOS; a file path alone
// opens an empty window with the file.
let command_line = workbench::command_line::CommandLine::from_args(&parsed, &working_dir);
let workspace = command_line.workspaces.into_iter().next().map(Workspace::open);
let files = command_line.files;
let development = ExtensionDevelopment::from_args(&args)?;
// An unbundled build gets no `open-url` event: `--open-url <url>` hands the url in.
let open_url = flag_value("--open-url");
let shell_env_error = apply_shell_env(args.iter().any(|arg| arg == "--force-disable-user-env"), &user_data);
// main.ts: `--export-default-keybindings [folder]`, a folder relative to the working directory, else `<appRoot>/doc`.
// keybindingsExport.contribution.ts ignores it on a stable build.
let export_default_keybindings = (args.iter().any(|arg| arg == "--export-default-keybindings") && !product::is_stable()).then(|| {
flag_value("--export-default-keybindings").filter(|folder| !folder.starts_with("--")).map_or_else(|| app_root.join("doc"), |folder| working_dir.join(folder))
});
// Before any scan: the display language decides the manifests' messages.
let home = home_dir().unwrap_or_default();
let locale = nls::user_locale(flag_value("--locale").as_deref(), &output::log_levels::argv_file(&home));
perf::mark("code/willGenerateNls");
let resolved = exthost::language_packs::resolve_nls(&user_data, &locale);
nls::init(&resolved);
exthost::language_packs::set_nls(&user_data, resolved);
perf::mark("code/didGenerateNls");
perf::mark("code/willLoadExtensions");
let builtins = scan_system_extensions(&app_root)?;
perf::mark("code/didScanExtensions");
// Artur: user extensions live in ~/.vsrustium/extensions, the default user data dir's extensions folder.
let extensions_folder = flag_value("--extensions-dir").map_or_else(|| user_data.join("extensions"), PathBuf::from);
configure_unc_access(&user_data, &extensions_folder);
// code/electron-main/main.ts `initServices` makes the extensions folder; the extensions watcher watches it.
std::fs::create_dir_all(&extensions_folder)?;
UserExtensions::new(extensions_folder.clone(), &VERSION).clean_up()?;
// storageMainService.ts: no storage during extension tests, so each test run starts empty.
let extension_tests = development.as_ref().is_some_and(|development| development.tests_path.is_some());
let shared_storage = match extension_tests {
true => Arc::new(Mutex::new(storage::Storage::in_memory())),
false => Arc::new(Mutex::new(open_shared_storage(flag_value("--shared-data-dir").map(PathBuf::from))?)),
};
let cli_profile = CliProfile::from_args(&args, std::env::var("VSCODE_CLI").is_ok_and(|cli| cli == "1"));
// app.ts: a start with a forced profile opens only its new empty window.
let restores = !(development.is_some() || cli_profile.is_forced() || screenshot.is_some() || export_default_keybindings.is_some() || open_url.is_some());
let app = AppState { args: args.clone(), runtime, user_data, app_root, builtins, user_extensions_folder: extensions_folder, shared_storage };
let startup = WindowRequest { workspace, files, development, host_debug: ExtensionHostDebug::from_args(&args), open_url, screenshot, screenshot_keys, screenshot_input, export_default_keybindings, profile: cli_profile, ..WindowRequest::default() };
let application = application();
// A click on the Dock icon without a window opens an empty one, as `app.on('activate')` does in app.ts.
application.on_reopen(|cx| {
if cx.windows().is_empty() {
open_window_or_log(WindowRequest::default(), cx);
}
});
// app.ts `open-url` and `open-file`: the bundle's CFBundleURLTypes route `code-oss://` urls here, its
// CFBundleDocumentTypes the files and folders opened from Finder or dropped on the Dock as `file://` urls.
let (url_sender, mut urls) = futures::channel::mpsc::unbounded::<Vec<String>>();
application.on_open_urls(move |opened| drop(url_sender.unbounded_send(opened)));
let no_cli_paths = positional.is_empty();
application.run(move |cx: &mut App| {
perf::mark("code/mainAppReady");
workbench::accessibility::watch_assistive_apps(cx);
#[cfg(target_os = "linux")]
webview::pump_gtk(cx);
// app.ts `macOpenFiles`: AppKit sends the launch's documents before `applicationDidFinishLaunching:`; they take the
// startup window's place and open from the task, as effects deferred from this callback never run.
let launch_urls: Vec<Vec<String>> = std::iter::from_fn(|| urls.try_recv().ok()).collect();
let opens_documents = no_cli_paths && launch_urls.iter().flatten().any(|url| url.starts_with("file:"));
let exact_restore = windows_state::take_exact_restore(&app.user_data);
let mut restored = match restores {
true => last_session_windows(&app.user_data, !no_cli_paths, opens_documents),
false => Vec::new(),
};
// windowsMainService.ts `openInBrowserWindow`: a window comes back minimized only in an exact restore.
for ui in restored.iter_mut().filter_map(|window| window.ui.as_mut()) {
ui.minimized &= exact_restore.is_some();
}
let opens_startup = !opens_documents && (!no_cli_paths || restored.is_empty());
cx.spawn(async move |cx| {
let mut opened_urls = futures::StreamExt::chain(futures::stream::iter(launch_urls), urls);
while let Some(opened) = futures::StreamExt::next(&mut opened_urls).await {
let opened = workbench::url_handler::with_following_documents(opened, &mut opened_urls, cx).await;
cx.update(|cx| workbench::url_handler::open_system_urls(opened, cx));
}
})
.detach();
cx.set_global(user_data_profile::UserDataProfilesService::load(&app.user_data, &app.user_extensions_folder));
cx.set_global(app);
for window in restored {
let workspace = window.workspace.clone().or(window.folder.clone()).map(Workspace::open);
open_window_or_log(WindowRequest { workspace, backup_folder: window.backup_path, ui: window.ui, ..WindowRequest::default() }, cx);
}
if opens_startup && let Err(error) = open_window(startup, cx) {
eprintln!("{error:#}");
std::process::exit(1);
}
// app.ts `resolveShellEnvironment(..., notifyOnError: true)` once the first window opened: to the focused one.
if let Some(message) = shell_env_error
&& let Some(handle) = cx.window_stack().unwrap_or_else(|| cx.windows()).into_iter().find_map(|handle| handle.downcast::<Workbench>())
{
let _ = handle.update(cx, |workbench, window, cx| workbench.show_resolve_shell_env_error(message, window, cx));
}
workbench::menubar::install(cx);
if let Some(launches) = launches {
launch::handle_launches(launches, cx);
}
// windowsMainService.ts `open`: an exact restore of a hidden app hides it again.
if exact_restore.is_some_and(|exact| exact.hide_application) {
cx.hide();
} else {
cx.activate(true);
}
});
Ok(())
}
/// What every window shares: the command line, the folders, the built-in extensions scanned at startup and the
/// application storage.
pub(crate) struct AppState {
args: Vec<String>,
runtime: Runtime,
pub user_data: PathBuf,
app_root: PathBuf,
builtins: Vec<ScannedExtension>,
user_extensions_folder: PathBuf,
shared_storage: Arc<Mutex<storage::Storage>>,
}
impl gpui::Global for AppState {}
/// A window to open: its folder or workspace and file; the first window also takes the command line's extension
/// development, URL, capture and export flags.
#[derive(Default)]
pub(crate) struct WindowRequest {
pub workspace: Option<Workspace>,
pub files: workbench::command_line::FilesToOpen,
pub development: Option<ExtensionDevelopment>,
pub host_debug: ExtensionHostDebug,
open_url: Option<String>,
screenshot: Option<PathBuf>,
screenshot_keys: Vec<Keystroke>,
screenshot_input: String,
export_default_keybindings: Option<PathBuf>,
/// The empty window backup folder of a restored window.
pub backup_folder: Option<PathBuf>,
/// The size, place and mode of a restored window.
pub ui: Option<windows_state::UiState>,
pub profile: CliProfile,
}
/// `--profile <name>` and `--profile-temp`: windowsMainService.ts `forceProfile` and `forceTempProfile`, given only
/// to the windows a command line opens, never to the ones opened later from the menu. With what the window's
/// `config` tells unattendedRestartScheduler.ts `getWindowBlockers` of that command line.
#[derive(Default, Clone)]
pub(crate) struct CliProfile {
pub name: Option<String>,
pub temp: bool,
/// `hasSessionArguments(window.config)`.
pub session_arguments: bool,
/// `isLaunchedFromCli(window.config.userEnv)`.
pub launched_from_cli: bool,
}
impl CliProfile {
/// `args` with the program first, as `std::env::args`.
pub fn from_args(args: &[String], launched_from_cli: bool) -> CliProfile {
let name = args.iter().position(|arg| arg == "--profile").and_then(|i| args.get(i + 1)).cloned();
let parsed = argv::parse_and_validate(args.get(1..).unwrap_or_default()).map(|(parsed, _)| parsed).unwrap_or_default();
let session_arguments = workbench::unattended_restart::SESSION_ARGUMENTS.iter().any(|id| parsed.flag(id));
CliProfile { name, temp: args.iter().any(|arg| arg == "--profile-temp"), session_arguments, launched_from_cli }
}
pub fn is_forced(&self) -> bool {
self.name.is_some() || self.temp
}
}
/// `open_window` from a window's command: a failure is logged, the other windows stay.
pub(crate) fn open_window_or_log(request: WindowRequest, cx: &mut App) {
if let Err(error) = open_window(request, cx) {
eprintln!("[windows] opening a window: {error:#}");
}
}
/// windowsMainService.ts `openInBrowserWindow`: a window with its own settings, storage, trust, extension host and
/// workbench, as each reference window has.
pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Result<gpui::WindowHandle<Workbench>> {
let WindowRequest { workspace, files, development, host_debug, open_url, screenshot, screenshot_keys, screenshot_input, export_default_keybindings, backup_folder, ui, profile: cli_profile } = request;
let app = cx.global::<AppState>();
let (args, runtime, user_data, app_root, builtins, shared_storage) = (app.args.clone(), app.runtime, app.user_data.clone(), app.app_root.clone(), app.builtins.clone(), app.shared_storage.clone());
let flag_value = |flag: &str| args.iter().position(|arg| arg == flag).and_then(|i| args.get(i + 1)).cloned();
let user_extensions_folder = app.user_extensions_folder.clone();
let (profile, default_profile, profiles_home) = cx.update_global(|service: &mut user_data_profile::UserDataProfilesService, _| {
let profile = service.resolve(workspace.as_ref(), cli_profile.name.as_deref(), cli_profile.temp, development.is_some());
(profile, service.profiles.default_profile().clone(), service.profiles.profiles_home.clone())
});
let user_extensions = UserExtensions { extensions_file: profile.current.extensions_resource.clone(), profiles_home: Some(profiles_home), ..UserExtensions::new(user_extensions_folder, &VERSION) };
let mut extensions = builtins.clone();
add_user_extensions(&mut extensions, user_extensions.scan()?);
if let Some(development) = &development {
development.add_extension(&mut extensions)?;
}
let proposed_api = exthost::proposed_api::ProposedApi::new(
&exthost::proposed_api::Environment {
is_built: product::is_bundled(&app_root),
is_extension_development: development.is_some(),
quality: product::quality(),
enabled_proposed_api: exthost::proposed_api::enabled_proposed_api(&args),
},
product::get("extensionEnabledApiProposals"),
);
proposed_api.update_enabled_api_proposals(&mut extensions);
let extension_tests = development.as_ref().is_some_and(|development| development.tests_path.is_some());
perf::mark("code/willInitStorage");
let storage = match extension_tests {
true => MainThreadStorage::in_memory(),
false => MainThreadStorage::open(&SessionPaths { app_root: &app_root, user_data: &user_data, workspace: workspace.as_ref() }, &profile.current.global_storage_home)?,
};
let application_storage = match extension_tests || profile.current.is_default {
true => storage.profile.clone(),
false => {
let home = &default_profile.global_storage_home;
std::fs::create_dir_all(home)?;
Arc::new(Mutex::new(storage::Storage::open(&home.join("state.vscdb"))))
}
};
perf::mark("code/didInitStorage");
// The extensions the user disabled stay out of the host and the registries (extensionEnablementService.ts).
let developed: Vec<String> = extensions.iter().filter(|extension| extension.description["isUnderDevelopment"] == true).map(|extension| extension.id.clone()).collect();
let installed = extensions.clone();
// Read before locking storage.profile: for the default profile application_storage is the same mutex.
let bisect = workbench::extension_bisect::BisectState::read(&application_storage.lock().unwrap());
let disabled = {
let mut profile = storage.profile.lock().unwrap();
let mut workspace_storage = storage.workspace.lock().unwrap();
workbench::extensions_view::disabled_at_startup(&installed, &mut profile, workspace.is_some().then_some(&mut *workspace_storage), &developed, bisect.as_ref())
};
extensions.retain(|extension| !disabled.contains(&extension.id));
let load_settings = |extensions: &[ScannedExtension]| {
let described: Vec<(&str, &serde_json::Value)> = extensions.iter().map(|extension| (extension.id.as_str(), &extension.description)).collect();
let mut settings = Settings::load_with_profile(Registry::with_extensions(&described), user_data.join("User"), user_data_profile::user_files(&profile.current, &default_profile), workspace.clone());
settings.set_policy_values(policy::read_native_policies(&settings.registry, policy::BUNDLE_IDENTIFIER));
settings
};
perf::mark("code/willInitWorkspaceService");
let mut settings = load_settings(&extensions);
perf::mark("code/didInitWorkspaceService");
let setting = |key: &str| settings.get_value(Some(key), &Overrides::default());
let new_window_dimensions = setting("window.newWindowDimensions").and_then(|value| value.as_str().map(str::to_owned)).unwrap_or_default();
// windowsMainService.ts: `--skip-add-to-recently-opened` (cli.ts sets it for the stdin file) keeps them out.
if !args.iter().any(|arg| arg == "--skip-add-to-recently-opened") {
add_recently_opened(&mut shared_storage.lock().unwrap(), workspace.as_ref(), files.open.iter().map(|file| file.path.as_path()));
}
let workspace_trust = workspace_trust::WorkspaceTrust::new(shared_storage.clone(), workspace_trust::Startup {
// workspaceTrust.ts isWorkspaceTrustEnabled: only an explicit false turns the setting off.
enabled: !args.iter().any(|arg| arg == "--disable-workspace-trust") && setting("security.workspace.trust.enabled") != Some(json!(false)),
workspace: workspace.as_ref(),
empty_window_trusted: setting("security.workspace.trust.emptyWindow") == Some(json!(true)),
workspace_storage: &mut storage.workspace.lock().unwrap(),
});
if !workspace_trust.is_trusted() {
let configured = setting("extensions.supportUntrustedWorkspaces").unwrap_or_default();
let count = extensions.len();
extensions.retain(|extension| !workspace_trust::disabled_when_untrusted(extension, workspace.as_ref(), &configured));
if extensions.len() != count {
settings = load_settings(&extensions);
}
settings.update_workspace_trust(false);
}
let theme = match flag_value("--theme") {
Some(theme_id) => load_theme(&extensions, &theme_id)?,
None => settings_theme(&extensions, &settings, cx)?,
};
let file_icons = settings_file_icons(&extensions, &settings)?;
let color_themes = theme::color_themes(&extensions)?;
let settings = Arc::new(Mutex::new(settings));
let keybindings_file = profile.current.keybindings_resource.clone();
// Same size as the reference capture in port/tools/ref-screenshot, so pixel diffs line up.
let mut bounds = Bounds::centered(None, size(px(1024.), px(768.)), cx);
// A half-point origin (an odd display height, e.g. 1650 px over screen sharing) makes the drawable 1 point taller.
bounds.origin = point(bounds.origin.x.round(), bounds.origin.y.round());
let open_windows: Vec<Bounds<gpui::Pixels>> = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).filter_map(|handle| handle.update(cx, |_, window, _| window.bounds()).ok()).collect();
let location = windows_state::WindowState {
workspace: workspace.as_ref().and_then(|workspace| workspace.file.clone()),
folder: workspace.as_ref().filter(|workspace| workspace.file.is_none()).map(|workspace| workspace.folders[0].path.clone()),
backup_path: backup_folder.clone(),
ui: None,
};
// Only a restored window of an exact restore asks for it; it must not take focus (windowImpl.ts `applyState`).
let minimized = ui.is_some_and(|ui| ui.minimized);
let ui = ui.or_else(|| windows_state::stored_ui_state(&user_data, &location, open_windows.is_empty(), cx).filter(|_| !extension_tests));
// windowsStateHandler.ts `doGetNewWindowState` for a window without a stored state: `window.newWindowDimensions`.
let last_active = cx.window_stack().unwrap_or_else(|| cx.windows()).into_iter().find_map(|handle| handle.downcast::<Workbench>());
let last_active_bounds = last_active.and_then(|handle| handle.update(cx, |_, window, _| window.window_bounds()).ok());
let default_bounds = match (new_window_dimensions.as_str(), last_active_bounds) {
("maximized", _) => WindowBounds::Maximized(bounds),
("fullscreen", _) => WindowBounds::Fullscreen(bounds),
("inherit", Some(inherited)) => inherited,
("offset", Some(WindowBounds::Windowed(inherited))) => WindowBounds::Windowed(windows_state::cascade(inherited, &open_windows)),
("offset", Some(inherited)) => inherited,
_ => WindowBounds::Windowed(windows_state::cascade(bounds, &open_windows)),
};
// The workbench draws its own title bar, as the reference does with window.titleBarStyle custom.
let titlebar = TitlebarOptions { title: None, appears_transparent: true, traffic_light_position: Some(point(px(10.), px(10.))) };
let (display_id, window_bounds) = ui.and_then(|ui| windows_state::window_bounds(ui, cx)).map_or((None, default_bounds), |(display, bounds)| (Some(display), bounds));
// window.ts `WindowMinimumSize`.
let window_min_size = Some(size(px(400.), px(270.)));
let options = WindowOptions { window_bounds: Some(window_bounds), display_id, titlebar: Some(titlebar), app_owns_titlebar_drag: true, window_min_size, app_id: crate::product::linux_desktop_name(), focus: !minimized, ..Default::default() };
perf::mark("code/willOpenNewWindow");
perf::mark("code/willCreateCodeWindow");
let window = {
cx.open_window(options, |window, cx| {
perf::mark("code/willStartWorkbench");
cx.new(|cx| {
let languages = Languages::new(&extensions);
let (host_start, mut host) = HostStart::new(theme.kind, &languages);
host.configuration_scopes = development.is_some();
perf::mark("code/willCreateWorkbenchContributions/1");
let mut workbench = Workbench::new(theme, app_root.clone(), workspace.clone(), languages, settings.clone(), host, cx);
perf::mark("code/didCreateWorkbench");
perf::mark("code/didCreateWorkbenchContributions/2");
cx.observe_window_appearance(window, |workbench, _, cx| workbench.host_color_scheme_changed(cx)).detach();
workbench.sync_app_icon();
workbench.apply_proxy_settings();
let window_logs = exthost::session::window_logs_path(&user_data);
workbench.register_window_log(window_logs.join("renderer.log"));
let home = home_dir().unwrap_or_default();
workbench.start_logs(output::log_levels::argv_file(&home), window_logs.parent().expect("a session folder").to_path_buf(), cx);
workbench.skip_dialogs = development.as_ref().is_some_and(|development| development.tests_path.is_some());
workbench.refresh_keyboard_mapper();
workbench.extension_development = development.is_some();
workbench.development = development.clone();
workbench.extension_host_debug = host_debug.clone();
workbench.proposed_api = proposed_api.clone();
workbench.cli_profile = cli_profile.clone();
workbench.load_keybindings(keybindings::default_keybindings(&extensions), keybindings_file.clone());
workbench.watch_settings_files(window, cx);
workbench.migrate_configurations(cx);
workbench.watch_policies(cx);
workbench.start_file_watcher(cx);
workbench.start_keybindings_watcher(cx);
workbench.start_system_wide_keybindings(window, cx);
workbench.register_update_actions(window, cx);
workbench.set_command_palette_menu(command_palette::menu(&extensions));
workbench.menus.extend(menus::extension_menus(&extensions));
workbench.command_icons = menus::command_icons(&extensions);
workbench.submenu_icons = menus::submenu_icons(&extensions);
workbench.status_entries = main_thread_status_bar::static_entries(&extensions);
workbench.file_icons = file_icons;
workbench.product_icons = product_icons::settings_product_icons(&extensions, &settings.lock().unwrap());
workbench.color_themes = color_themes;
workbench.set_tree_views(&extensions);
extension_point_messages::report(&extensions);
workbench.host.set_running_extensions(&extensions);
workbench.extensions = extensions.clone();
workbench.start_tasks();
if let Some(folder) = &export_default_keybindings {
match workbench.export_default_keybindings(folder) {
Ok(path) => eprintln!("[workbench.contrib.keybindingsExport] Wrote {}", path.display()),
Err(error) => eprintln!("[workbench.contrib.keybindingsExport] Failed to generate default keybindings {error}"),
}
cx.quit();
}
workbench.restore_profile_state(storage.profile.clone(), application_storage);
workbench.restore_workspace_state(storage.workspace.clone());
workbench.workspace_trust = workspace_trust;
workbench.shared_storage = shared_storage;
workbench.watch_recently_opened(window, cx);
workbench.watch_window_focus(window, cx);
workbench.watch_window_close(window, cx);
workbench.set_installed_extensions(builtins.clone(), user_extensions.clone_for_profile(), developed.clone(), cx);
workbench.start_extensions_watcher(cx);
workbench.set_user_data_profiles(profile, cx);
workbench.install_template_extensions(window, cx);
workbench.offer_settings_import(window, cx);
workbench.start_terminal_host();
workbench.watch_editor_focus(window, cx);
workbench.watch_comment_reply_blur(window, cx);
workbench.show_trust_modal_on_start(window, cx);
workbench.restore_notebook_editors(window, cx);
workbench.start_backups(&user_data, backup_folder, window, cx);
perf::mark("code/willRestoreEditors");
let resolver_cache = workbench.take_editor_resolver_cache();
let editors_known = workbench.restore_custom_editors_memento();
if !editors_known {
workbench.set_restored_editor_type_controls();
}
let restores_parts = files.is_empty();
workbench.open_command_line_files(files, Some((&resolver_cache, editors_known)), window, cx);
if restores_parts && workbench.editors.active().is_some() && window.focused(cx).is_none() {
// editorGroupView.ts `restoreEditors`: the active group's restored editor takes the focus unless
// something else took it meanwhile.
window.focus(&workbench.editor_focus, cx);
}
// editorParts.ts `restoreParts`: the editor windows come back when the main part restored its state.
if restores_parts {
workbench.restore_auxiliary_windows(cx);
}
workbench.revive_terminals(window, cx);
workbench.run_startup_page(args.iter().any(|arg| arg == "--skip-welcome"), window, cx);
workbench.show_release_notes_after_update(args.iter().any(|arg| arg == "--skip-release-notes"), window, cx);
perf::set_startup_editors(workbench.visible_editor_ids());
perf::mark("code/didRestoreEditors");
if let Some(url) = &open_url {
workbench.open_protocol_url(url, window, cx);
}
let launch = HostLaunch { process: HostProcess::Runtime(runtime), user_data: user_data.clone() };
workbench.host_launch = Some(launch.clone());
let activated = workbench.spawn_extension_host(host_start, launch, development, window, cx);
if let Some(path) = screenshot {
cx.spawn_in(window, async move |workbench, cx| {
if activated.await.is_err() {
return;
}
// Captured once eager extensions are up, so the frame shows the workbench as the host left it.
cx.background_executor().timer(Duration::from_millis(500)).await;
if !screenshot_keys.is_empty() {
cx.update(|window, cx| {
for keystroke in &screenshot_keys {
window.dispatch_keystroke(keystroke.clone(), cx);
}
})
.ok();
}
for step in screenshot_input.split(';').filter(|step| !step.trim().is_empty()) {
let input = screenshot_step(step).with_context(|| format!("--screenshot-input step {step:?}"));
let dispatched = input.and_then(|input| cx.update(|window, cx| window.dispatch_event(input, cx)));
if let Err(error) = dispatched {
eprintln!("{error:#}");
std::process::exit(1);
}
cx.background_executor().timer(Duration::from_millis(300)).await;
}
// The editor's scrollbars show at open and after a scroll, hide 500ms later and fade out
// over 800ms; ref-screenshot waits the same.
cx.background_executor().timer(Duration::from_millis(1500)).await;
// The capture reads the last frame: draw one now without the input carets.
workbench.update(cx, |workbench, _| workbench.input_carets_hidden = true).ok();
cx.update(|window, _| window.refresh()).ok();
cx.background_executor().timer(Duration::from_millis(100)).await;
let saved = cx.update(|window, _| save_screenshot(window, &path)).and_then(|result| result);
if let Err(error) = saved {
eprintln!("screenshot failed: {error:#}");
std::process::exit(1);
}
cx.update(|_, cx| cx.quit()).ok();
})
.detach();
}
perf::mark("code/didStartWorkbench");
workbench.restored_at = Some(std::time::Instant::now());
workbench
})
})?
};
if minimized {
window.update(cx, |_, window, _| window.minimize_window())?;
}
perf::mark("code/didCreateCodeWindow");
Ok(window)
}
/// package.json `version`, with `-<quality>` on a build that is not stable (`insider`), as gulpfile.vscode.ts writes it.
static VERSION: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| version_for_quality(product::quality()));
fn version_for_quality(quality: Option<&str>) -> String {
match quality {
Some(quality) if quality != "stable" => format!("1.148.0-{quality}"),
_ => "1.148.0".to_owned(),
}
}
/// The OS whose key conventions gpui-fast's keystroke parsing and printing take, before an `App` exists.
fn host_os() -> gpui::OperatingSystem {
match () {
_ if cfg!(target_os = "macos") => gpui::OperatingSystem::Mac,
_ if cfg!(target_os = "windows") => gpui::OperatingSystem::Windows,
_ => gpui::OperatingSystem::Linux,
}
}
/// Wu's `Keystroke::parse`, which took `secondary-` as cmd on macOS and ctrl elsewhere.
fn parse_keystroke(source: &str) -> Result<Keystroke, gpui::InvalidKeystrokeError> {
Keystroke::parse_with_os(source, host_os())
}
/// A step of `--screenshot-input`: `right X Y` (a right click), `move X Y` or `key KEYSTROKE`, in window points.
fn screenshot_step(step: &str) -> anyhow::Result<gpui::PlatformInput> {
let parts: Vec<&str> = step.split_whitespace().collect();
let position = || -> anyhow::Result<gpui::Point<gpui::Pixels>> { Ok(point(px(parts.get(1).context("no x")?.parse()?), px(parts.get(2).context("no y")?.parse()?))) };
let modifiers = gpui::Modifiers::default();
Ok(match parts[0] {
"right" => gpui::PlatformInput::MouseDown(gpui::MouseDownEvent { button: gpui::MouseButton::Right, position: position()?, modifiers, click_count: 1, first_mouse: false }),
"move" => gpui::PlatformInput::MouseMove(gpui::MouseMoveEvent { position: position()?, pressed_button: None, modifiers }),
"key" => gpui::PlatformInput::KeyDown(gpui::KeyDownEvent { keystroke: parse_keystroke(parts.get(1).context("no key")?)?, is_held: false, prefer_character_input: false }),
other => anyhow::bail!("unknown step {other}"),
})
}
/// Reads the last rendered frame back from Metal, so capture needs no Screen Recording permission.
#[cfg(feature = "screenshot")]
fn save_screenshot(window: &Window, path: &std::path::Path) -> anyhow::Result<()> {
window.render_to_image()?.save(path)?;
Ok(())
}
#[cfg(not(feature = "screenshot"))]
fn save_screenshot(_window: &Window, _path: &std::path::Path) -> anyhow::Result<()> {
anyhow::bail!("built without the screenshot feature: cargo gc build --features screenshot")
}
/// The color theme setting for the host scheme (`getColorThemeSettingId`); a theme no extension contributes falls back to the default, as ThemeService does.
fn settings_theme(extensions: &[ScannedExtension], settings: &Settings, cx: &App) -> anyhow::Result<theme::Theme> {
let key = workbench::themes::color_theme_setting_id(settings, workbench::themes::host_color_scheme(cx));
let id = settings.get_value(Some(key), &Overrides::default());
if let Some(theme) = id.as_ref().and_then(|id| id.as_str()).and_then(|id| load_theme(extensions, id).ok()) {
return Ok(theme);
}
let default = &settings.registry.property(key).expect("the color theme settings are registered").default;
load_theme(extensions, default.as_str().expect("the default theme is a settings id"))
}
/// workbenchThemeService.ts `initializeFileIconTheme`: `null` is the built-in "no icons" theme, an unknown id the default.
fn settings_file_icons(extensions: &[ScannedExtension], settings: &Settings) -> anyhow::Result<Option<file_icons::FileIconTheme>> {
let id = settings.get_value(Some("workbench.iconTheme"), &Overrides::default());
let id = match id {
Some(serde_json::Value::Null) => return Ok(None),
Some(serde_json::Value::String(id)) => id,
_ => file_icons::DEFAULT_ICON_THEME.to_string(),
};
let theme = file_icons::FileIconTheme::load(extensions, &id).or_else(|_| file_icons::FileIconTheme::load(extensions, file_icons::DEFAULT_ICON_THEME))?;
Ok(Some(theme))
}
#[cfg(test)]
fn default_settings() -> Arc<Mutex<Settings>> {
Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), PathBuf::from("/nonexistent/User"), None)))
}
/// The running test's name, for a temporary folder of its own: tests run in parallel threads named after them, and
/// one that removes or rewrites a folder another test has open breaks it.
#[cfg(test)]
fn test_name() -> String {
std::thread::current().name().unwrap_or("main").replace("::", "-")
}
#[test]
fn icon_theme_follows_workbench_icon_theme() {
let extensions = scan_builtin_extensions(&PathBuf::from(env!("VSCODE_SRC")).join("extensions")).unwrap();
let user_home = std::env::temp_dir().join(format!("code-gpui-icon-theme-{}", std::process::id()));
std::fs::create_dir_all(&user_home).unwrap();
let icons_with = |settings_json: &str| {
std::fs::write(user_home.join("settings.json"), settings_json).unwrap();
let settings = Settings::load(Registry::with_extensions(&[]), user_home.clone(), None);
settings_file_icons(&extensions, &settings).unwrap().is_some()
};
assert!(icons_with("{}"));
assert!(!icons_with(r#"{ "workbench.iconTheme": null }"#));
assert!(icons_with(r#"{ "workbench.iconTheme": "no-such-theme" }"#));
std::fs::remove_dir_all(&user_home).unwrap();
}
/// windowsMainService.ts `getPathsToOpen` at startup: the last session's windows open for a start without paths, and
/// next to the command line's paths or the documents Finder hands the app with `window.restoreWindows` `preserve`.
fn last_session_windows(user_data: &Path, cli_paths: bool, opens_documents: bool) -> Vec<windows_state::WindowState> {
let user_settings = Settings::load(Registry::with_extensions(&[]), user_data.join("User"), None);
let setting = user_settings.get_value(Some("window.restoreWindows"), &Overrides::default()).and_then(|value| value.as_str().map(str::to_owned)).unwrap_or_else(|| "all".into());
if (cli_paths || opens_documents) && setting != "preserve" {
return Vec::new();
}
let restore_fullscreen = user_settings.get_value(Some("window.restoreFullscreen"), &Overrides::default()) == Some(json!(true));
let (last_active, opened) = windows_state::load(user_data);
let mut windows = windows_state::to_restore(&setting, last_active, opened);
// windowsStateHandler.ts `getNewWindowState`: fullscreen comes back only with `window.restoreFullscreen`.
for ui in windows.iter_mut().filter_map(|window| window.ui.as_mut()).filter(|ui| ui.mode == windows_state::FULLSCREEN && !restore_fullscreen) {
ui.mode = windows_state::NORMAL;
}
windows
}
#[test]
fn a_finder_launch_restores_the_last_session_only_with_preserve() {
let user_data = std::env::temp_dir().join(format!("vsrustium-finder-launch-{}", std::process::id()));
// The `fsPath` the stored folder URI reads back as: a lower-case drive letter on Windows.
let user_data = PathBuf::from(uri::Uri::file(&user_data.to_string_lossy()).fs_path());
let _ = std::fs::remove_dir_all(&user_data);
std::fs::create_dir_all(user_data.join("User/globalStorage")).unwrap();
std::fs::create_dir_all(user_data.join("folder")).unwrap();
let folder = windows_state::WindowState { folder: Some(user_data.join("folder")), ..Default::default() };
windows_state::save(&user_data, Some(&folder), &[], None);
let restored_with = |setting: &str| {
std::fs::write(user_data.join("User/settings.json"), format!(r#"{{ "window.restoreWindows": "{setting}" }}"#)).unwrap();
last_session_windows(&user_data, false, true)
};
assert_eq!(restored_with("preserve"), [folder]);
assert_eq!(restored_with("all"), []);
std::fs::remove_dir_all(&user_data).unwrap();
}
/// windowsMainService.ts `open` with `addRecentlyOpened`: the window's folder or workspace and its file.
fn add_recently_opened<'a>(shared: &mut storage::Storage, workspace: Option<&Workspace>, files: impl Iterator<Item = &'a Path>) {
let mut opened = Vec::new();
// workspacesHistoryMainService.ts: untitled workspaces are not remembered.
if let Some(workspace) = workspace.filter(|workspace| !workspace.file.as_deref().is_some_and(config::workspace::is_untitled_workspace)) {
opened.push(match &workspace.file {
Some(file) => recently_opened::entry(recently_opened::Kind::Workspace, file, None),
None => recently_opened::entry(recently_opened::Kind::Folder, &workspace.folders[0].path, None),
});
}
opened.extend(files.map(|file| recently_opened::entry(recently_opened::Kind::File, file, None)));
if !opened.is_empty() {
recently_opened::add(shared, opened);
}
}
/// The APPLICATION_SHARED storage, `sharedStorage/state.vscdb` in `--shared-data-dir`, else in
/// `~/.vscode-gpui-shared` as the reference keeps it in `~/<sharedDataFolderName>`.
fn open_shared_storage(shared_data: Option<PathBuf>) -> anyhow::Result<storage::Storage> {
let shared_data = match shared_data {
Some(dir) => dir,
None => home_dir().context("HOME or USERPROFILE is not set")?.join(".vscode-gpui-shared"),
};
let dir = shared_data.join("sharedStorage");
std::fs::create_dir_all(&dir)?;
Ok(storage::Storage::open(&dir.join("state.vscdb")))
}
/// app.ts "UNC Host Allowlist" from the user's settings, and main.ts `allowWindowsUNCPath` of the extensions folder.
fn configure_unc_access(user_data: &Path, extensions_folder: &Path) {
let user_settings = Settings::load(Registry::with_extensions(&[]), user_data.join("User"), None);
let setting = |key: &str| user_settings.get_value(Some(key), &Overrides::default());
if setting("security.restrictUNCAccess") == Some(json!(false)) {
files::unc::disable_unc_access_restrictions();
} else {
files::unc::add_unc_hosts_to_allowlist(&setting("security.allowedUNCHosts").unwrap_or_default());
}
if let Some(host) = files::unc::unc_host(&extensions_folder.to_string_lossy()) {
files::unc::add_unc_host_to_allowlist(host);
}
}
/// main.ts `resolveShellEnv` merged into `process.env`: a Dock launch gets the login shell's PATH for the host,
/// terminals and tasks. Runs before the host and the UI start.
#[cfg(unix)]
fn apply_shell_env(force_disable: bool, user_data: &Path) -> Option<String> {
let env: std::collections::HashMap<String, String> = std::env::vars_os().filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?))).collect();
let user_settings = Settings::load(Registry::with_extensions(&[]), user_data.join("User"), None);
let timeout = shell_env::resolution_timeout(user_settings.get_value(Some("application.shellEnvironmentResolutionTimeout"), &Overrides::default()));
match shell_env::resolve_shell_env(&env, force_disable, timeout) {
Some(Ok(resolved)) => {
for (key, value) in resolved {
// SAFETY: the host and the UI start later; the one other thread, `launch` (launch::listen), reads no environment variable.
unsafe { std::env::set_var(key, value) };
}
None
}
Some(Err(message)) => {
eprintln!("[shellEnv] {message}");
Some(message)
}
None => None,
}
}
/// shellEnv.ts `getResolvedShellEnv` skips Windows: the process environment stays as it is.
#[cfg(windows)]
fn apply_shell_env(_force_disable: bool, _user_data: &Path) -> Option<String> {
None
}
/// The built-in extensions: `VSCODE_GPUI_EXTENSIONS` (a checkout's set) or `<app root>/extensions`, then the dev
/// system extensions and, run from a checkout, the port's own (port/extensions, which a package copies into `extensions`).
pub(crate) fn scan_system_extensions(app_root: &Path) -> anyhow::Result<Vec<ScannedExtension>> {
let extensions_dir = std::env::var_os("VSCODE_GPUI_EXTENSIONS").map(PathBuf::from).unwrap_or_else(|| app_root.join("extensions"));
let mut extensions = scan_builtin_extensions(&extensions_dir)?;
let lists = ["builtInExtensions", "portBuiltInExtensions"].map(|key| product::get(key).as_array().into_iter().flatten());
let names = lists.into_iter().flatten().filter_map(|extension| extension["name"].as_str());
extensions.extend(exthost::scan::scan_dev_system_extensions(app_root, names)?);
if !product::is_bundled(app_root) {
extensions.extend(scan_builtin_extensions(Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../port/extensions")))?);
}
Ok(extensions)
}
#[test]
fn a_checkout_run_scans_the_port_extensions() {
let ids: Vec<String> = scan_system_extensions(Path::new(env!("VSCODE_SRC"))).unwrap().into_iter().map(|extension| extension.id).collect();
assert!(ids.iter().any(|id| id == "vsrustium.apache") && ids.iter().any(|id| id == "vsrustium.dotenv-intellisense"), "{ids:?}");
}
/// `os.homedir()`: a Windows session started from Explorer has `USERPROFILE` but no `HOME`.
pub(crate) fn home_dir() -> Option<PathBuf> {
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
}
fn default_user_data() -> anyhow::Result<PathBuf> {
let home = home_dir().ok_or_else(|| anyhow::anyhow!("HOME or USERPROFILE is not set"))?;
// Artur: all user data lives in ~/.vsrustium, product.json `dataFolderName`.
let dir = home.join(".vsrustium");
std::fs::create_dir_all(&dir)?;
Ok(dir)
}