Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.5 KB
Raw Blame
//! viewQuickAccess.ts: `view ` lists the view containers by location, then their views, the terminals, the debug
//! consoles and the output channels. Open View and Quick Open View (Ctrl+Q) show it.

use std::collections::HashMap;

use gpui::{Context, Window};

use super::Accept;
use crate::filters::{fuzzy_contains, matches_fuzzy_separate};
use crate::quick_input::{Entry, Item};
use crate::workbench::Workbench;
use crate::workbench::debug_commands::REPL_VIEW_ID;
use crate::workbench::debug_view::{DEBUG_CONTAINER, DEBUG_WELCOME_VIEW};
use crate::workbench::layout::Part;
use crate::workbench::view_locations::{MovableView, is_generated_container};
use crate::workbench::view_panes::{OPEN_EDITORS_VIEW, OUTLINE_VIEW, SCM_REPOSITORIES_VIEW, TIMELINE_VIEW};

/// `ViewQuickAccessProvider.PREFIX`.
pub const PREFIX: &str = "view ";
pub const PLACEHOLDER: &str = "Type the name of a view, output channel or terminal to open.";

/// What a view pick opens, besides a terminal.
#[derive(Clone, Debug)]
pub enum ViewTarget {
    /// A container's open command or a view's `<view id>.focus`.
    Command(String),
    /// A debug session whose console shows.
    DebugConsole(String),
    OutputChannel(String),
}

/// `IViewQuickPickItem`.
struct ViewPick {
    label: String,
    container_label: String,
    accept: Accept,
}

impl Workbench {
    /// `_getPicks`: the picks whose label matches the filter or whose container label holds its letters, a separator
    /// before each container's run, `Parent / Child` when the container is itself a pick.
    pub(super) fn view_picks(&self, filter: &str) -> (Vec<Entry>, Vec<Accept>) {
        let mut matched = Vec::new();
        for pick in self.view_pick_items() {
            if filter.is_empty() {
                matched.push((pick, Vec::new()));
                continue;
            }
            let highlights = matches_fuzzy_separate(filter, &pick.label);
            if highlights.is_some() || fuzzy_contains(&pick.container_label, filter) {
                matched.push((pick, highlights.unwrap_or_default()));
            }
        }
        let mut container_of_label = HashMap::new();
        for (pick, _) in &matched {
            container_of_label.entry(pick.label.clone()).or_insert_with(|| pick.container_label.clone());
        }
        let (mut entries, mut accepts) = (Vec::new(), Vec::new());
        let mut last_container = None;
        for (pick, label_highlights) in matched {
            if last_container.as_ref() != Some(&pick.container_label) {
                let separator = match container_of_label.get(&pick.container_label) {
                    Some(parent) => format!("{parent} / {}", pick.container_label),
                    None => pick.container_label.clone(),
                };
                entries.push(Entry::Separator(Some(separator)));
                last_container = Some(pick.container_label);
            }
            entries.push(Entry::Item(Item { handle: accepts.len() as i64, label: pick.label, label_highlights, pickable: true, ..Item::default() }));
            accepts.push(pick.accept);
        }
        if accepts.is_empty() {
            entries = vec![Entry::Item(Item { handle: 0, label: "No matching views".into(), pickable: true, ..Item::default() })];
            accepts = vec![Accept::Nothing];
        }
        (entries, accepts)
    }

    /// `doGetViewPickItems`.
    fn view_pick_items(&self) -> Vec<ViewPick> {
        let command = |label: &str, container_label: &str, command: String| ViewPick { label: label.into(), container_label: container_label.into(), accept: Accept::View(ViewTarget::Command(command)) };
        let mut picks = Vec::new();

        // The containers the composite bars show (`hideIfEmpty` ones while they have a view), the pinned ones first.
        let unpinned = self.unpinned_containers(Part::SideBar);
        let mut side_bar = self.activity_bar_containers();
        side_bar.sort_by_key(|(id, _)| unpinned.iter().any(|other| other == id));
        for (id, title) in side_bar {
            let open = match is_generated_container(id) {
                true => format!("{}.focus", self.generated_container_view(id).expect("a container with a view").id),
                false => id.to_owned(),
            };
            picks.push(command(title, "Side Bar", open));
        }
        for (part, location) in [(Part::Panel, "Panel"), (Part::AuxiliaryBar, "Secondary Side Bar")] {
            for tab in self.part_tabs(part) {
                picks.push(command(tab.title, location, format!("{}.focus", tab.view)));
            }
        }

        // Every view whose `when` holds, by container.
        for (_, container, title) in self.containers_by_location() {
            if container == DEBUG_CONTAINER && self.debug_views().iter().any(|(id, _)| *id == DEBUG_WELCOME_VIEW) {
                picks.push(command("Run", &title, format!("{DEBUG_WELCOME_VIEW}.focus")));
            }
            for view in self.views_in(container) {
                if self.view_when_holds(&view) {
                    picks.push(command(view.name, &title, format!("{}.focus", view.id)));
                }
            }
        }

        for (group_index, group) in self.terminal_view.group_instances().iter().enumerate() {
            for (terminal_index, &id) in group.iter().enumerate() {
                let Some(instance) = self.terminal_view.instance(id) else { continue };
                let label = format!("{}.{}: {}", group_index + 1, terminal_index + 1, instance.title());
                picks.push(ViewPick { label, container_label: "Terminal".into(), accept: Accept::Terminal(id) });
            }
        }

        // debugSession.ts `hasSeparateRepl`.
        for session in &self.debug.sessions {
            if session.parent.is_none() || session.options["repl"] != "mergeWithParent" {
                picks.push(ViewPick { label: session.name.clone(), container_label: "Debug Console".into(), accept: Accept::View(ViewTarget::DebugConsole(session.id.clone())) });
            }
        }

        for channel in &self.output.channels {
            picks.push(ViewPick { label: channel.label.clone(), container_label: "Output".into(), accept: Accept::View(ViewTarget::OutputChannel(channel.id.clone())) });
        }
        picks
    }

    /// The view's `when`, which `allViewDescriptors` keeps whether or not the user hid the view.
    pub(in crate::workbench) fn view_when_holds(&self, view: &MovableView) -> bool {
        match self.tree_views.views.iter().find(|tree_view| tree_view.id == view.id) {
            Some(tree_view) => tree_view.when.as_ref().is_none_or(|when| when.evaluate(&self.context_keys)),
            None if view.id == SCM_REPOSITORIES_VIEW => !self.scm.model.providers.is_empty(),
            None => matches!(view.id, OPEN_EDITORS_VIEW | OUTLINE_VIEW | TIMELINE_VIEW) || self.movable_view_shown(view),
        }
    }

    pub(super) fn accept_view_pick(&mut self, target: ViewTarget, window: &mut Window, cx: &mut Context<Self>) {
        match target {
            ViewTarget::Command(id) => drop(self.execute_command(&id, Vec::new(), window, cx)),
            ViewTarget::DebugConsole(session) => {
                let focus = self.debug.focus_target(Some(&session), None);
                self.set_debug_focus(focus, crate::workbench::debug_service::Reveal::PreservingFocus, window, cx);
                if !self.is_view_visible(REPL_VIEW_ID) {
                    drop(self.execute_command(&format!("{REPL_VIEW_ID}.focus"), Vec::new(), window, cx));
                }
            }
            ViewTarget::OutputChannel(id) => self.show_output_channel(&id, false, window, cx),
        }
    }
}