Skip to content

Visual Studio Code, rebuilt in Rust

Rust
43.9 KB
Raw Blame
//! Installing and uninstalling extensions from the workbench (extensions.contribution.ts): the commands, the
//! notification after a VSIX install, and the contributions the workbench reads again once the host runs the change.

use std::path::PathBuf;
use std::time::Duration;

use config::configuration::Overrides;
use files::watcher::{Change, Watcher};
use futures::StreamExt;
use futures::channel::mpsc;
use exthost::extension_management::Job;
use anyhow::Context as _;
use exthost::gallery::{ExtensionInfo, Gallery, GalleryVersion, Operation};
use exthost::scan::ScannedExtension;
use futures::channel::oneshot;
use gpui::{Context, PromptLevel, Task, Window};
use serde_json::Value;

use super::Workbench;
use super::host_requests::uri_parts;
use crate::commands::Outcome;
use crate::file_dialog::FileDialog;
use exthost::main_thread::serialized_error;
use crate::notifications::{Notification, Progress, Severity};
use crate::quick_input::{Entry, Item, Kind, QuickInput};

/// `SELECT_INSTALL_VSIX_EXTENSION_COMMAND_ID`.
const SELECT_INSTALL_VSIX: &str = "workbench.extensions.action.installVSIX";
/// `INSTALL_EXTENSION_FROM_VSIX_COMMAND_ID`.
const INSTALL_FROM_VSIX: &str = "workbench.extensions.command.installFromVSIX";

impl Workbench {
    pub(super) fn register_extension_management_commands(&mut self) {
        self.commands.register(SELECT_INSTALL_VSIX, |workbench, _, window, cx| {
            let filters = vec![("VSIX Extensions".to_owned(), vec!["vsix".to_owned()])];
            let dialog = FileDialog { title: Some("Install from VSIX".into()), button_label: Some("Install".into()), filters, files: true, multiple: true, ..FileDialog::default() };
            let picked = workbench.show_open_dialog(dialog, cx);
            let (sender, receiver) = oneshot::channel();
            cx.spawn_in(window, async move |workbench, cx| {
                let paths = picked.await.unwrap_or_default();
                if paths.is_empty() {
                    return drop(sender.send(Ok(Value::Null)));
                }
                let uris = paths.iter().map(|path| exthost::scan::file_uri(path)).collect();
                let outcome = workbench.update_in(cx, |workbench, window, cx| workbench.execute_command(INSTALL_FROM_VSIX, vec![Value::Array(uris)], window, cx));
                let result = match outcome {
                    Ok(Outcome::Ready(result)) => result,
                    Ok(Outcome::Pending(pending)) => pending.await.unwrap_or(Ok(Value::Null)),
                    Err(_) => Ok(Value::Null),
                };
                let _ = sender.send(result);
            })
            .detach();
            Outcome::Pending(receiver)
        });
        self.commands.register(INSTALL_FROM_VSIX, |workbench, args, _, cx| {
            let resources = match args.into_iter().next() {
                Some(Value::Array(resources)) => resources,
                Some(resource) => vec![resource],
                None => Vec::new(),
            };
            let mut vsixs = Vec::new();
            for resource in &resources {
                match uri_parts(resource) {
                    Ok((_, path)) => vsixs.push(path),
                    Err(error) => return Outcome::Ready(Err(error)),
                }
            }
            workbench.install_vsixs(vsixs, true, cx)
        });
        self.commands.register_with_constraints("workbench.extensions.installExtension", &[|value| value.is_string() || crate::commands::is_uri(value)], |workbench, args, window, cx| match args.first() {
            Some(Value::String(arg)) => {
                let (id, version) = id_and_version(arg);
                let options = args.get(1).cloned().unwrap_or_default();
                // extensionsWorkbenchService.ts: `preferPreReleases` (not a stable build) when the options do not say.
                let pre_release = options["installPreReleaseVersion"].as_bool().unwrap_or(!crate::product::is_stable());
                match options.get("justification") {
                    Some(justification) => workbench.install_with_justification(id, version, pre_release, justification.clone(), window, cx),
                    None => workbench.install_from_gallery(id, version, pre_release, cx),
                }
            }
            Some(uri) => match uri_parts(uri) {
                Ok((_, path)) => workbench.install_vsixs(vec![path], false, cx),
                Err(error) => Outcome::Ready(Err(error)),
            },
            None => Outcome::error("Extension id required."),
        });
        self.commands.register("workbench.extensions.uninstallExtension", |workbench, args, _, cx| {
            let Some(id) = args.first().and_then(Value::as_str).filter(|id| !id.is_empty()) else { return Outcome::error("Extension id required.") };
            if let Some(extension) = workbench.extensions.iter().find(|extension| extension.id.eq_ignore_ascii_case(id))
                && extension.description["isBuiltin"] == true
            {
                return Outcome::error(format!("Extension '{id}' is a Built-in extension and cannot be uninstalled"));
            }
            let id = id.to_owned();
            workbench.reset_extension_enablement(&id);
            workbench.run_extension_jobs(vec![Job::Uninstall(id.clone())], None, cx, move |error| {
                error.replace(&format!("Extension '{id}' is not installed."), &format!("Extension '{id}' is not installed. Make sure you use the full extension ID, including the publisher, e.g.: ms-dotnettools.csharp."))
            })
        });
    }

