Skip to content

Visual Studio Code, rebuilt in Rust

Rust
9.5 KB
Raw Blame
//! The workbench's side of mainThreadConsole.ts, mainThreadErrors.ts and the activation errors of
//! mainThreadExtensionService.ts. The session prints each call to the port log (stderr, the window's console) and
//! answers it; the workbench gets a copy (`OBSERVED_REQ`) for the Window log and notifications.

use std::time::Instant;

use exthost::gallery::{ExtensionInfo, Gallery, GalleryExtension};
use exthost::session::ForwardedRequest;
use gpui::Context;
use serde_json::{Value, json};

use crate::commands::Outcome;
use crate::extension_enablement::EnablementState;
use crate::extensions_model::Extension;
use crate::notifications::{Action, Notification, Run, Severity};
use crate::output::logger::{console_log_line, to_error_message};
use crate::workbench::Workbench;

const INSTALL_AND_RELOAD: &str = "_mainThreadExtensionService.installAndReload";
const ENABLE_AND_RELOAD: &str = "_mainThreadExtensionService.enableAndReload";
const RELOAD_WINDOW: &str = "workbench.action.reloadWindow";

impl Workbench {
    pub fn handle_observed_request(&mut self, request: &ForwardedRequest, cx: &mut Context<Self>) -> Outcome {
        let arg = |index: usize| request.args.get(index).cloned().unwrap_or(Value::Null);
        match (request.proxy, request.method.as_str()) {
            // `MainThreadConsole.$logExtensionHostMessage`: an extension test run from the command line logs every
            // entry (`isExtensionDevTestFromCli`), any other run its errors only.
            ("MainThreadConsole", "$logExtensionHostMessage") => {
                if let Some((level, text)) = console_log_line(&arg(0), self.skip_dialogs) {
                    self.output.log_window(level, &text);
                }
            }
            ("MainThreadErrors", "$onUnexpectedError") => {
                if let Some(text) = self.unexpected_errors.handle(&arg(0), Instant::now()) {
                    self.output.log_window(5, &text);
                }
            }
            ("MainThreadExtensionService", "$onExtensionActivationError") => self.extension_activation_failed(&arg(0), &arg(1), &arg(2), cx),
            _ => {}
        }
        Outcome::done()
    }

