Skip to content

Visual Studio Code, rebuilt in Rust

Rust
19.2 KB
Raw Blame
//! The view containers extensions contribute (viewsExtensionPoint.ts `viewsContainers.activitybar` and `panel`) and
//! the tree views of every container (viewsService.ts): the activity bar items of side bar containers with an active
//! view, their side bar, the panel tabs of panel containers (panel.rs), and the `<view id>.focus` and
//! `workbench.view.extension.<id>` commands.

use std::collections::HashMap;
use std::path::PathBuf;

use gpui::{ClickEvent, Context, Div, InteractiveElement, ParentElement, StatefulInteractiveElement, Styled, Window, div, px, svg};
use serde_json::{Value, json};

use super::Workbench;
use super::hover::HoverOptions;
use super::layout::Part;
use super::search_view::SideBarView;
use super::tree_view::static_id;
use super::view_panes::{FILE_VIEW, OUTLINE_VIEW, PaneContainer, TIMELINE_VIEW};
use crate::command_palette::MenuItem;
use crate::commands::Outcome;
use crate::contextkey::Expr;
use crate::notifications::Severity;

pub(super) struct ViewContainer {
    /// `workbench.view.extension.<contributed id>`.
    pub id: &'static str,
    /// The contributed id, the `contributes.views` key of its views.
    pub key: String,
    pub title: String,
    pub icon: ContainerIcon,
    /// The contributed location: `Part::SideBar` for `activitybar`, `Part::Panel` for `panel`.
    pub location: Part,
}

pub(super) enum ContainerIcon {
    Codicon(String),
    File(PathBuf),
}

/// `registerCustomViewContainers` for the activity bar and the panel, in extension order.
pub(super) fn contributed_view_containers(extensions: &[exthost::scan::ScannedExtension]) -> Vec<ViewContainer> {
    let mut containers = Vec::new();
    for (extension, location, descriptor) in valid_view_containers(extensions) {
        let location = match location {
            "activitybar" => Part::SideBar,
            "panel" => Part::Panel,
            _ => continue,
        };
        let (Some(key), Some(title), Some(icon)) = (descriptor["id"].as_str(), descriptor["title"].as_str(), descriptor["icon"].as_str()) else { continue };
        let icon = match icon.strip_prefix("$(").and_then(|name| name.strip_suffix(')')) {
            Some(name) => ContainerIcon::Codicon(name.to_owned()),
            None => ContainerIcon::File(extension.location.join(icon)),
        };
        containers.push(ViewContainer { id: static_id(&format!("workbench.view.extension.{key}")), key: key.to_owned(), title: title.to_owned(), icon, location });
    }
    containers
}

/// viewsExtensionPoint.ts `addCustomViewContainers`: the descriptors of every location whose array passes
/// `isValidViewsContainer`, which reports why the others do not.
pub(super) fn valid_view_containers(extensions: &[exthost::scan::ScannedExtension]) -> Vec<(&exthost::scan::ScannedExtension, &str, &Value)> {
    let mut valid = Vec::new();
    for extension in extensions {
        let Some(locations) = extension.description["contributes"]["viewsContainers"].as_object() else { continue };
        for (location, descriptors) in locations {
            if let Err((severity, message)) = validate_view_containers(descriptors) {
                crate::perf::extension_point_message(&extension.id, severity, message);
                if severity == Severity::Error {
                    continue;
                }
            }
            valid.extend(descriptors.as_array().into_iter().flatten().map(|descriptor| (extension, location.as_str(), descriptor)));
        }
    }
    valid
}

/// viewsExtensionPoint.ts `isValidViewsContainer`; its warning for an empty title keeps the location.
fn validate_view_containers(descriptors: &Value) -> Result<(), (Severity, String)> {
    let Some(descriptors) = descriptors.as_array() else { return Err((Severity::Error, "views containers must be an array".into())) };
    let id_error = "property `id` is mandatory and must be of type `string` with non-empty value. Only alphanumeric characters, '_', and '-' are allowed.";
    for descriptor in descriptors {
        let id = descriptor["id"].as_str().unwrap_or_default();
        if id.is_empty() || !id.chars().all(|char| char.is_ascii_alphanumeric() || char == '_' || char == '-') {
            return Err((Severity::Error, id_error.into()));
        }
        for property in ["title", "icon"] {
            if !descriptor[property].is_string() {
                return Err((Severity::Error, format!("property `{property}` is mandatory and must be of type `string`")));
            }
        }
        if descriptor["title"].as_str().is_some_and(|title| title.trim().is_empty()) {
            return Err((Severity::Warning, "property `title` is mandatory and must be of type `string` with non-empty value".into()));
        }
    }
    Ok(())
}

