Skip to content

Visual Studio Code, rebuilt in Rust

Rust
8.0 KB
Raw Blame
//! debugQuickAccess.ts `StartDebugQuickAccessProvider`: `debug ` lists the launch configurations, the most recent
//! first, and an Add Configuration pick per folder. Debug: Select and Start Debugging shows it.

use std::path::PathBuf;

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

use super::Accept;
use crate::debug::configuration::compare_presentation;
use crate::filters::matches_fuzzy_separate;
use crate::quick_input::{Button, Entry, Item};
use crate::workbench::Workbench;
use crate::workbench::debug_task_runner::DebugTasks;

/// debugCommands.ts `DEBUG_QUICK_ACCESS_PREFIX`.
pub const PREFIX: &str = "debug ";
pub const PLACEHOLDER: &str = "Type the name of a launch configuration to run.";

/// What a `debug ` pick does.
#[derive(Clone, Debug)]
pub enum DebugPick {
    /// A launch configuration of the folder, started on accept; its gear button opens the folder's launch.json.
    Launch { folder: PathBuf, name: String },
    AddConfiguration(PathBuf),
    /// A recently used dynamic configuration; its trash button drops it from the recent list.
    RecentDynamic { name: String, debug_type: String },
    /// A dynamic configuration provider's `{label}...`, its type's picker on accept.
    Dynamic(String),
}

impl Workbench {
    /// `_getPicks`.
    pub(super) fn debug_picks(&self, filter: &str) -> (Vec<Entry>, Vec<Accept>) {
        let (mut entries, mut accepts) = (Vec::new(), Vec::new());
        if self.debug.debuggers.is_empty() {
            // pickerQuickAccess.ts: the `noResultsPick` only for a typed filter.
            if !filter.is_empty() {
                entries.push(Entry::Item(Item { handle: 0, label: "No matching launch configurations".into(), pickable: true, ..Item::default() }));
                accepts.push(Accept::Nothing);
            }
            return (entries, accepts);
        }
        let multi_root = self.workspace().is_some_and(|workspace| workspace.file.is_some());
        let folder_name = |folder: &PathBuf| folder.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
        let folders = self.workspace_folders();
        let mut configurations: Vec<(PathBuf, Value)> = Vec::new();
        for folder in &folders {
            let launch = self.folder_launch(folder);
            for config in launch.configurations.into_iter().chain(launch.compounds) {
                if config["presentation"]["hidden"] != true && config["name"].is_string() {
                    configurations.push((folder.clone(), config));
                }
            }
        }
        configurations.sort_by(|(_, first), (_, second)| compare_presentation(&first["presentation"], &second["presentation"]));

        let (selected_folder, selected_name) = self.selected_launch();
        let mut most_recent = None;
        entries.push(Entry::Separator(Some("launch.json".into())));
        let mut last_group = None;
        for (folder, config) in configurations {
            let name = config["name"].as_str().expect("filtered above").to_owned();
            let Some(label_highlights) = matches_fuzzy_separate(filter, &name) else { continue };
            let item = Item {
                handle: 0,
                label: name.clone(),
                description: multi_root.then(|| folder_name(&folder)),
                label_highlights,
                pickable: true,
                buttons: vec![Button { handle: 0, codicon: Some("gear".into()), tooltip: Some("Configure Launch Configuration".into()), ..Button::default() }],
                ..Item::default()
            };
            let accept = Accept::Debug(DebugPick::Launch { folder: folder.clone(), name: name.clone() });
            if selected_name.as_ref() == Some(&name) && selected_folder.as_ref() == Some(&folder) {
                most_recent = Some((item, accept));
                continue;
            }
            let group = config["presentation"]["group"].as_str().map(str::to_owned);
            if last_group != group {
                entries.push(Entry::Separator(None));
                last_group = group;
            }
            entries.push(Entry::Item(item));
            accepts.push(accept);
        }
        if let Some((item, accept)) = most_recent {
            entries.splice(0..0, [Entry::Separator(Some("Most Recent".into())), Entry::Item(item)]);
            accepts.insert(0, accept);
        }

        let dynamic = self.dynamic_providers();
        if !dynamic.is_empty() {
            entries.push(Entry::Separator(Some("contributed".into())));
        }
        for (name, debug_type) in self.recent_dynamic_configurations() {
            let Some(label_highlights) = matches_fuzzy_separate(filter, &name) else { continue };
            let button = Button { handle: 0, codicon: Some("trash".into()), tooltip: Some("Remove Launch Configuration".into()), ..Button::default() };
            entries.push(Entry::Item(Item { handle: 0, label: name.clone(), label_highlights, pickable: true, buttons: vec![button], ..Item::default() }));
            accepts.push(Accept::Debug(DebugPick::RecentDynamic { name, debug_type }));
        }
        for (debug_type, label) in dynamic {
            entries.push(Entry::Item(Item { handle: 0, label: format!("$(folder) {label}..."), pickable: true, ..Item::default() }));
            accepts.push(Accept::Debug(DebugPick::Dynamic(debug_type)));
        }

        if !folders.is_empty() {
            entries.push(Entry::Separator(Some("configure".into())));
        }
        for folder in folders {
            let label = match multi_root {
                true => format!("Add Config ({})...", folder_name(&folder)),
                false => "Add Configuration...".to_owned(),
            };
            let label_highlights = matches_fuzzy_separate(filter, &label).unwrap_or_default();
            entries.push(Entry::Item(Item { handle: 0, label, description: multi_root.then(|| folder_name(&folder)), label_highlights, pickable: true, ..Item::default() }));
            accepts.push(Accept::Debug(DebugPick::AddConfiguration(folder)));
        }

        let mut handle = 0;
        for entry in &mut entries {
            if let Entry::Item(item) = entry {
                item.handle = handle;
                handle += 1;
            }
        }
        (entries, accepts)
    }

