Skip to content

Visual Studio Code, rebuilt in Rust

Rust
14.9 KB
Raw Blame
//! debugConfigurationManager.ts dynamic configurations: the types whose provider registered with
//! `DebugConfigurationProviderTriggerKind.Dynamic` or that an `onDebugDynamicConfigurations` activation event names,
//! the picker of their configurations, and the recently used ones in workspace storage.

use std::path::PathBuf;

use gpui::{AsyncWindowContext, Context, WeakEntity, Window};
use serde_json::{Value, json};

use super::Workbench;
use super::debug_service::{BUTTON_ANSWER, answer, on_workbench};
use super::debug_task_runner::DebugTasks;
use crate::quick_input::{Button, Entry, Item};

/// debugStorage.ts `DEBUG_RECENT_DYNAMIC_CONFIGURATIONS`.
const RECENT_KEY: &str = "debug.recentdynamicconfigurations";
const ACTIVATION_EVENT: &str = "onDebugDynamicConfigurations";
/// `DebugConfigurationProviderTriggerKind.Dynamic`.
pub(super) const DYNAMIC: i64 = 2;

/// A `getLaunches()` entry: a folder's launch.json, the `.code-workspace` file's `launch`, or the user settings'.
#[derive(Clone, Debug, PartialEq)]
pub(super) enum Launch {
    Folder(PathBuf),
    Workspace(PathBuf),
    User,
}

impl Launch {
    /// The folder `startDebugging` takes: `launch.workspace`, only a folder's launch has one.
    pub(super) fn folder(&self) -> Option<PathBuf> {
        match self {
            Launch::Folder(folder) => Some(folder.clone()),
            Launch::Workspace(_) | Launch::User => None,
        }
    }

    /// `launch.name`.
    fn name(&self) -> String {
        match self {
            Launch::Folder(folder) => folder.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(),
            Launch::Workspace(_) => "workspace".into(),
            Launch::User => "user settings".into(),
        }
    }
}

impl Workbench {
    /// `getDynamicProviders`: each type with its debugger's label.
    pub(super) fn dynamic_providers(&self) -> Vec<(String, String)> {
        let mut types: Vec<String> = Vec::new();
        for extension in &self.extensions {
            let events = exthost::activation_events::read_activation_events(&extension.id, &extension.description);
            let explicit: Vec<String> = events.iter().filter_map(|event| event.strip_prefix(ACTIVATION_EVENT)?.strip_prefix(':')).map(str::to_owned).collect();
            if !explicit.is_empty() {
                types.extend(explicit);
            } else if events.iter().any(|event| event == ACTIVATION_EVENT)
                && let Some(debug_type) = extension.description["contributes"]["debuggers"][0]["type"].as_str()
            {
                types.push(debug_type.to_owned());
            }
        }
        types.extend(self.debug.providers.iter().filter(|provider| provider.trigger_kind == DYNAMIC).map(|provider| provider.debug_type.clone()));
        let mut providers: Vec<(String, String)> = Vec::new();
        for debug_type in types {
            if providers.iter().any(|(known, _)| *known == debug_type) {
                continue;
            }
            // `getDebuggerLabel(type)!`: a type no debugger contributes has no label to show.
            let Some(debugger) = self.debug.debugger(&debug_type) else { continue };
            let label = debugger.label().to_owned();
            providers.push((debug_type, label));
        }
        providers
    }

    /// `getLaunches()`: the folders', the workspace file's in a workspace window, then the user settings'.
    fn launches(&self) -> Vec<Launch> {
        let mut launches: Vec<Launch> = self.workspace_folders().into_iter().map(Launch::Folder).collect();
        if let Some(file) = self.workspace().and_then(|workspace| workspace.file.clone()) {
            launches.push(Launch::Workspace(file));
        }
        launches.push(Launch::User);
        launches
    }

    /// `getRecentDynamicConfigurations`: (name, type), the most recent first.
    pub(super) fn recent_dynamic_configurations(&self) -> Vec<(String, String)> {
        let stored = self.workspace_storage.lock().unwrap().get(RECENT_KEY).and_then(|raw| serde_json::from_str::<Value>(raw).ok()).unwrap_or_default();
        let entries = stored.as_array().cloned().unwrap_or_default();
        entries.iter().filter_map(|entry| Some((entry["name"].as_str()?.to_owned(), entry["type"].as_str()?.to_owned()))).collect()
    }

    fn store_recent_dynamic_configurations(&mut self, recent: &[(String, String)]) {
        let stored = Value::Array(recent.iter().map(|(name, debug_type)| json!({ "name": name, "type": debug_type })).collect());
        self.workspace_storage.lock().unwrap().set(RECENT_KEY, stored.to_string());
    }

    /// `removeRecentDynamicConfigurations`.
    pub(super) fn remove_recent_dynamic_configuration(&mut self, name: &str, debug_type: &str) {
        let mut recent = self.recent_dynamic_configurations();
        recent.retain(|(known_name, known_type)| known_name != name || known_type != debug_type);
        self.store_recent_dynamic_configurations(&recent);
    }