    /// `extensionsWorkbenchService.install(vsix)` for each file; `notify` shows the result as INSTALL_FROM_VSIX does.
    /// `installExtensions`: the gallery dependencies and pack members of each VSIX install first, off the UI thread; a
    /// VSIX whose lookup fails installs without them.
    fn install_vsixs(&mut self, vsixs: Vec<PathBuf>, notify: bool, cx: &mut Context<Self>) -> Outcome {
        let done = match (notify, vsixs.len()) {
            (false, _) => None,
            (true, 1) => Some("Completed installing extension."),
            (true, _) => Some("Completed installing extensions."),
        };
        let (downloads, verify_signature) = self.download_settings();
        let gallery = self.gallery();
        let installed = self.extensions.clone();
        let prepare = cx.background_executor().spawn(async move {
            let mut jobs = Vec::new();
            let mut queued: Vec<String> = Vec::new();
            for vsix in &vsixs {
                // A VSIX without a readable manifest fails in its own install job, with its error.
                let Ok(manifest) = exthost::extension_management::vsix_manifest(vsix) else { continue };
                let id = exthost::extension_management::gallery_extension_id(&manifest);
                let dependencies = crate::cli_process::string_list(&manifest["extensionDependencies"]);
                let pack = crate::cli_process::string_list(&manifest["extensionPack"]);
                let others = match gallery.dependencies_and_packs(&id, &dependencies, &pack, &installed, false) {
                    Ok(others) => others,
                    Err(error) => {
                        eprintln!("[extensions] Cannot install dependencies and packed extensions of extension: {id} {error:#}");
                        continue;
                    }
                };
                for other in others {
                    if queued.contains(&other.id.to_lowercase()) {
                        continue;
                    }
                    queued.push(other.id.to_lowercase());
                    jobs.push(Job::InstallGallery(gallery.download(&other, Operation::Install, &downloads, verify_signature)?, Box::new(other)));
                }
            }
            jobs.extend(vsixs.into_iter().map(Job::InstallVsix));
            anyhow::Ok(jobs)
        });
        let (sender, receiver) = oneshot::channel();
        cx.spawn(async move |workbench, cx| {
            let installed = match prepare.await {
                Ok(jobs) => workbench.update(cx, |workbench, cx| workbench.run_extension_jobs(jobs, done, cx, |error| error)),
                Err(error) => workbench.update(cx, |workbench, _| {
                    let error = format!("{error:#}");
                    workbench.notify_error(error.clone());
                    Outcome::Ready(Err(serialized_error(&error)))
                }),
            };
            let result = match installed {
                Ok(Outcome::Ready(result)) => result,
                Ok(Outcome::Pending(pending)) => pending.await.unwrap_or(Ok(Value::Null)),
                Err(_) => Ok(Value::Null),
            };
            let _ = sender.send(result);
        })
        .detach();
        Outcome::Pending(receiver)
    }

    /// Where gallery downloads go (`<user data>/CachedExtensionVSIXs`) and whether their signatures are checked.
    fn download_settings(&self) -> (PathBuf, bool) {
        let settings = self.settings.lock().unwrap();
        let downloads = settings.user_home().parent().expect("the user home is <user data>/User").join("CachedExtensionVSIXs");
        let verify_signature = settings.get_value(Some("extensions.verifySignature"), &Overrides::default()) != Some(Value::Bool(false));
        (downloads, verify_signature)
    }