    /// The pick's `accept`: `selectConfiguration`, then `startDebugging` with `startedByUser`.
    pub(super) fn accept_debug_pick(&mut self, pick: DebugPick, window: &mut Window, cx: &mut Context<Self>) {
        match pick {
            DebugPick::Launch { folder, name } => {
                self.debug.selected = Some((Some(folder.clone()), name.clone()));
                self.debug.selected_type = None;
                self.store_selected_configuration();
                drop(self.start_debugging(Some(folder), json!(name), json!({ "startedByUser": true }), DebugTasks::PreLaunch, window, cx));
            }
            // `ADD_CONFIGURATION_ID` with the folder's launch.json.
            DebugPick::AddConfiguration(folder) => {
                let outcome = self.open_folder_launch_json(&folder, window, cx);
                super::show_failure("Add Configuration...".into(), outcome, window, cx);
            }
            DebugPick::RecentDynamic { name, debug_type } => self.start_recent_dynamic(name, debug_type, window, cx),
            DebugPick::Dynamic(debug_type) => self.pick_dynamic_and_start(debug_type, window, cx),
        }
    }

    /// A button's `trigger`, then `TriggerAction.CLOSE_PICKER`: the gear runs `launch.openConfigFile`, the trash
    /// `removeRecentDynamicConfigurations`.
    pub(super) fn trigger_debug_pick(&mut self, pick: DebugPick, window: &mut Window, cx: &mut Context<Self>) {
        match pick {
            DebugPick::Launch { folder, .. } => {
                let outcome = self.open_folder_launch_json(&folder, window, cx);
                super::show_failure("Configure Launch Configuration".into(), outcome, window, cx);
            }
            DebugPick::RecentDynamic { name, debug_type } => self.remove_recent_dynamic_configuration(&name, &debug_type),
            DebugPick::AddConfiguration(_) | DebugPick::Dynamic(_) => {}
        }
    }
}