impl Workbench {
    pub(super) fn register_view_container_commands(&mut self) {
        for container in &self.tree_views.containers {
            let id = container.id;
            if self.commands.get(id).is_none() {
                self.commands.register(id, move |workbench, _, window, cx| {
                    workbench.open_view_container(id, window, cx);
                    Outcome::done()
                });
            }
            // viewsService.ts `registerOpenViewContainerAction`, f1: "Show <title>" in the side bar, else "Toggle <title>".
            let enabled = Expr::deserialize(&format!("viewContainer.{id}.enabled"));
            let verb = if container.location == Part::SideBar { "Show" } else { "Toggle" };
            let title = format!("{verb} {}", container.title);
            self.quick_access.menu.push(MenuItem { id: id.into(), title, category: Some("View".into()), description: None, when: enabled.clone(), precondition: enabled, source: None });
        }
        for view in &self.tree_views.views {
            let id = view.id;
            let command = format!("{id}.focus");
            if self.commands.get(&command).is_none() {
                self.commands.register(command.clone(), move |workbench, _, window, cx| {
                    workbench.open_tree_view(id, true, window, cx);
                    Outcome::done()
                });
            }
            // viewsService.ts `registerFocusViewAction`: "Focus on <name> View", its default container's title as category.
            let category = self.tree_view_default_container(&view.container).map(|(container, _)| self.container_title(container));
            let title = format!("Focus on {} View", view.name);
            self.quick_access.menu.push(MenuItem { id: command, title, category, description: None, when: view.when.clone(), precondition: None, source: None });
        }
    }

    /// viewsService.ts `registerFocusViewAction` of the built-in views: `<view id>.focus` runs `openView(id, true)`.
    /// The panel's views register theirs in `register_panel_view`, the contributed ones above.
    pub(super) fn register_view_focus_commands(&mut self) {
        self.register_open_editors_commands();
        for id in [FILE_VIEW, OUTLINE_VIEW, TIMELINE_VIEW] {
            self.commands.register(format!("{id}.focus"), move |workbench, _, window, cx| {
                let previous_focus = window.focused(cx);
                if !workbench.open_moved_view(id, cx) {
                    drop(workbench.execute_command("workbench.view.explorer", Vec::new(), window, cx));
                    workbench.expand_pane(PaneContainer::Explorer, id, cx);
                }
                // outlinePane.ts `focus` moves to the tree, which a message hides, so the focus stays where it was.
                if id == OUTLINE_VIEW && workbench.active_notebook_editor().is_none() && workbench.outline_message().is_some() {
                    if let Some(previous_focus) = previous_focus {
                        window.focus(&previous_focus, cx);
                    }
                    return Outcome::done();
                }
                let focus = match id {
                    OUTLINE_VIEW => workbench.outline_pane.focus.clone(),
                    TIMELINE_VIEW => workbench.timeline.focus.clone(),
                    _ => workbench.explorer.focus.clone(),
                };
                window.focus(&focus, cx);
                Outcome::done()
            });
        }
        let containers = [
            ("workbench.view.search", "workbench.view.search"),
            ("workbench.scm", "workbench.view.scm"),
            ("workbench.scm.history", "workbench.view.scm"),
            ("workbench.debug.welcome", "workbench.view.debug"),
            ("workbench.view.testing", "workbench.view.testing"),
        ];
        for (view, container) in containers {
            self.commands.register(format!("{view}.focus"), move |workbench, _, window, cx| {
                if !workbench.open_moved_view(view, cx) {
                    return workbench.execute_command(container, Vec::new(), window, cx);
                }
                match view {
                    "workbench.view.search" => workbench.focus_search_input(super::search_view::SearchField::Query, true, window, cx),
                    "workbench.scm" => window.focus(&workbench.scm.input_focus.clone(), cx),
                    _ => {}
                }
                Outcome::done()
            });
        }
        // markers.contribution.ts: "Focus Problems (Errors, Warnings, Infos)" opens the Problems view focused.
        self.commands.register("workbench.action.problems.focus", |workbench, _, window, cx| workbench.execute_command("workbench.panel.markers.view.focus", Vec::new(), window, cx));
        for view in super::extensions_view::VIEW_IDS {
            self.commands.register(format!("{view}.focus"), move |workbench, _, window, cx| {
                workbench.open_extensions_viewlet(window, cx);
                if workbench.extensions_viewlet.panes.iter().any(|pane| pane.descriptor.id == view) {
                    window.focus(&workbench.extensions_viewlet.list_focus.clone(), cx);
                }
                Outcome::done()
            });
        }
    }