    /// `extensionsWorkbenchService.installExtension` with `justification`: asks "Would you like to install ..." with the
    /// gallery extension's names before installing; Cancel ends in a `CancellationError`, which no one shows.
    pub(super) fn install_with_justification(&mut self, id: String, version: Option<String>, pre_release: bool, justification: Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let lookup = {
            let (id, version) = (id.clone(), version.clone());
            cx.background_executor().spawn(async move { Gallery::open_vsx(&crate::VERSION).installable_extension(&id, version.as_deref(), pre_release) })
        };
        let (sender, receiver) = oneshot::channel();
        cx.spawn_in(window, async move |workbench, cx| {
            let extension = match lookup.await {
                Ok(extension) => extension,
                Err(error) => {
                    let error = format!("{error:#}");
                    let _ = workbench.update(cx, |workbench, _| workbench.notify_error(error.clone()));
                    return drop(sender.send(Err(serialized_error(&error))));
                }
            };
            let (message, detail, install_label) = install_prompt(&extension.display_name, &extension.publisher_display_name, &justification);
            let Ok(answer) = cx.update(|window, cx| crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, PromptLevel::Info, &message, Some(&detail), &[&install_label, "Cancel"], None, cx)) else {
                return;
            };
            if !matches!(answer.await, Ok((0, _))) {
                return drop(sender.send(Err(serialized_error("Canceled"))));
            }
            let Ok(Outcome::Pending(installed)) = workbench.update(cx, |workbench, cx| workbench.install_from_gallery(id, version, pre_release, cx)) else {
                return;
            };
            let _ = sender.send(installed.await.unwrap_or(Ok(Value::Null)));
        })
        .detach();
        Outcome::Pending(receiver)
    }

    /// `extensionsWorkbenchService.install(id)`: the gallery lookup and the download run off the UI thread, then the
    /// host installs the VSIX and starts the extension. A built-in cannot be installed from the gallery.
    pub(crate) fn install_from_gallery(&mut self, id: String, version: Option<String>, pre_release: bool, cx: &mut Context<Self>) -> Outcome {
        self.install_from_gallery_verifying(id, version, pre_release, true, cx)
    }

    /// `install_from_gallery` with `donotVerifySignature` as `!verify`.
    fn install_from_gallery_verifying(&mut self, id: String, version: Option<String>, pre_release: bool, verify: bool, cx: &mut Context<Self>) -> Outcome {
        let installed = self.extensions.iter().find(|extension| extension.id.eq_ignore_ascii_case(&id));
        let builtin = installed.is_some_and(|extension| extension.description["isBuiltin"] == true);
        let operation = if installed.is_some() { Operation::Update } else { Operation::Install };
        let (downloads, verify_setting) = self.download_settings();
        let verify_signature = verify_setting && verify;
        let lower = id.to_lowercase();
        if !self.extensions_viewlet.installing.contains(&lower) {
            self.extensions_viewlet.installing.push(lower.clone());
            self.refresh_extensions_views(cx);
        }
        let trusted = self.user_trusted_publishers();
        let gallery = self.gallery();
        let download_gallery = self.gallery();
        let installed_extensions = self.extensions.clone();
        let lookup = cx.background_executor().spawn(async move {
            if builtin {
                anyhow::bail!("The extension '{id}' cannot be installed because it was not found.");
            }
            let extension = gallery.installable_extension(&id, version.as_deref(), pre_release)?;
            let others = super::trusted_publishers::other_untrusted_publishers(&gallery, &extension, &trusted);
            Ok((extension, others))
        });
        let (sender, receiver) = oneshot::channel();
        cx.spawn(async move |workbench, cx| {
            // `installFromGallery`: `checkForTrustedPublishers` runs before the download.
            let download = async {
                let (extension, others) = lookup.await?;
                let trust = workbench.update(cx, |workbench, cx| workbench.check_trusted_publishers(std::slice::from_ref(&extension), others, cx))??;
                if let Some(trust) = trust
                    && !trust.await.unwrap_or(false)
                {
                    anyhow::bail!(super::trusted_publishers::CANCELED);
                }
                let gallery = download_gallery;
                cx.background_executor()
                    .spawn(async move {
                        // `installExtensions`: the dependencies and pack members install before the extension.
                        let mut jobs = Vec::new();
                        for other in gallery.dependencies_and_packs(&extension.id, &extension.dependencies, &extension.extension_pack, &installed_extensions, pre_release)? {
                            jobs.push(Job::InstallGallery(gallery.download(&other, Operation::Install, &downloads, verify_signature)?, Box::new(other)));
                        }
                        let publisher = (extension.publisher.clone(), extension.publisher_display_name.clone());
                        jobs.push(Job::InstallGallery(gallery.download(&extension, operation, &downloads, verify_signature)?, Box::new(extension)));
                        Ok((jobs, publisher))
                    })
                    .await
            };
            let installed = match download.await {
                Ok((jobs, publisher)) => workbench.update(cx, |workbench, cx| {
                    // `onProfileAwareDidInstallExtensions`: a gallery install trusts its publisher.
                    workbench.trust_publishers(&[publisher]);
                    workbench.run_extension_jobs(jobs, None, cx, |error| error)
                }),
                Err(error) => workbench.update(cx, |workbench, cx| {
                    let error = format!("{error:#}");
                    if error != super::trusted_publishers::CANCELED {
                        workbench.notify_error(error.clone());
                    }
                    cx.notify();
                    Outcome::Ready(Err(serialized_error(&error)))
                }),
            };
            let result = match installed {
                Ok(Outcome::Ready(result)) => result,
                Ok(Outcome::Pending(pending)) => pending.await.unwrap_or(Ok(Value::Null)),
                Err(_) => Ok(Value::Null),
            };
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.extensions_viewlet.installing.retain(|installing| *installing != lower);
                workbench.refresh_extensions_views(cx);
            });
            let _ = sender.send(result);
        })
        .detach();
        Outcome::Pending(receiver)
    }

    /// `InstallAnotherVersionAction.run`: the compatible versions in a pick, then the picked one installs; the
    /// installed version picked again does nothing.
    pub(super) fn install_another_version(&mut self, extension: &crate::extensions_model::Extension, window: &mut Window, cx: &mut Context<Self>) {
        let identifier = extension.identifier();
        let pre_release = match &extension.local {
            Some(_) => extension.pre_release(),
            None => extension.gallery.as_ref().is_some_and(|gallery| gallery.is_pre_release_version),
        };
        let current = extension.local.as_ref().and_then(|local| local.description["version"].as_str()).map(str::to_owned);
        let gallery = self.gallery();
        let lookup = cx.background_executor().spawn(async move {
            let versions = gallery.get_all_compatible_versions(&identifier.id, identifier.uuid.as_deref(), pre_release);
            (identifier.id, versions)
        });
        cx.spawn_in(window, async move |workbench, cx| {
            let (id, versions) = lookup.await;
            let versions = match versions {
                Ok(versions) => versions,
                Err(error) => return workbench.update(cx, |workbench, cx| {
                    workbench.notify_error(format!("{error:#}"));
                    cx.notify();
                }),
            };
            if versions.is_empty() {
                return cx.update(|window, cx| drop(crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, PromptLevel::Info, "This extension has no other versions.", None, &["OK"], None, cx)));
            }
            let input = version_pick(&versions, current.as_deref(), "Select Version to Install");
            let picked = workbench.update_in(cx, |workbench, window, cx| workbench.choose(input, window, cx))?;
            let Some(picked) = picked.await.ok().and_then(Result::ok).and_then(|picked| picked.as_i64()) else { return Ok(()) };
            let version = &versions[picked as usize];
            if current.as_deref() == Some(version.version.as_str()) {
                return Ok(());
            }
            let (number, pre_release) = (version.version.clone(), version.is_pre_release_version);
            workbench.update(cx, |workbench, cx| drop(workbench.install_from_gallery(id, Some(number), pre_release, cx)))
        })
        .detach();
    }

    /// `InstallAction.run` for an unsigned gallery extension of a gallery whose repository is all signed: "Install
    /// Anyway" installs it with `donotVerifySignature`.
    pub(super) fn install_unsigned(&mut self, extension: &crate::extensions_model::Extension, window: &mut Window, cx: &mut Context<Self>) {
        let id = extension.identifier().id;
        let message = format!("'{}' is an extension from an unknown source. Are you sure you want to install?", extension.display_name());
        let answer = crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, PromptLevel::Warning, &message, Some("Extension is not signed."), &["Install Anyway", "Cancel"], None, cx);
        cx.spawn(async move |workbench, cx| {
            if matches!(answer.await, Ok((0, _))) {
                let _ = workbench.update(cx, |workbench, cx| drop(workbench.install_from_gallery_verifying(id, None, false, false, cx)));
            }
        })
        .detach();
    }

    /// extensionsWorkbenchService.ts `downloadVSIX`: `any` picks the version first (`pickVersionToDownload`), more
    /// than one platform asks for one, then the VSIX goes into the picked folder with the progress in a notification.
    pub(super) fn download_vsix(&mut self, id: String, version_kind: VersionKind, window: &mut Window, cx: &mut Context<Self>) {
        let gallery = self.gallery();
        cx.spawn_in(window, async move |workbench, cx| {
            let mut version = None;
            if version_kind == VersionKind::Any {
                let (all_gallery, all_id) = (gallery.clone(), id.clone());
                let versions = match cx.background_executor().spawn(async move { all_gallery.get_all_versions(&all_id) }).await {
                    Ok(versions) => versions,
                    Err(error) => return workbench.update(cx, |workbench, cx| notify_failure(workbench, format!("{error:#}"), cx)),
                };
                if versions.is_empty() {
                    return cx.update(|window, cx| drop(crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, PromptLevel::Info, "This extension has no other versions.", None, &["OK"], None, cx)));
                }
                let input = version_pick(&versions, None, "Select Version to Download");
                let picked = workbench.update_in(cx, |workbench, window, cx| workbench.choose(input, window, cx))?;
                let Some(picked) = picked.await.ok().and_then(Result::ok).and_then(|picked| picked.as_i64()) else { return Ok(()) };
                version = Some(versions[picked as usize].clone());
            }
            let info = ExtensionInfo { id: id.clone(), version: version.as_ref().map(|version| version.version.clone()), pre_release: version_kind == VersionKind::Prerelease, ..ExtensionInfo::default() };
            let compatible = version.is_none();
            let executor = cx.background_executor().clone();
            let lookup = |target_platform| {
                let (gallery, info) = (gallery.clone(), info.clone());
                executor.spawn(async move {
                    let found = gallery.get_extensions_for_platform(std::slice::from_ref(&info), compatible, target_platform)?;
                    found.into_iter().next().with_context(|| format!("Extension '{}' not found.", info.id))
                })
            };
            let found = match lookup(exthost::gallery::CURRENT_TARGET_PLATFORM).await {
                Ok(found) => found,
                Err(error) => return workbench.update(cx, |workbench, cx| notify_failure(workbench, format!("{error:#}"), cx)),
            };
            let platforms = version.as_ref().map_or(&found.all_target_platforms, |version| &version.target_platforms);
            let mut options: Vec<(&'static str, &str)> = Vec::new();
            for &platform in platforms {
                if platform != exthost::gallery::UNKNOWN && platform != exthost::gallery::UNIVERSAL {
                    options.push((platform, if platform == exthost::gallery::UNDEFINED { "All Platforms" } else { exthost::gallery::target_platform_label(platform) }));
                }
            }
            let mut target_platform = found.target_platform;
            if options.len() > 1 {
                options.sort_by_key(|(_, label)| label.to_lowercase());
                let items = options.iter().enumerate().map(|(handle, (_, label))| Entry::Item(Item { handle: handle as i64, label: (*label).into(), pickable: true, ..Item::default() })).collect();
                let mut input = QuickInput::new(0, Kind::QuickPick);
                input.placeholder = Some("Please select the platform for which you want to download the VSIX".into());
                input.set_items(items);
                let picked = workbench.update_in(cx, |workbench, window, cx| workbench.choose(input, window, cx))?;
                let Some(picked) = picked.await.ok().and_then(Result::ok).and_then(|picked| picked.as_i64()) else { return Ok(()) };
                target_platform = options[picked as usize].0;
            }
            let found = match target_platform == found.target_platform {
                true => found,
                false => match lookup(target_platform).await {
                    Ok(found) => found,
                    Err(error) => return workbench.update(cx, |workbench, cx| notify_failure(workbench, format!("{error:#}"), cx)),
                },
            };
            let file_name = match vsix_file_name(&found.id, &found.version, target_platform) {
                Ok(file_name) => file_name,
                Err(error) => return workbench.update(cx, |workbench, cx| notify_failure(workbench, format!("{error:#}"), cx)),
            };
            let dialog = FileDialog { title: Some("Select folder to download the VSIX".into()), button_label: Some("Download".into()), folders: true, ..FileDialog::default() };
            let picked = workbench.update(cx, |workbench, cx| workbench.show_open_dialog(dialog, cx))?;
            let Some(folder) = picked.await.unwrap_or_default().into_iter().next() else { return Ok(()) };
            let location = folder.join(file_name);
            let mut progress = Notification::new(Severity::Info, "Downloading VSIX...");
            progress.progress = Some(Progress { infinite: true, ..Progress::default() });
            let key = workbench.update(cx, |workbench, cx| {
                cx.notify();
                workbench.notify(progress)
            })?;
            let downloaded = cx.background_executor().spawn(async move { gallery.download_to(&found, &location) }).await;
            workbench.update_in(cx, |workbench, window, cx| {
                if let Some(key) = key {
                    workbench.close_notification(key, window, cx);
                }
                match downloaded {
                    Ok(()) => {
                        workbench.notify(Notification::new(Severity::Info, "Successfully downloaded the VSIX"));
                    }
                    Err(error) => workbench.notify_error(format!("Error while downloading the VSIX: {error:#}")),
                }
                cx.notify();
            })
        })
        .detach();
    }

    /// The gallery the installs query: Open VSX unless a test points `gallery_url` elsewhere.
    pub(super) fn gallery(&self) -> Gallery {
        Gallery { service_url: self.gallery_url.clone(), product_version: crate::VERSION.clone() }
    }

    /// `ExtensionsResource.apply` with a token (userDataProfileImportExport.ts): the gallery extensions of `ids`, one
    /// `requestPublisherTrust` dialog for all their publishers, then `installFromGallery` one at a time with the
    /// progress in a notification. Answers the ids that did not install, each with why.
    pub(crate) fn install_gallery_extensions(&mut self, ids: Vec<String>, window: &mut Window, cx: &mut Context<Self>) -> Task<Vec<(String, String)>> {
        let gallery = self.gallery();
        let infos: Vec<ExtensionInfo> = ids.iter().map(|id| ExtensionInfo { id: id.clone(), ..ExtensionInfo::default() }).collect();
        let lookup = cx.background_executor().spawn(async move { gallery.get_extensions(&infos, false) });
        let mut notification = Notification::new(Severity::Info, "Installing Extensions...");
        notification.progress = Some(Progress { total: Some(ids.len() as f64), worked: Some(0.), ..Progress::default() });
        let progress = self.notify(notification);
        cx.spawn_in(window, async move |workbench, cx| {
            let mut failed = Vec::new();
            let found = match lookup.await {
                Ok(found) => found,
                Err(error) => {
                    failed.extend(ids.iter().map(|id| (id.clone(), format!("{error:#}"))));
                    Vec::new()
                }
            };
            for id in ids.iter().filter(|id| !found.iter().any(|extension| extension.id == **id)) {
                failed.push((id.clone(), format!("The extension '{id}' cannot be installed because it was not found.")));
            }
            let trust = workbench.update(cx, |workbench, cx| workbench.check_trusted_publishers(&found, Vec::new(), cx));
            let trusted = match trust {
                Ok(Ok(None)) => Ok(()),
                Ok(Ok(Some(answer))) => match answer.await.unwrap_or(false) {
                    true => Ok(()),
                    false => Err(super::trusted_publishers::CANCELED.to_owned()),
                },
                Ok(Err(error)) => Err(format!("{error:#}")),
                Err(_) => return failed,
            };
            if let Err(error) = trusted {
                failed.extend(found.iter().map(|extension| (extension.id.clone(), error.clone())));
            } else {
                for (index, extension) in found.iter().enumerate() {
                    let installed = workbench.update(cx, |workbench, cx| {
                        if let Some(item) = progress.and_then(|key| workbench.notifications.model.item_mut(key)) {
                            item.update_message(&format!("Installing extension {}...", extension.display_name_or_id()));
                            item.progress = Some(Progress { total: Some(found.len() as f64), worked: Some(index as f64), ..Progress::default() });
                        }
                        workbench.install_from_gallery(extension.id.clone(), None, false, cx)
                    });
                    let result = match installed {
                        Ok(Outcome::Ready(result)) => result,
                        Ok(Outcome::Pending(pending)) => pending.await.unwrap_or(Ok(Value::Null)),
                        Err(_) => return failed,
                    };
                    if let Err(error) = result {
                        failed.push((extension.id.clone(), error["message"].as_str().unwrap_or_default().to_owned()));
                    }
                }
            }
            if let Some(key) = progress {
                let _ = workbench.update_in(cx, |workbench, window, cx| workbench.close_notification(key, window, cx));
            }
            failed
        })
    }

    /// `MainThreadDownloadService.$download`, downloadService.ts: a file is copied, anything else is fetched with a GET.
    pub(crate) fn download_resource(&mut self, resource: &Value, target: &Value, cx: &mut Context<Self>) -> Outcome {
        let target = match uri_parts(target) {
            Ok((_, path)) => path,
            Err(error) => return Outcome::Ready(Err(error)),
        };
        let part = |key: &str| resource[key].as_str().unwrap_or_default().to_owned();
        let scheme = part("scheme");
        let mut url = format!("{scheme}://{}{}", part("authority"), part("path"));
        if !part("query").is_empty() {
            url += &format!("?{}", part("query"));
        }
        if !part("fragment").is_empty() {
            url += &format!("#{}", part("fragment"));
        }
        let source = PathBuf::from(part("path"));
        let download = cx.background_executor().spawn(async move {
            if scheme != "file" {
                return exthost::request::download(&url, &target).map_err(|error| format!("{error:#}"));
            }
            if target.exists() {
                return Err(format!("Unable to move/copy '{}' because target '{}' already exists at destination.", source.display(), target.display()));
            }
            std::fs::copy(&source, &target).map(drop).map_err(|error| error.to_string())
        });
        let (sender, receiver) = oneshot::channel();
        cx.spawn(async move |_, _| {
            let _ = sender.send(download.await.map(|()| Value::Null).map_err(|error| serialized_error(&error)));
        })
        .detach();
        Outcome::Pending(receiver)
    }

    /// Runs the jobs one after another on the host thread, then reads the contributions of the running extensions.
    /// The first failure is shown and rejects the command, as `onUnexpectedError` and the rethrow upstream do.
    pub(super) fn run_extension_jobs(&mut self, jobs: Vec<Job>, done: Option<&'static str>, cx: &mut Context<Self>, error_text: impl Fn(String) -> String + 'static) -> Outcome {
        let replies: Vec<_> = jobs.into_iter().map(|job| self.host.run_extensions(job)).collect();
        let (sender, receiver) = oneshot::channel();
        cx.spawn(async move |workbench, cx| {
            let mut result = Ok(Value::Null);
            for reply in replies {
                let reply = reply.await.unwrap_or_else(|_| Err("The extension host is not running.".into()));
                let updated = workbench.update(cx, |workbench, cx| {
                    match reply {
                        Ok(running) => workbench.set_running_extensions(running, cx),
                        Err(error) if result.is_ok() => {
                            let error = error_text(error);
                            workbench.notify_error(error.clone());
                            result = Err(serialized_error(&error));
                        }
                        Err(_) => {}
                    }
                    cx.notify();
                });
                if updated.is_err() {
                    return;
                }
            }
            if let (Ok(_), Some(done)) = (&result, done) {
                let _ = workbench.update(cx, |workbench, cx| {
                    drop(workbench.prompt_notification(Severity::Info, done, &[]));
                    cx.notify();
                });
            }
            let _ = sender.send(result);
        })
        .detach();
        Outcome::Pending(receiver)
    }

    /// extensionsWatcher.ts: the profile's `extensions.json` changes when the CLI or another window installs or
    /// uninstalls; this window then starts and stops those extensions.
    pub fn start_extensions_watcher(&mut self, cx: &mut Context<Self>) {
        let (sender, mut receiver) = mpsc::unbounded::<Vec<Change>>();
        let watcher = match Watcher::new(move |changes| drop(sender.unbounded_send(changes))) {
            Ok(watcher) => watcher,
            Err(error) => return eprintln!("[extensions] Error while initializing Extensions Watcher: {error}"),
        };
        self.extensions_viewlet.profile_watcher = Some(watcher);
        self.watch_profile_extensions();
        cx.spawn(async move |workbench, cx| {
            while let Some(changes) = receiver.next().await {
                if workbench.update(cx, |workbench, cx| workbench.profile_extensions_changed(&changes, cx)).is_err() {
                    return;
                }
            }
        })
        .detach();
    }

    /// `onDidChangeProfiles`: the folder of the current profile's `extensions.json`; a profile switch watches the new one.
    pub(super) fn watch_profile_extensions(&mut self) {
        let viewlet = &mut self.extensions_viewlet;
        let (Some(watcher), Some(user)) = (viewlet.profile_watcher.as_mut(), &viewlet.user) else { return };
        watcher.unwatch(0);
        let folder = user.extensions_file.parent().expect("extensions.json has a folder");
        if let Err(error) = watcher.watch(0, folder, false, &[]) {
            eprintln!("[extensions] {}: {error}", folder.display());
        }
    }

    /// `onDidFilesChange`: a change of `extensions.json` reads it again 100 ms after the last one, as the CLI writes it
    /// once per extension.
    pub(super) fn profile_extensions_changed(&mut self, changes: &[Change], cx: &mut Context<Self>) {
        let Some(user) = &self.extensions_viewlet.user else { return };
        if !changes.iter().any(|change| change.path == user.extensions_file) {
            return;
        }
        self.extensions_viewlet.profile_change = Some(cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(Duration::from_millis(100)).await;
            let _ = workbench.update(cx, |workbench, cx| drop(workbench.apply_profile_extensions(cx)));
        }));
    }

    /// `onDidChangeExtensionsByAnotherSource`, then `_handleDeltaExtensions`: the enabled user extensions that do not run
    /// start (replacing another copy of their id), and running user extensions no longer installed stop (a built-in with
    /// their id starts instead). What this window installed itself already runs, so it makes no delta.
    pub(super) fn apply_profile_extensions(&mut self, cx: &mut Context<Self>) -> Outcome {
        // A half-written extensions.json reads as an error; its next change brings the rest.
        if !self.rescan_installed_extensions() {
            return Outcome::done();
        }
        let viewlet = &self.extensions_viewlet;
        let user_folder = viewlet.user.as_ref().expect("a scanned profile").folder.clone();
        let is_user = |extension: &ScannedExtension| extension.location.starts_with(&user_folder);
        let mut to_add = Vec::new();
        let mut to_remove = Vec::new();
        for extension in self.local_extensions() {
            let Some(local) = extension.local else { continue };
            if !extension.enablement.is_enabled() || viewlet.development.iter().any(|id| id.eq_ignore_ascii_case(&local.id)) {
                continue;
            }
            let running = self.extensions.iter().find(|running| running.id.eq_ignore_ascii_case(&local.id));
            match running {
                None if is_user(&local) => to_add.push(local),
                Some(running) if running.location != local.location && (is_user(&local) || is_user(running)) => {
                    to_remove.push(running.id.clone());
                    to_add.push(local);
                }
                _ => {}
            }
        }
        for running in &self.extensions {
            let installed = viewlet.installed.iter().any(|extension| extension.id.eq_ignore_ascii_case(&running.id));
            if is_user(running) && !installed {
                to_remove.push(running.id.clone());
            }
        }
        self.refresh_extensions_views(cx);
        if to_add.is_empty() && to_remove.is_empty() {
            return Outcome::done();
        }
        self.run_extension_jobs(vec![Job::Delta(to_add, to_remove)], None, cx, |error| error)
    }

    /// The extension points the workbench reads, after `_doHandleExtensionPoints` with the running extensions.
    pub(super) fn set_running_extensions(&mut self, running: Vec<ScannedExtension>, cx: &mut Context<Self>) {
        self.languages = crate::languages::Languages::new(&running);
        self.menus = crate::menus::workbench_menus();
        self.menus.extend(crate::menus::extension_menus(&running));
        self.command_icons = crate::menus::command_icons(&running);
        self.submenu_icons = crate::menus::submenu_icons(&running);
        self.set_default_keybindings(crate::keybindings::default_keybindings(&running));
        if let Some(file) = self.keybindings.user_file.clone() {
            self.set_user_keybindings(crate::keybindings::user_keybindings(&file));
        }
        self.set_command_palette_menu(crate::command_palette::menu(&running));
        match crate::theme::color_themes(&running) {
            Ok(themes) => self.color_themes = themes,
            Err(error) => eprintln!("[extensions] reading color themes: {error:#}"),
        }
        self.set_tree_views(&running);
        crate::extension_point_messages::report(&running);
        self.host.set_running_extensions(&running);
        self.extensions = running;
        // workbenchThemeService.ts: a theme registry change restores the themes the settings name, which an install may have brought.
        self.restore_color_theme(cx);
        self.restore_file_icon_theme();
        self.restore_product_icon_theme();
        self.refresh_extensions_views(cx);
        cx.notify();
    }
}