    /// `selectConfiguration(launch, name, config, { type })`: the name selected under the provider's type and put
    /// first in the recent list.
    fn select_dynamic_configuration(&mut self, folder: Option<PathBuf>, name: String, debug_type: String) {
        let mut recent = self.recent_dynamic_configurations();
        recent.retain(|(known_name, known_type)| *known_name != name || *known_type != debug_type);
        recent.insert(0, (name.clone(), debug_type.clone()));
        self.store_recent_dynamic_configurations(&recent);
        self.debug.selected = Some((folder, name));
        self.debug.selected_type = Some(debug_type);
        self.store_selected_configuration();
    }

    /// debugQuickAccess.ts: a provider's `{label}...` pick, the provider's picker, then the chosen configuration
    /// selected under the provider's type and started.
    pub(super) fn pick_dynamic_and_start(&mut self, debug_type: String, window: &mut Window, cx: &mut Context<Self>) {
        cx.spawn_in(window, async move |this, cx| {
            let Ok(Some((folder, config))) = pick_dynamic_configuration(&this, cx, debug_type.clone()).await else { return };
            let _ = on_workbench(&this, cx, |workbench, window, cx| {
                let name = config["name"].as_str().unwrap_or_default().to_owned();
                // The provider's type, not the config's: a config can have a subtype such as `node-terminal`.
                workbench.select_dynamic_configuration(folder.clone(), name, debug_type);
                drop(workbench.start_debugging(folder, config, json!({ "startedByUser": true }), DebugTasks::PreLaunch, window, cx));
            });
        })
        .detach();
    }

    /// debugQuickAccess.ts: a recent dynamic configuration's pick, selected then started with the configuration
    /// the type's provider gives the selected folder under that name (`selectedConfiguration.getConfig()`).
    pub(super) fn start_recent_dynamic(&mut self, name: String, debug_type: String, window: &mut Window, cx: &mut Context<Self>) {
        let (folder, _) = self.selected_launch();
        self.select_dynamic_configuration(folder.clone(), name.clone(), debug_type.clone());
        self.start_dynamic(folder, name, debug_type, json!({ "startedByUser": true }), window, cx);
    }

    /// The selected launch's dynamic selection, when launch.json has no configuration of its name
    /// (debugConfigurationManager.ts `selectConfiguration` asks the type's providers then).
    pub(super) fn selected_dynamic(&self) -> Option<(Option<PathBuf>, String, String)> {
        let (root, name) = self.debug.selected.clone()?;
        let debug_type = self.debug.selected_type.clone()?;
        let folder = root.or_else(|| self.workspace_folders().first().cloned());
        let in_launch_json = folder.as_ref().is_some_and(|folder| self.folder_launch(folder).configuration_names().contains(&name));
        (!in_launch_json).then_some((folder, name, debug_type))
    }

    /// `selectedConfiguration.getConfig()` of a dynamic selection: the type's provider's configuration of that name
    /// for the folder, started with `options`.
    pub(super) fn start_dynamic(&mut self, folder: Option<PathBuf>, name: String, debug_type: String, options: Value, window: &mut Window, cx: &mut Context<Self>) {
        let launches: Vec<Launch> = folder.clone().map(Launch::Folder).into_iter().collect();
        cx.spawn_in(window, async move |this, cx| {
            let configurations = match provide_dynamic_configurations(&this, cx, &debug_type, launches).await {
                Ok(configurations) => configurations,
                Err(message) => return drop(on_workbench(&this, cx, |workbench, _, _| workbench.notify_error(message))),
            };
            let config = configurations.into_iter().map(|(_, config)| config).find(|config| config["name"].as_str() == Some(&name));
            let _ = on_workbench(&this, cx, |workbench, window, cx| drop(workbench.start_debugging(folder, config.unwrap_or(Value::Null), options, DebugTasks::PreLaunch, window, cx)));
        })
        .detach();
    }
}

/// `provider.pick()`: the type's configurations of each launch in "Select Launch Configuration", answered with the
/// launch's folder; a pick's gear writes it to its launch and selects it there instead.
pub(super) async fn pick_dynamic_configuration(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, debug_type: String) -> Result<Option<(Option<PathBuf>, Value)>, String> {
    let configurations = dynamic_configurations(this, cx, &debug_type).await?;
    let mut entries = Vec::new();
    for (handle, (launch, config)) in configurations.iter().enumerate() {
        let button = Button { handle: 0, codicon: Some("gear".into()), tooltip: Some("Edit Debug Configuration in launch.json".into()), ..Button::default() };
        let label = config["name"].as_str().unwrap_or_default().to_owned();
        entries.push(Entry::Item(Item { handle: handle as i64, label, description: Some(launch.name()), pickable: true, buttons: vec![button], ..Item::default() }));
    }
    let picked = on_workbench(this, cx, |workbench, window, cx| workbench.debug_pick("Select Launch Configuration", entries, window, cx))?;
    let Some(picked) = picked.await.ok().flatten() else { return Ok(None) };
    if let Some(button) = picked.strip_prefix(BUTTON_ANSWER) {
        let (launch, config) = configurations[button.parse::<usize>().expect("an item handle")].clone();
        on_workbench(this, cx, |workbench, window, cx| workbench.write_dynamic_configuration(launch, &debug_type, config, window, cx))?;
        return Ok(None);
    }
    let (launch, config) = configurations[picked.parse::<usize>().expect("an item handle")].clone();
    Ok(Some((launch.folder(), config)))
}

