Visual Studio Code, rebuilt in Rust
Rust
//! `workbench.action.restartExtensionHost` and the restart a profile switch needs (`stopExtensionHosts`, then
//! `startExtensionHosts`): the host is told to terminate, what it registered in the workbench is disposed as each
//! MainThread* `dispose` does, and a new host starts with the window's current extensions, settings and storage.
use config::configuration::Overrides;
use exthost::WakingSender;
use exthost::extension_development::ExtensionDevelopment;
use exthost::extension_management::add_user_extensions;
use exthost::scan::ScannedExtension;
use exthost::session::ForwardedRequest;
use futures::StreamExt;
use futures::channel::mpsc::UnboundedReceiver;
use gpui::{App, Context, PromptLevel, Task, Window};
use serde_json::Value;
use super::Workbench;
use super::host_requests::uri_parts;
use crate::commands::Outcome;
use crate::extension_host_start::HostStart;
use crate::main_thread::HostRequest;
use crate::markers::ReadOptions;
impl Workbench {
pub(super) fn register_extension_host_commands(&mut self) {
self.commands.register("workbench.action.restartExtensionHost", |workbench, _, window, cx| {
workbench.restart_extension_host("An explicit request", window, cx);
Outcome::done()
});
}
/// `stopExtensionHosts` then, unless vetoed, `startExtensionHosts`, with the user extensions of the current profile.
pub(crate) fn restart_extension_host(&mut self, reason: &str, window: &mut Window, cx: &mut Context<Self>) {
let stopped = self.stop_extension_hosts(reason, window, cx);
cx.spawn_in(window, async move |workbench, cx| {
if stopped.await {
let _ = workbench.update_in(cx, |workbench, window, cx| workbench.start_extension_hosts(window, cx));
}
})
.detach();
}
/// abstractExtensionService.ts `_doStopExtensionHostsWithVeto`: the `onWillStop` listeners veto, a veto asks to
/// restart anyway; true when the host stopped.
pub(crate) fn stop_extension_hosts(&mut self, reason: &str, window: &mut Window, cx: &mut Context<Self>) -> Task<bool> {
let mut vetoes = Vec::new();
// debugService.ts
if !self.debug.sessions.is_empty() {
vetoes.push("A debug session is still running that would terminate.".to_owned());
}
// mainThreadCustomEditors.ts `MainThreadCustomEditorModel` of an editable document.
for document in self.webview_panels.custom_editors.documents.iter().filter(|document| document.editable) {
let name = uri_parts(&document.resource).ok().and_then(|(_, path)| path.file_name().map(|name| name.to_string_lossy().into_owned())).unwrap_or_default();
vetoes.push(format!("An extension provided editor for '{name}' is still open that would close otherwise."));
}
// customTextEditorModel.ts
for panel in self.webview_panels.panels.iter().filter(|panel| panel.editor.is_some()) {
vetoes.push(format!("An extension provided text editor for '{}' is still open that would close otherwise.", panel.title));
}
// notebookEditorInput.ts: a dirty notebook vetoes unless it saves.
let dirty: Vec<String> = self.host.notebooks.models.iter().filter(|model| model.dirty).map(|model| model.uri_string()).collect();
let mut saves = Vec::new();
for key in dirty {
let name = key.rsplit('/').next().unwrap_or_default();
let veto = format!("An extension provided notebook for '{name}' could not be saved.");
saves.push((self.save_notebook_editor(&key, cx), veto));
}
let reason = reason.to_owned();
cx.spawn_in(window, async move |workbench, cx| {
for (saved, veto) in saves {
if saved.await != Ok(true) {
vetoes.push(veto);
}
}
let mut reasons: Vec<String> = Vec::new();
for veto in vetoes {
if !reasons.contains(&veto) {
reasons.push(veto);
}
}
if !reasons.is_empty() {
eprintln!("Extension host was not stopped because of veto (stop reason: {reason}, veto reason: {})", reasons.join(", "));
let detail = reasons.join("\n -");
let Ok(answer) = workbench.update_in(cx, |_, window, cx| crate::dialog::show_message_box(window, crate::dialog::InTests::Confirm, PromptLevel::Warning, "Please confirm restart of extensions.", Some(&detail), &["Restart Anyway", "Cancel"], None, cx)) else { return false };
if !matches!(answer.await, Ok((0, _))) {
return false;
}
}
workbench.update(cx, |workbench, cx| workbench.stop_extension_host(cx)).is_ok()
})
}
/// `startExtensionHosts`: a new host with the window's extensions to run.
pub(super) fn start_extension_hosts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let extensions = self.extensions_to_run();
self.set_running_extensions_after_restart(extensions, cx);
self.start_extension_host(window, cx);
}
pub(super) fn stop_extension_host(&mut self, cx: &mut Context<Self>) {
self.host.stop_extension_host();
// MainThreadCommands: the commands the host registered.
for (id, registration) in std::mem::take(&mut self.extension_commands) {
self.commands.dispose(&id, registration);
}
// MainThreadLanguageFeatures, MainThreadSCM, MainThreadWebview*, MainThreadUrls, MainThreadUriOpeners.
self.language_features = Default::default();
self.folding_providers = Default::default();
self.scm_extension_host_stopping();
self.scm.model = Default::default();
self.webview_views = Default::default();
self.urls.handlers.clear();
self.urls.openers.clear();
// MainThreadDiagnostics: `changeAll(owner, [])` for each owner the host used.
let host_markers = self.diagnostics.service.read(ReadOptions::default());
let mut owners: Vec<String> = host_markers.iter().filter(|marker| marker.origin.as_deref() == Some(super::diagnostics::EXT_HOST_ID)).map(|marker| marker.owner.clone()).collect();
owners.dedup();
for owner in owners {
self.clear_markers(&owner, cx);
}
self.trigger_folding_model_changed(cx);
}
/// The installed extensions less those disabled in the profile or workspace and those an untrusted workspace
/// turns off, as main.rs picks them at startup.
pub(super) fn extensions_to_run(&mut self) -> Vec<ScannedExtension> {
let viewlet = &self.extensions_viewlet;
let mut installed = viewlet.builtins.clone();
match viewlet.user.as_ref().map(|user| user.scan()).transpose() {
Ok(user) => add_user_extensions(&mut installed, user.unwrap_or_default()),
Err(error) => eprintln!("[extensions] scanning the user extensions: {error:#}"),
}
let development = self.development_without_tests();
if let Some(development) = &development
&& let Err(error) = development.add_extension(&mut installed)
{
eprintln!("[extensions] {error:#}");
}
self.proposed_api.update_enabled_api_proposals(&mut installed);
let developed = viewlet.development.clone();
let disabled = {
let mut profile = self.profile_storage.lock().unwrap();
let mut workspace = self.workspace_storage.lock().unwrap();
super::extensions_view::disabled_at_startup(&installed, &mut profile, self.folder.is_some().then_some(&mut *workspace), &developed, self.extensions_viewlet.bisect.as_ref())
};
installed.retain(|extension| !disabled.contains(&extension.id));
if !self.workspace_trust.is_trusted() {
let configured = self.settings.lock().unwrap().get_value(Some("extensions.supportUntrustedWorkspaces"), &Overrides::default()).unwrap_or_default();
let workspace = self.workspace().cloned();
installed.retain(|extension| !crate::workspace_trust::disabled_when_untrusted(extension, workspace.as_ref(), &configured));
}
installed
}
fn set_running_extensions_after_restart(&mut self, extensions: Vec<ScannedExtension>, cx: &mut Context<Self>) {
let described: Vec<(&str, &Value)> = extensions.iter().map(|extension| (extension.id.as_str(), &extension.description)).collect();
let before = self.model_creation_options();
let change = self.settings.lock().unwrap().set_registry(config::registry::Registry::with_extensions(&described));
self.observe_relaunch_settings();
self.status_entries = crate::main_thread_status_bar::static_entries(&extensions);
self.set_running_extensions(extensions, cx);
self.configuration_changed(&change, before, cx);
}
/// A new host for the window's running extensions; the old one's documents, editors and tabs are sent again.
fn start_extension_host(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(launch) = self.host_launch.clone() else {
self.extension_host_started(cx);
return;
};
let (start, mut host) = HostStart::new(self.theme.kind, &self.languages);
host.configuration_scopes = self.host.configuration_scopes;
host.untitled_names_from_content = self.host.untitled_names_from_content;
host.search_tabs = std::mem::take(&mut self.host.search_tabs);
host.terminal_tabs = std::mem::take(&mut self.host.terminal_tabs);
self.host = host;
self.send_host_changes();
let development = self.development_without_tests();
drop(self.spawn_extension_host(start, launch, development, window, cx));
}
}
impl Workbench {
/// Counts a host this window starts, whose exit is reported with the returned number, and has a debug session
/// attach to its inspector port.
pub fn extension_host_started(&mut self, cx: &mut App) -> u32 {
self.extension_host_starts += 1;
super::host::attach_extension_host_session(&self.extension_host_debug, cx);
self.extension_host_starts
}
/// abstractExtensionService.ts `_onExtensionHostCrashOrExit`: the exit of an extension development window's
/// current host closes the window (nativeExtensionService.ts `_onExtensionHostExit`). A host a restart replaced
/// does not count.
pub fn extension_host_exited(&mut self, start: u32, window: &mut Window, cx: &mut Context<Self>) {
if start != self.extension_host_starts || !self.extension_development {
return;
}
_ = self.execute_command("workbench.action.closeWindow", vec![], window, cx);
}
/// The extension under development without its tests: a restarted host does not run them again.
fn development_without_tests(&self) -> Option<ExtensionDevelopment> {
let development = self.development.clone()?;
Some(ExtensionDevelopment { tests_path: None, ..development })
}
}
/// Answers the host requests the session forwards to the workbench, each on the window's thread.
pub fn serve_host_requests(mut requests: UnboundedReceiver<ForwardedRequest>, reply_sender: WakingSender<(u32, Result<Value, Value>)>, window: &mut Window, cx: &mut Context<Workbench>) {
cx.spawn_in(window, async move |workbench, cx| {
while let Some(request) = requests.next().await {
let req = request.req;
// A cancellation answers nothing itself; the request it cancels gets its answer. An observed call
// was answered by the session.
let cancel = request.method == "$cancel" || req == exthost::session::OBSERVED_REQ;
let Ok(outcome) = workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(request, window, cx)) else { break };
let result = match outcome {
_ if cancel => continue,
Outcome::Ready(result) => result,
// Requests from the host may overlap, so a pending answer is awaited off this loop.
Outcome::Pending(pending) => {
let reply_sender = reply_sender.clone();
cx.background_executor()
.spawn(async move {
let _ = reply_sender.send((req, pending.await.unwrap_or(Ok(Value::Null))));
})
.detach();
continue;
}
};
let _ = reply_sender.send((req, result));
}
})
.detach();
}
/// Runs the MainThread* calls the workbench implements (`WorkbenchMainThread`) on the window's thread.
pub fn serve_main_thread_requests(mut requests: UnboundedReceiver<HostRequest>, window: &mut Window, cx: &mut Context<Workbench>) {
cx.spawn_in(window, async move |workbench, cx| {
while let Some(request) = requests.next().await {
let HostRequest { proxy, method, args, reply } = request;
// A blocking call's answer goes back through `reply`, never by its `req`.
let request = ForwardedRequest { req: 0, proxy, method, args };
let result = match workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(request, window, cx)) {
Ok(Outcome::Ready(result)) => result,
// A save waits on its dialogs; the session pumps meanwhile (main_thread.rs `ask_while_pumping`).
Ok(Outcome::Pending(pending)) => pending.await.unwrap_or_else(|_| Err(exthost::main_thread::serialized_error("Canceled"))),
Err(_) => Err(exthost::main_thread::serialized_error("Canceled")),
};
let _ = reply.send(result);
}
})
.detach();
}
#[cfg(test)]
mod tests;