    /// `openViewContainer(id, true)` of a contributed container; a panel one that shows with the focus in the panel
    /// closes (`OpenViewContainerAction.run`).
    fn open_view_container(&mut self, id: &'static str, window: &mut Window, cx: &mut Context<Self>) {
        let part = self.container_location(id);
        if part != Part::SideBar {
            let focused = match self.focused_part(window, cx) {
                Some(super::part_navigation::FocusPart::Panel) => Part::Panel,
                Some(super::part_navigation::FocusPart::AuxiliaryBar) => Part::AuxiliaryBar,
                _ => Part::SideBar,
            };
            if self.panel_view_visible(id) && focused == part {
                return self.close_panel_view(id, cx);
            }
            self.show_view_container(id, cx);
        } else {
            self.side_bar_view = SideBarView::Contributed(id);
            self.set_part_hidden(Part::SideBar, false, cx);
        }
        if let Some(first) = self.container_views(id).first().copied() {
            self.focus_tree_view(first, window, cx);
        }
        self.sync_tree_views(cx);
        cx.notify();
    }

    /// `viewsService.openView(id, focus)`: shows the view's container and expands the view.
    pub(super) fn open_tree_view(&mut self, id: &str, focus: bool, window: &mut Window, cx: &mut Context<Self>) {
        let Some(view) = self.tree_views.views.iter().find(|view| view.id == id) else { return };
        let (id, container) = (view.id, view.container.clone());
        if self.open_moved_view(id, cx) {
            if focus {
                self.focus_tree_view(id, window, cx);
            }
            self.sync_tree_views(cx);
            return;
        }
        match container.as_str() {
            "explorer" => {
                drop(self.execute_command("workbench.view.explorer", Vec::new(), window, cx));
                self.expand_pane(PaneContainer::Explorer, id, cx);
            }
            "scm" => {
                drop(self.execute_command("workbench.view.scm", Vec::new(), window, cx));
                self.expand_pane(PaneContainer::Scm, id, cx);
            }
            "debug" => {
                drop(self.execute_command("workbench.view.debug", Vec::new(), window, cx));
                self.expand_pane(PaneContainer::Debug, id, cx);
            }
            "test" => {
                drop(self.execute_command("workbench.view.testing", Vec::new(), window, cx));
                self.expand_pane(PaneContainer::Contributed(super::view_locations::TESTING_CONTAINER), id, cx);
            }
            key => {
                let Some(container) = self.tree_views.containers.iter().find(|container| container.key == key).map(|container| container.id) else { return };
                if self.container_location(container) == Part::SideBar {
                    self.side_bar_view = SideBarView::Contributed(container);
                    self.set_part_hidden(Part::SideBar, false, cx);
                } else {
                    self.show_view_container(container, cx);
                }
                self.expand_pane(PaneContainer::Contributed(container), id, cx);
            }
        }
        if focus {
            self.focus_tree_view(id, window, cx);
        }
        self.sync_tree_views(cx);
        cx.notify();
    }

    fn focus_tree_view(&mut self, id: &'static str, window: &mut Window, cx: &mut Context<Self>) {
        if self.tree_views.views.iter().any(|view| view.id == id && view.webview) {
            return self.focus_webview_view(id, window, cx);
        }
        let focus = self.tree_views.focus.entry(id.to_owned()).or_insert_with(|| cx.focus_handle()).clone();
        window.focus(&focus, cx);
    }