    /// The actions of the missing dependency notifications: `extensionsWorkbenchService.install` or `setEnablement`,
    /// then `hostService.reload`.
    pub(crate) fn register_activation_error_commands(&mut self) {
        self.commands.register(INSTALL_AND_RELOAD, |workbench, args, window, cx| {
            let Some(id) = args.first().and_then(Value::as_str) else { return Outcome::error("Extension id required.") };
            let Outcome::Pending(installed) = workbench.install_from_gallery(id.to_owned(), None, false, cx) else { return Outcome::done() };
            // A failed install already notified its error.
            cx.spawn_in(window, async move |workbench, cx| {
                if let Ok(Ok(_)) = installed.await {
                    let _ = workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(RELOAD_WINDOW, Vec::new(), window, cx)));
                }
            })
            .detach();
            Outcome::done()
        });
        self.commands.register(ENABLE_AND_RELOAD, |workbench, args, window, cx| {
            let Some(id) = args.first().and_then(Value::as_str) else { return Outcome::error("Extension id required.") };
            let state = if args.get(1) == Some(&json!(true)) { EnablementState::EnabledWorkspace } else { EnablementState::EnabledGlobally };
            match workbench.set_extension_enablement(&[id.to_owned()], state, cx) {
                Outcome::Ready(Err(error)) => Outcome::Ready(Err(error)),
                _ => workbench.execute_command(RELOAD_WINDOW, Vec::new(), window, cx),
            }
        });
    }

    /// `$onExtensionActivationError`: a missing dependency of a known extension is a notification
    /// (`_handleMissingInstalledDependency`, `_handleMissingNotInstalledDependency`); any other error one while an
    /// extension is developed (`isDev`, the port being a built product), else only the console line the session printed.
    fn extension_activation_failed(&mut self, extension_id: &Value, error: &Value, missing_dependency: &Value, cx: &mut Context<Self>) {
        let id = extension_id["value"].as_str().unwrap_or_default();
        let extension = self.extensions.iter().find(|extension| extension.id.eq_ignore_ascii_case(id));
        if let (Some(dependency), Some(extension)) = (missing_dependency["dependency"].as_str(), extension) {
            let name = display_name(&extension.description);
            let installed = self.local_extensions().into_iter().find(|local| local.identifier().id.eq_ignore_ascii_case(dependency));
            match installed {
                Some(installed) => self.missing_installed_dependency(&name, &installed),
                None => self.missing_not_installed_dependency(name, dependency.to_owned(), cx),
            }
            return;
        }
        if self.extension_development {
            self.notify(Notification::new(Severity::Error, to_error_message(error, false)));
        }
    }

    /// `_handleMissingInstalledDependency`. The port has no virtual workspaces, so `notSupportedInWorkspace` has no
    /// counterpart.
    fn missing_installed_dependency(&mut self, name: &str, dependency: &Extension) {
        let local = dependency.local.as_ref().expect("an installed extension");
        let dependency_name = display_name(&local.description);
        // `DisabledByTrustRequirement` is computed for a user-enabled extension only (`_computeEnablementState`).
        let user_enabled = !matches!(dependency.enablement, EnablementState::DisabledByEnvironment | EnablementState::DisabledByInvalidExtension | EnablementState::DisabledGlobally | EnablementState::DisabledWorkspace);
        let disabled_by_trust = user_enabled && !self.workspace_trust.is_trusted() && {
            let configured = self.settings.lock().unwrap().get_value(Some("extensions.supportUntrustedWorkspaces"), &config::configuration::Overrides::default()).unwrap_or_default();
            crate::workspace_trust::disabled_when_untrusted(local, self.workspace(), &configured)
        };
        let notification = if dependency.enablement.is_enabled() && !disabled_by_trust {
            let message = format!("Cannot activate the '{name}' extension because it depends on the '{dependency_name}' extension, which is not loaded. Would you like to reload the window to load the extension?");
            with_action(message, "reload", "Reload Window", Run::Command(RELOAD_WINDOW.into(), Vec::new()))
        } else if disabled_by_trust {
            let message = format!("Cannot activate the '{name}' extension because it depends on the '{dependency_name}' extension which is not supported in Restricted Mode");
            with_action(message, "manageWorkspaceTrust", "Manage Workspace Trust", Run::Command("workbench.trust.manage".into(), Vec::new()))
        } else if self.can_change_enablement(&local.id) {
            let message = format!("Cannot activate the '{name}' extension because it depends on the '{dependency_name}' extension which is disabled. Would you like to enable the extension and reload the window?");
            let workspace = dependency.enablement != EnablementState::DisabledGlobally;
            with_action(message, "enable", "Enable and Reload", Run::Command(ENABLE_AND_RELOAD.into(), vec![json!(local.id), json!(workspace)]))
        } else {
            Notification::new(Severity::Error, format!("Cannot activate the '{name}' extension because it depends on the '{dependency_name}' extension which is disabled."))
        };
        self.notify(notification);
    }

    /// `_handleMissingNotInstalledDependency`: the Open VSX lookup runs off the UI thread; a failed lookup finds nothing.
    fn missing_not_installed_dependency(&mut self, name: String, dependency: String, cx: &mut Context<Self>) {
        let info = ExtensionInfo { id: dependency.clone(), uuid: None, version: None, pre_release: false };
        let lookup = cx.background_executor().spawn(async move { Gallery::open_vsx(&crate::VERSION).get_extensions(&[info], false).ok().and_then(|found| found.into_iter().next()) });
        cx.spawn(async move |workbench, cx| {
            let found = lookup.await;
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.notify_missing_dependency(&name, &dependency, found.as_ref());
                cx.notify();
            });
        })
        .detach();
    }

    pub(crate) fn notify_missing_dependency(&mut self, name: &str, dependency: &str, found: Option<&GalleryExtension>) {
        let Some(found) = found else {
            return self.notify_error(format!("Cannot activate the '{name}' extension because it depends on an unknown '{dependency}' extension."));
        };
        let message = format!(
            "Cannot activate the '{name}' extension because it depends on the '{}' extension from '{}', which is not installed. Would you like to install the extension and reload the window?",
            found.display_name, found.publisher_display_name
        );
        self.notify(with_action(message, "install", "Install and Reload", Run::Command(INSTALL_AND_RELOAD.into(), vec![json!(found.id)])));
    }
}

fn display_name(manifest: &Value) -> String {
    manifest["displayName"].as_str().filter(|name| !name.is_empty()).or(manifest["name"].as_str()).unwrap_or_default().to_owned()
}

fn with_action(message: String, id: &str, label: &str, run: Run) -> Notification {
    Notification { primary: vec![Action { id: id.into(), label: label.into(), run }], ..Notification::new(Severity::Error, message) }
}

#[cfg(test)]
mod tests;