/// `getIdAndVersion`: `[email protected]` or `publisher.name@prerelease`, the id lowercased.
pub(crate) fn id_and_version(arg: &str) -> (String, Option<String>) {
    let split = arg.rsplit_once('@').filter(|(id, version)| {
        let semver = || {
            let core = version.split_once('-').map_or(*version, |(core, _)| core);
            let parts: Vec<&str> = core.split('.').collect();
            parts.len() == 3 && parts.iter().all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
        };
        id.split_once('.').is_some_and(|(publisher, name)| !publisher.is_empty() && !publisher.contains('@') && !name.is_empty()) && (*version == "prerelease" || semver())
    });
    match split {
        Some((id, version)) => (id.to_lowercase(), Some(version.to_owned())),
        None => (arg.to_lowercase(), None),
    }
}

/// The `versionKind` of `downloadVSIX`.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum VersionKind {
    Release,
    Prerelease,
    Any,
}

/// The version pick of `InstallAnotherVersionAction` and `pickVersionToDownload`: each version with how long ago it
/// shipped, `(pre-release)` and `(current)` after it.
fn version_pick(versions: &[GalleryVersion], current: Option<&str>, placeholder: &str) -> QuickInput {
    let now = chrono::Utc::now().timestamp_millis();
    let mut items = Vec::new();
    for (handle, version) in versions.iter().enumerate() {
        let date = chrono::DateTime::parse_from_rfc3339(&version.date).map_or(now, |date| date.timestamp_millis());
        let mut description = crate::timeline::from_now_ago(date, now);
        if version.is_pre_release_version {
            description.push_str(" (pre-release)");
        }
        if current == Some(version.version.as_str()) {
            description.push_str(" (current)");
        }
        items.push(Entry::Item(Item { handle: handle as i64, id: Some(version.version.clone()), label: version.version.clone(), description: Some(description), pickable: true, ..Item::default() }));
    }
    let mut input = QuickInput::new(0, Kind::QuickPick);
    input.placeholder = Some(placeholder.into());
    input.match_on_detail = true;
    input.set_items(items);
    input
}