    /// The shown views of a contributed container, by its `workbench.view.extension.<id>` id.
    pub(super) fn container_views(&self, id: &str) -> Vec<&'static str> {
        let Some(container) = self.tree_views.containers.iter().find(|container| container.id == id) else { return Vec::new() };
        self.shown_views_of(&container.key).into_iter().filter(|view| self.stays_in(view, id)).collect()
    }

    /// Whether a contributed view's tree shows: its container visible and the view expanded.
    pub(super) fn tree_view_body_visible(&self, id: &'static str) -> bool {
        let Some(view) = self.tree_views.views.iter().find(|view| view.id == id) else { return false };
        let container = self.movable_view(id).map(|movable| (self.view_container(&movable), movable.default_container));
        if container.is_some_and(|(current, default)| current != default || self.container_location(current) != Part::SideBar) {
            return self.is_view_visible(id);
        }
        if !self.is_part_visible(Part::SideBar) || !self.shown_views_of(&view.container).contains(&id) {
            return false;
        }
        let (shown_container, panes) = match view.container.as_str() {
            "explorer" => (SideBarView::Explorer, PaneContainer::Explorer),
            "scm" => (SideBarView::Scm, PaneContainer::Scm),
            "debug" => (SideBarView::Debug, PaneContainer::Debug),
            "test" => (SideBarView::Testing, PaneContainer::Contributed(super::view_locations::TESTING_CONTAINER)),
            key => match self.tree_views.containers.iter().find(|container| container.key == key) {
                Some(container) => (SideBarView::Contributed(container.id), PaneContainer::Contributed(container.id)),
                None => return false,
            },
        };
        self.side_bar_view == shown_container && self.view_pane_expanded(panes, id)
    }

    /// viewDescriptorService.ts `<view id>.active` of the contributed views.
    pub(super) fn view_containers_context(&self, context: &mut HashMap<String, Value>) {
        for container in &self.tree_views.containers {
            let enabled = self.views_in(container.id).iter().any(|view| self.view_when_holds(view));
            context.insert(format!("viewContainer.{}.enabled", container.id), json!(enabled));
        }
        for view in &self.tree_views.views {
            if view.when.as_ref().is_none_or(|when| when.evaluate(&self.context_keys)) {
                context.insert(format!("{}.active", view.id), json!(true));
            }
        }
    }

    /// The activity bar items of contributed containers with an active view.
    pub(super) fn contributed_activity_items(&self, hover: HoverOptions, window: &Window, cx: &mut Context<Self>) -> Vec<(&'static str, gpui::Stateful<Div>)> {
        let mut items = Vec::new();
        let unpinned = self.unpinned_containers(super::layout::Part::SideBar);
        for container in &self.tree_views.containers {
            if self.container_location(container.id) != Part::SideBar || self.shown_views_of(&container.key).is_empty() || unpinned.iter().any(|id| id == container.id) {
                continue;
            }
            let id = container.id;
            let active = self.side_bar_view == SideBarView::Contributed(id) && self.is_part_visible(Part::SideBar);
            let inactive = self.activity_item_foreground("activity", id, window, cx);
            let icon = match (&container.icon, active) {
                (ContainerIcon::Codicon(name), true) => self.active_view_icon(name),
                (ContainerIcon::Codicon(name), false) => self.inactive_view_icon(name, inactive),
                (ContainerIcon::File(path), _) => {
                    let color = if active { self.color("modernActivityBarItem.activeForeground") } else { inactive };
                    div().w(px(36.)).h(px(36.)).flex().items_center().justify_center().child(svg().external_path(path.to_string_lossy().into_owned()).size(px(24.)).text_color(color))
                }
            };
            let title: &'static str = static_id(&container.title);
            let drag_icon = match &container.icon {
                ContainerIcon::Codicon(name) => self.codicon_svg(name),
                ContainerIcon::File(path) => path.to_string_lossy().into_owned().into(),
            };
            items.push((id, self.activity_composite_item(self.action_bar_item("activity", id, icon.id(id), cx), "activity", id, title, drag_icon, active, cx).relative().children(self.container_activity_badge(id)).cursor_pointer().child(self.action_hover(title, id, hover)).on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| workbench.activity_item_clicked(active, id, event, window, cx)))));
        }
        items
    }

    /// A contributed container's side bar: its views as panes (`view_pane_container`).
    pub(super) fn contributed_side_bar(&self, id: &'static str, window: &Window, cx: &mut Context<Self>) -> Div {
        let title = self.tree_views.containers.iter().find(|container| container.id == id).expect("a contributed container").title.clone();
        self.view_pane_container(PaneContainer::Contributed(id), &title, Vec::new(), window, cx).child(div().h(px(5.)).flex_none())
    }

    /// The shown views of a `contributes.views` key, each with whether it starts collapsed (`"visibility": "collapsed"`).
    pub(super) fn contributed_panes(&self, key: &str) -> Vec<(&'static str, bool)> {
        self.shown_views_of(key).into_iter().map(|id| (id, self.contributed_view_collapsed(id))).collect()
    }

    /// The descriptor's `collapsed` (`visibility: collapsed`), which goes with the view to any container.
    pub(super) fn contributed_view_collapsed(&self, id: &str) -> bool {
        self.tree_views.views.iter().any(|view| view.id == id && view.collapsed)
    }
}

#[cfg(test)]
mod tests;