/// `getDynamicConfigurationsByType`: each launch's configurations from the type's dynamic provider.
pub(super) async fn dynamic_configurations(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, debug_type: &str) -> Result<Vec<(Launch, Value)>, String> {
    let launches = on_workbench(this, cx, |workbench, _, _| workbench.launches())?;
    provide_dynamic_configurations(this, cx, debug_type, launches).await
}

/// `provideDebugConfigurations` of the type's dynamic provider for each launch, after its `onDebugDynamicConfigurations`
/// activation.
async fn provide_dynamic_configurations(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, debug_type: &str, launches: Vec<Launch>) -> Result<Vec<(Launch, Value)>, String> {
    let events = on_workbench(this, cx, |workbench, _, _| {
        workbench.debug.init_extension_activations();
        [ACTIVATION_EVENT.to_owned(), "onDebug".to_owned(), format!("{ACTIVATION_EVENT}:{debug_type}")].map(|event| workbench.host.activate_by_event(&event))
    })?;
    for event in events {
        let _ = event.await;
    }
    let handle = on_workbench(this, cx, |workbench, _, _| {
        let provider = workbench.debug.providers.iter().find(|provider| provider.debug_type == debug_type && provider.trigger_kind == DYNAMIC && provider.has_provide);
        provider.map(|provider| provider.handle)
    })?;
    let Some(handle) = handle else { return Ok(Vec::new()) };
    let mut configurations = Vec::new();
    for launch in launches {
        let uri = launch.folder().map_or(Value::Null, |folder| exthost::scan::file_uri(&folder));
        let reply = on_workbench(this, cx, |workbench, _, _| workbench.host.call("ExtHostDebugService", "$provideDebugConfigurations", vec![json!(handle), uri]))?;
        let provided = answer(reply).await?;
        configurations.extend(provided.as_array().into_iter().flatten().map(|config| (launch.clone(), config.clone())));
    }
    Ok(configurations)
}

impl Workbench {
    /// The picker's gear: `launch.openConfigFile`, `writeConfiguration`, then the written configuration selected by
    /// name and dropped from the recent list.
    fn write_dynamic_configuration(&mut self, launch: Launch, debug_type: &str, config: Value, window: &mut Window, cx: &mut Context<Self>) {
        let outcome = match &launch {
            Launch::Folder(folder) => self.open_folder_launch_json(folder, window, cx),
            Launch::Workspace(file) => {
                self.open_file(file.clone(), true, window, cx);
                crate::commands::Outcome::done()
            }
            Launch::User => self.execute_command("workbench.action.openSettingsJson", vec![json!({ "revealSetting": { "key": "launch" } })], window, cx),
        };
        super::quick_access::show_failure("Edit Debug Configuration in launch.json".into(), outcome, window, cx);
        let name = config["name"].as_str().unwrap_or_default().to_owned();
        let folder = launch.folder();
        let overrides = config::configuration::Overrides { resource: folder.as_deref(), override_identifier: None };
        let mut settings = self.settings.lock().unwrap();
        let inspected = settings.configuration.inspect("launch", &overrides);
        let (target, layer) = match &launch {
            Launch::Folder(_) => (config::service::Target::WorkspaceFolder, inspected.workspace_folder),
            Launch::Workspace(_) => (config::service::Target::Workspace, inspected.workspace),
            Launch::User => (config::service::Target::User, inspected.user_local),
        };
        let mut launch_value = layer.value.unwrap_or_else(|| json!({}));
        let mut configurations = launch_value["configurations"].as_array().cloned().unwrap_or_default();
        configurations.push(config);
        launch_value["configurations"] = Value::Array(configurations);
        let written = settings.update_value("launch", Some(&launch_value), target, folder.as_deref(), &[]);
        if let Ok(change) = &written
            && !change.is_empty()
        {
            self.host.send_configuration_change(&settings, change);
        }
        drop(settings);
        if let Err(error) = written {
            return self.notify_error(error);
        }
        self.debug.selected = Some((folder, name.clone()));
        self.debug.selected_type = None;
        self.store_selected_configuration();
        self.remove_recent_dynamic_configuration(&name, debug_type);
    }
}