/// `<id>-<version>[-<platform>].vsix`; the gallery's id and version are untrusted, so a part that is not a plain file
/// name component (empty, `..`, a separator) is rejected before it is joined to the picked folder.
fn vsix_file_name(id: &str, version: &str, target_platform: &str) -> anyhow::Result<String> {
    for part in [id, version] {
        if part.is_empty() || part.contains(['/', '\\']) || part.contains("..") {
            anyhow::bail!("The gallery sent an invalid extension id or version: '{part}'.");
        }
    }
    let suffix = match target_platform {
        exthost::gallery::UNDEFINED | exthost::gallery::UNIVERSAL | exthost::gallery::UNKNOWN => String::new(),
        platform => format!("-{platform}"),
    };
    Ok(format!("{id}-{version}{suffix}.vsix"))
}

fn notify_failure(workbench: &mut Workbench, message: String, cx: &mut Context<Workbench>) {
    workbench.notify_error(message);
    cx.notify();
}

/// The prompt of `installExtension` with a justification: its message, its detail and the install button's label.
fn install_prompt(display_name: &str, publisher_display_name: &str, justification: &Value) -> (String, String, String) {
    let message = format!("Would you like to install '{display_name}' extension from '{publisher_display_name}'?");
    let (detail, label) = match justification {
        Value::String(reason) => (reason.clone(), "Install Extension".to_owned()),
        _ => (
            justification["reason"].as_str().unwrap_or_default().to_owned(),
            justification["action"].as_str().map_or("Install Extension".to_owned(), |action| format!("Install Extension and {action}")),
        ),
    };
    (message, detail, label)
}

