Visual Studio Code, rebuilt in Rust
Rust
//! workbench/services/host (hostService.ts, nativeHostService.ts, windowsMainService.ts): new windows, the window of
//! a folder or file, `reload`, a workspace replacing this window's, switching windows, and the window's extension host
//! ending with it.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use exthost::Waker;
use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};
use futures::channel::oneshot;
use gpui::{App, Context, Window, WindowHandle};
#[cfg(target_os = "macos")]
use objc2_app_kit::{NSFloatingWindowLevel, NSNormalWindowLevel};
#[cfg(target_os = "macos")]
use objc2_foundation::NSString;
use serde_json::Value;
use super::Workbench;
use super::command_line::{CommandLine, FileToOpen, FilesToOpen};
use super::lifecycle::ShutdownReason;
use super::workspace_actions::Openable;
use crate::commands::Outcome;
use crate::main_thread_quick_open::Owner;
use crate::quick_input::{Button, Entry, Event, Item, Kind, QuickInput};
use crate::{CliProfile, WindowRequest, open_window_or_log};
impl Workbench {
pub(super) fn register_host_commands(&mut self) {
self.commands.register("workbench.action.reloadWindow", |workbench, _, window, cx| {
let folder = workbench.workspace_location();
workbench.relaunch(ShutdownReason::Reload, folder, FilesToOpen::default(), window, cx)
});
// windowActions.ts `NewWindowAction` (Shift+Cmd+N): an empty window.
self.commands.register("workbench.action.newWindow", |_, _, _, cx| {
open_new_window(None, cx);
Outcome::done()
});
// windowActions.ts `ToggleFullScreenAction` (Ctrl+Cmd+F, View > Appearance > Full Screen).
self.commands.register("workbench.action.toggleFullScreen", |_, _, window, _| {
window.toggle_fullscreen();
Outcome::done()
});
// electron-browser windowActions.ts `ToggleWindowAlwaysOnTopAction`: Electron's floating window level.
self.commands.register("workbench.action.toggleWindowAlwaysOnTop", |_, _, window, _| {
set_always_on_top(window, !is_always_on_top(window));
Outcome::done()
});
// `EnableWindowAlwaysOnTopAction` and `DisableWindowAlwaysOnTopAction`, an editor window's title actions.
for (id, on_top) in [("workbench.action.enableWindowAlwaysOnTop", true), ("workbench.action.disableWindowAlwaysOnTop", false)] {
self.commands.register(id, move |_, _, window, _| {
set_always_on_top(window, on_top);
Outcome::done()
});
}
self.commands.register("workbench.action.switchWindow", |workbench, _, window, cx| {
workbench.show_switch_window(window, cx);
Outcome::done()
});
self.commands.register("workbench.action.quickSwitchWindow", |workbench, _, window, cx| {
workbench.show_switch_window(window, cx);
Outcome::done()
});
}
/// contextkeys.ts `IsMainWindowFullscreenContext`.
pub(super) fn host_context(&self, window: &Window, context: &mut std::collections::HashMap<String, Value>) {
context.insert("isFullscreen".into(), Value::Bool(window.is_fullscreen()));
context.insert("isWindowAlwaysOnTop".into(), Value::Bool(is_always_on_top(window)));
}
/// window.ts `vscode:showResolveShellEnvError`: the error of resolving the login shell's environment at startup.
pub fn show_resolve_shell_env_error(&mut self, message: String, window: &mut Window, cx: &mut Context<Self>) {
let reply = self.prompt_notification(crate::notifications::Severity::Error, message, &["Restart", "Configure", "Learn More"]);
cx.spawn_in(window, async move |workbench, cx| {
let Ok(Ok(choice)) = reply.await else { return };
let _ = workbench.update_in(cx, |workbench, window, cx| match choice.as_u64() {
Some(0) => super::relauncher::relaunch(cx),
Some(1) => drop(workbench.execute_command("workbench.action.openSettings", vec![serde_json::json!({ "query": "application.shellEnvironmentResolutionTimeout" })], window, cx)),
Some(2) => cx.open_url("https://go.microsoft.com/fwlink/?linkid=2149667"),
_ => {}
});
})
.detach();
}
/// The window's extension host session ends once the workbench is released (its window closed); `ended` answers
/// when the session thread is done with the window's storage.
pub fn watch_session_end(&mut self, closed: Arc<AtomicBool>, waker: Waker, ended: oneshot::Receiver<()>, cx: &mut Context<Self>) {
cx.on_release(move |_, _| {
closed.store(true, Ordering::Relaxed);
waker.wake();
})
.detach();
self.lifecycle.session_ended = Some(ended);
}
/// `reload` and opening a workspace in this window: after the shutdown vetoes this window closes, and once its
/// session let go of the workspace storage a window opens on `folder` (a folder or workspace file) in the same
/// place, as the reference renderer loads again in its BrowserWindow, with the command line's `files`. A reloaded
/// empty window keeps its backups.
pub(super) fn relaunch(&mut self, reason: ShutdownReason, folder: Option<PathBuf>, files: FilesToOpen, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
self.shutdown(reason, window, cx, move |workbench, window, cx| {
let ended = workbench.lifecycle.session_ended.take();
let backup_folder = workbench.lifecycle.backups.home.clone().filter(|_| reason == ShutdownReason::Reload && folder.is_none());
// A reload keeps the window's command line profile, or its transient one; another folder in this window
// resolves its own.
let transient = workbench.user_data_profiles.state.as_ref().map(|state| &state.current).filter(|current| current.is_transient);
let profile = match (reason == ShutdownReason::Reload, transient) {
(true, Some(current)) => CliProfile { name: Some(current.name.clone()), temp: false, ..workbench.cli_profile.clone() },
(true, None) => workbench.cli_profile.clone(),
(false, _) => Default::default(),
};
workbench.user_data_profiles.reloading = reason == ShutdownReason::Reload;
// windowImpl.ts `reload`: an extension development window stays one, with its debug flags.
let (development, host_debug) = match reason == ShutdownReason::Reload {
true => (workbench.development.clone(), workbench.extension_host_debug.clone()),
false => Default::default(),
};
let request = WindowRequest { workspace: folder.map(config::workspace::Workspace::open), backup_folder, ui: Some(crate::windows_state::ui_state(window, cx)), profile, files, development, host_debug, ..WindowRequest::default() };
workbench.lifecycle.window_closed = true;
workbench.delete_wait_markers();
workbench.remove_auxiliary_windows(cx);
window.remove_window();
cx.spawn(async move |_, cx| {
if let Some(ended) = ended {
let _ = ended.await;
}
let _ = cx.update(|cx| open_window_or_log(request, cx));
})
.detach();
});
Outcome::done()
}
/// The window's title on its NSWindow, as Electron sets the document title on the BrowserWindow: the Window menu
/// and the window switcher show it.
/// window.ts `updateDocumentEdited` and `updateRepresentedFilename` on macOS too: the close button's dot while
/// a working copy is dirty, and the active editor's file as the window's represented file.
pub(super) fn sync_window_title(&mut self, window: &mut Window) {
let title = self.window_title();
if self.lifecycle.title != title {
window.set_window_title(&title);
self.lifecycle.title = title;
}
let edited = self.editors.all_editors().any(|editor| editor.is_dirty());
let represented = self.editors.active().filter(|editor| editor.document().scheme == "file").map(|editor| editor.document().path.clone());
if self.lifecycle.document_edited == edited && self.lifecycle.represented_filename == represented {
return;
}
#[cfg(target_os = "macos")]
if let Some(ns_window) = crate::dialog::app_kit_window(window) {
ns_window.setDocumentEdited(edited);
ns_window.setRepresentedFilename(&NSString::from_str(&represented.as_deref().map(|path| path.to_string_lossy()).unwrap_or_default()));
}
self.lifecycle.document_edited = edited;
self.lifecycle.represented_filename = represented;
}
/// windowActions.ts `BaseSwitchWindow`: the open windows by title with their file's icon, this one described as the
/// current window, the next one active; the picked one comes to the front and each row's button closes its window.
fn show_switch_window(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let current = window.window_handle().window_id();
let mut windows: Vec<WindowHandle<Workbench>> = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>()).collect();
windows.sort_by_key(|handle| handle.window_id().as_u64());
let mut entries = Vec::new();
let mut active = 0;
for (index, handle) in windows.iter().enumerate() {
let is_current = handle.window_id() == current;
let (title, filename, dirty) = match is_current {
true => (self.window_title(), self.lifecycle.represented_filename.clone(), self.lifecycle.document_edited),
false => handle.read(cx).map(|workbench| (workbench.window_title(), workbench.lifecycle.represented_filename.clone(), workbench.lifecycle.document_edited)).unwrap_or_default(),
};
if is_current && index + 1 < windows.len() {
active = index as i64 + 1;
}
let button = match (dirty, is_current) {
(true, _) => Button { codicon: Some("close-dirty".into()), tooltip: Some("Close Window".into()), always_visible: true, ..Button::default() },
(false, true) => Button { codicon: Some("window-active".into()), tooltip: Some("Close Active Window".into()), always_visible: true, ..Button::default() },
(false, false) => Button { codicon: Some("remove-close".into()), tooltip: Some("Close Window".into()), ..Button::default() },
};
entries.push(Entry::Item(Item {
handle: index as i64,
label: title,
description: is_current.then(|| "Current Window".to_owned()),
file_icon: filename,
buttons: vec![button],
..Item::default()
}));
}
let mut input = QuickInput::new(0, Kind::QuickPick);
input.placeholder = Some("Select a window to switch to".into());
input.set_items(entries);
input.set_active_items(&[active]);
let id = self.quick_inputs.add(input, Owner::SwitchWindow(windows));
self.show_quick_input(id, window, cx);
self.flush_quick_input_events(window, cx);
}
pub fn switch_window_event(&mut self, id: i64, event: Event, window: &mut Window, cx: &mut Context<Self>) {
let Some(Owner::SwitchWindow(windows)) = self.quick_inputs.owner(id) else { return };
let windows = windows.clone();
match event {
Event::Accept(_) => {
let Some(handle) = self.quick_inputs.get(id).and_then(|input| input.selected_handles().first().copied()) else { return };
self.hide_quick_input_by_id(id, window, cx);
let target = windows[handle as usize];
cx.defer(move |cx| _ = target.update(cx, |_, window, _| window.activate_window()));
}
Event::TriggerItemButton(handle, _, _) => {
if let Some(input) = self.quick_inputs.get_mut(id) {
input.remove_item(handle);
}
let target = windows[handle as usize];
if target.window_id() == window.window_handle().window_id() {
self.hide_quick_input_by_id(id, window, cx);
_ = self.execute_command("workbench.action.closeWindow", vec![], window, cx);
return;
}
cx.defer(move |cx| _ = target.update(cx, |workbench, window, cx| _ = workbench.execute_command("workbench.action.closeWindow", vec![], window, cx)));
cx.notify();
}
Event::Hide => self.quick_inputs.remove(id),
_ => {}
}
}
}
/// launchMainService.ts `startOpenWindow` for a second instance's command line: without paths the last active window
/// comes to the front (the macOS default of `window.openWithoutArgumentsInNewWindow`), or an empty window opens with
/// `on` or `--new-window`. With paths, windowsMainService.ts `open`: `--add` folders join the last active window,
/// files open in the window whose folder holds them (`findWindowOnFile`), else there, folders and workspaces in new windows unless `--reuse-window`,
/// `--wait` or `window.openFoldersInNewWindow` keep the first one in the last active window. `from_dock` is the
/// `DOCK` context of Finder and the Dock, where files open in a new window too.
pub(crate) fn start_open_window(args: Vec<String>, cwd: PathBuf, from_dock: bool, launched_from_cli: bool, cx: &mut App) {
let parsed = match crate::argv::parse_and_validate(&args[1..]) {
Ok((parsed, _)) => parsed,
Err(error) => return eprintln!("[windows] {error}"),
};
let profile = CliProfile::from_args(&args, launched_from_cli);
let CommandLine { workspaces, folders_to_add, files, new_window, reuse_window } = CommandLine::from_args(&parsed, &cwd);
let last_active = cx.window_stack().unwrap_or_else(|| cx.windows()).into_iter().find_map(|window| window.downcast::<Workbench>());
let setting = |key: &str, cx: &App| last_active.and_then(|handle| handle.read(cx).ok()).map(|workbench| workbench.setting(key));
if parsed.positional.is_empty() {
let in_new_window = new_window || profile.is_forced() || (!reuse_window && setting("window.openWithoutArgumentsInNewWindow", cx).is_none_or(|value| value == "on"));
match last_active.filter(|_| !in_new_window) {
Some(handle) => drop(handle.update(cx, |workbench, window, cx| {
workbench.open_command_line_files(files, None, window, cx);
window.activate_window();
})),
None => open_command_line_window(None, files, profile, cx),
}
return;
}
if !folders_to_add.is_empty()
&& let Some(handle) = last_active
{
drop(handle.update(cx, |workbench, window, cx| {
if let Err(error) = workbench.add_workspace_folders(folders_to_add.into_iter().map(|folder| (folder, None)).collect(), None, window, cx) {
workbench.notify_error(error);
}
window.activate_window();
}));
}
// `shouldOpenNewWindow`: forced by the flags, else `window.openFoldersInNewWindow`, else new unless `--wait`.
let folder_in_new_window = match (new_window, reuse_window, setting("window.openFoldersInNewWindow", cx)) {
(_, true, _) => false,
(true, _, _) => true,
(_, _, Some(value)) if value == "on" || value == "off" => value == "on",
_ => !parsed.flag("wait"),
};
let files_in_new_window = match (new_window, reuse_window, setting("window.openFilesInNewWindow", cx)) {
(_, true, _) => false,
(true, _, _) => true,
(_, _, Some(value)) if value == "on" || value == "off" => value == "on",
_ => from_dock,
};
let mut files = Some(files).filter(|files| !files.is_empty() || files.wait_marker.is_some());
for (index, path) in workspaces.into_iter().enumerate() {
let reuse = index == 0 && !folder_in_new_window;
match last_active.filter(|_| reuse) {
Some(handle) => {
let files = files.take().unwrap_or_default();
drop(handle.update(cx, |workbench, window, cx| workbench.relaunch(ShutdownReason::Load, Some(path), files, window, cx)));
}
None => open_command_line_window(Some(path), files.take().unwrap_or_default(), profile.clone(), cx),
}
}
let Some(files) = files else { return };
let file_to_check = files.open.first().map(|file| file.path.as_path()).or(files.diff.first().map(PathBuf::as_path)).or(files.merge.first().map(PathBuf::as_path));
let window_on_file = file_to_check.and_then(|file| find_window_on_file(file, cx));
match window_on_file.or(last_active).filter(|_| !files_in_new_window) {
Some(handle) => drop(handle.update(cx, |workbench, window, cx| {
workbench.open_command_line_files(files, None, window, cx);
window.activate_window();
})),
None => open_command_line_window(None, files, profile, cx),
}
}
/// windowsFinder.ts `findWindowOnFile`: the first workspace window with a folder that holds the file, else the single
/// folder window nearest above it. Paths compare ignoring case (`extUriBiasedIgnorePathCase` on macOS).
fn find_window_on_file(file: &Path, cx: &App) -> Option<WindowHandle<Workbench>> {
let file = PathBuf::from(file.to_string_lossy().to_lowercase());
let holds_file = |folder: &Path| file.starts_with(folder.to_string_lossy().to_lowercase());
let mut folder_window: Option<(WindowHandle<Workbench>, usize)> = None;
for handle in cx.windows().into_iter().filter_map(|window| window.downcast::<Workbench>()) {
let Some(workspace) = handle.read(cx).ok().and_then(|workbench| workbench.workspace()) else { continue };
let depth = workspace.folders.iter().filter(|folder| holds_file(&folder.path)).map(|folder| folder.path.as_os_str().len()).max();
match (&workspace.file, depth) {
(_, None) => {}
(Some(_), Some(_)) => return Some(handle),
(None, Some(depth)) => {
if folder_window.is_none_or(|(_, deepest)| depth > deepest) {
folder_window = Some((handle, depth));
}
}
}
}
folder_window.map(|(handle, _)| handle)
}
/// windowsMainService.ts `open` with `forceNewWindow`: a folder or `.code-workspace` file opens as a new window's
/// workspace unless a window has it open already (that one comes to the front), any other path as an empty window's
/// file, nothing as an empty window. Opened after the caller's update.
pub(super) fn open_new_window(path: Option<PathBuf>, cx: &mut App) {
open_command_line_window(path, FilesToOpen::default(), CliProfile::default(), cx);
}
/// `open_new_window` for a command line, with its `--profile` or `--profile-temp` and the files to open in it.
pub(super) fn open_command_line_window(path: Option<PathBuf>, mut files: FilesToOpen, profile: CliProfile, cx: &mut App) {
let mut request = WindowRequest { profile, ..WindowRequest::default() };
match path.map(Openable::of) {
Some(Openable::Workspace(path)) => request.workspace = Some(config::workspace::Workspace::open(path)),
Some(Openable::File(path)) => files.open.insert(0, FileToOpen { path, line: None, column: None }),
None => {}
}
request.files = files;
cx.defer(move |cx| {
let location = request.workspace.as_ref().map(|workspace| workspace.file.clone().unwrap_or_else(|| workspace.folders[0].path.clone()));
let windows = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>());
let existing = windows.filter(|_| location.is_some()).find(|handle| handle.read(cx).is_ok_and(|workbench| workbench.workspace_location() == location));
match existing {
Some(handle) => drop(handle.update(cx, |workbench, window, cx| {
workbench.open_command_line_files(request.files, None, window, cx);
window.activate_window();
})),
#[cfg(not(test))]
None => open_window_or_log(request, cx),
// main.rs `open_window` needs the app's extensions and an extension host; tests open a bare workbench window.
#[cfg(test)]
None => tests::open_request_window(request, cx),
}
});
}
/// extensionHostDebugIpc.ts and windowsMainService.ts `openExtensionDevelopmentHostWindow`: the window on the same
/// extension path reloads with the new debug flags, else a new window opens on the arguments' folder and files.
pub(super) fn open_extension_development_host_window(args: &[String], cx: &mut App) -> anyhow::Result<()> {
let Some(development) = ExtensionDevelopment::from_args(args)? else { anyhow::bail!("no --extensionDevelopmentPath") };
let host_debug = ExtensionHostDebug::from_args(args);
let (parsed, _) = crate::argv::parse_and_validate(args).map_err(anyhow::Error::msg)?;
let CommandLine { workspaces, files, .. } = CommandLine::from_args(&parsed, &std::env::current_dir()?);
cx.defer(move |cx| {
let mut windows = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>());
let existing = windows.find(|handle| handle.read(cx).is_ok_and(|workbench| workbench.development.as_ref().is_some_and(|open| open.extension_path == development.extension_path)));
if let Some(handle) = existing {
drop(handle.update(cx, |workbench, window, cx| {
workbench.extension_host_debug = host_debug;
let folder = workbench.workspace_location();
workbench.relaunch(ShutdownReason::Reload, folder, FilesToOpen::default(), window, cx)
}));
return;
}
let request = WindowRequest { workspace: workspaces.into_iter().next().map(config::workspace::Workspace::open), files, development: Some(development), host_debug, ..WindowRequest::default() };
#[cfg(not(test))]
open_window_or_log(request, cx);
#[cfg(test)]
tests::open_request_window(request, cx);
});
Ok(())
}
/// extensionHostDebugService.ts `close` and `reload` as localProcessExtensionHost.ts hears them: the extension
/// development window whose `--debugId` is the session's runs `command`.
pub(super) fn run_in_extension_development_host(debug_id: &str, command: &'static str, cx: &mut App) {
let debug_id = debug_id.to_owned();
cx.defer(move |cx| {
let mut windows = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>());
let found = windows.find(|handle| handle.read(cx).is_ok_and(|workbench| workbench.extension_development && workbench.extension_host_debug.debug_id.as_deref() == Some(debug_id.as_str())));
let Some(handle) = found else { return };
drop(handle.update(cx, |workbench, window, cx| workbench.execute_command(command, vec![], window, cx)));
});
}
/// localProcessExtensionHost.ts `attachSession`: a host started with an inspector port in a window a debug session
/// launched has that session, in whichever window runs it, attach to the port.
pub(super) fn attach_extension_host_session(host_debug: &ExtensionHostDebug, cx: &mut App) {
let (Some(debug_id), Some(port)) = (host_debug.debug_id.clone(), host_debug.port) else { return };
cx.defer(move |cx| {
let mut windows = cx.windows().into_iter().filter_map(|handle| handle.downcast::<Workbench>());
let found = windows.find(|handle| handle.read(cx).is_ok_and(|workbench| workbench.debug.sessions_including_inactive().iter().any(|session| session.id == debug_id)));
let Some(handle) = found else { return };
drop(handle.update(cx, |workbench, window, cx| workbench.attach_session(&debug_id, port, window, cx)));
});
}
/// Electron's `setAlwaysOnTop` on macOS: the floating window level.
#[cfg(target_os = "macos")]
pub(super) fn is_always_on_top(window: &Window) -> bool {
crate::dialog::app_kit_window(window).is_some_and(|ns_window| ns_window.level() == NSFloatingWindowLevel)
}
#[cfg(target_os = "macos")]
fn set_always_on_top(window: &Window, on_top: bool) {
crate::dialog::ns_window(window).setLevel(if on_top { NSFloatingWindowLevel } else { NSNormalWindowLevel });
}
#[cfg(target_os = "windows")]
pub(super) use crate::win32::is_always_on_top;
#[cfg(target_os = "windows")]
use crate::win32::set_always_on_top;
#[cfg(target_os = "linux")]
thread_local! {
/// The windows set always on top: Chromium's X11 and Wayland windows keep the z-order level they were given and
/// report that one, Wayland having no protocol to apply it.
static ALWAYS_ON_TOP: std::cell::RefCell<std::collections::HashSet<gpui::WindowId>> = Default::default();
}
#[cfg(target_os = "linux")]
pub(super) fn is_always_on_top(window: &Window) -> bool {
ALWAYS_ON_TOP.with_borrow(|windows| windows.contains(&window.window_handle().window_id()))
}
/// Chromium's X11Window `SetZOrderLevel`: the `_NET_WM_STATE_ABOVE` state through the window manager.
#[cfg(target_os = "linux")]
fn set_always_on_top(window: &Window, on_top: bool) {
ALWAYS_ON_TOP.with_borrow_mut(|windows| match on_top {
true => windows.insert(window.window_handle().window_id()),
false => windows.remove(&window.window_handle().window_id()),
});
let Some(xid) = crate::x11::window_xid(window) else { return };
if let Err(error) = crate::x11::set_wm_state(xid, "_NET_WM_STATE_ABOVE", on_top) {
eprintln!("[window] always on top: {error}");
}
}
#[cfg(test)]
mod tests;