#[cfg(test)]
#[test]
fn install_prompt_names_the_justification_action() {
    let uri = serde_json::json!({ "reason": "This extension wants to open a URI:\ncode-oss://a.b/c", "action": "Open URI" });
    let (message, detail, label) = install_prompt("B", "A", &uri);
    assert_eq!(message, "Would you like to install 'B' extension from 'A'?");
    assert_eq!(detail, "This extension wants to open a URI:\ncode-oss://a.b/c");
    assert_eq!(label, "Install Extension and Open URI");
    assert_eq!(install_prompt("B", "A", &Value::from("why")).2, "Install Extension");
}

#[cfg(test)]
#[test]
fn id_and_version_splits_a_version_suffix() {
    assert_eq!(id_and_version("RedHat.vscode-yaml"), ("redhat.vscode-yaml".into(), None));
    assert_eq!(id_and_version("[email protected]"), ("redhat.vscode-yaml".into(), Some("2.0.0".into())));
    assert_eq!(id_and_version("[email protected]"), ("redhat.vscode-yaml".into(), Some("2.0.0-next.1".into())));
    assert_eq!(id_and_version("redhat.vscode-yaml@prerelease"), ("redhat.vscode-yaml".into(), Some("prerelease".into())));
    assert_eq!(id_and_version("redhat.vscode-yaml@latest"), ("redhat.vscode-yaml@latest".into(), None));
}

#[cfg(test)]
mod tests;