Visual Studio Code, rebuilt in Rust
Rust
//! View visibility (viewContainerModel.ts `ViewDescriptorsState`, viewDescriptorService.ts
//! `registerViewsVisibilityActionsForContainer`): a view that `canToggleVisibility` is hidden while its container's
//! `<storage id>.hidden` profile state says so, else while it is `hideByDefault` (`"visibility": "hidden"` in
//! `contributes.views`). `<view id>.toggleVisibility` shows or hides it from the container's Views submenu.
// Not ported yet: the ViewContainerTitleContext and ViewTitleContext menus (right click on the title and on pane
// headers) with `<view id>.removeView`, workspace-scoped visibility (`visibleWorkspace`).
use std::collections::HashMap;
use gpui::{Context, Div, MouseButton, MouseDownEvent, Stateful, Window, prelude::*, px};
use serde_json::{Value, json};
use super::Workbench;
use super::view_panes::{FILE_VIEW, OPEN_EDITORS_VIEW, PaneContainer};
use crate::commands::Outcome;
use crate::menus::{MenuAction, MenuId};
#[cfg(test)]
mod tests;
/// A view of a container as its Views submenu lists it.
struct ViewEntry {
id: &'static str,
name: String,
can_toggle: bool,
}
/// `viewContainer.storageId || `${viewContainer.id}.state``.
pub(super) fn container_storage_id(container: &str) -> String {
match container {
"explorer" => "workbench.explorer.views.state".into(),
"scm" => "workbench.scm.views.state".into(),
"debug" => "workbench.view.debug.state".into(),
"search" => "workbench.view.search.state".into(),
"test" => "workbench.view.extension.test.state".into(),
super::extensions_view::VIEWLET_ID => format!("{}.state", super::extensions_view::VIEWLET_ID),
generated if super::view_locations::is_generated_container(generated) => format!("{generated}.state"),
// The panel containers' `storageId`s (markers.contribution.ts, output.contribution.ts, ...).
super::problems_view::MARKERS_CONTAINER_ID | super::output_view::OUTPUT_VIEW_ID | super::terminal_view::TERMINAL_VIEW_ID | super::debug_console::DEBUG_PANEL_ID | super::refactor_preview::REFACTOR_PREVIEW_ID => container.into(),
super::comments_view::COMMENTS_VIEW_ID => "Comments".into(),
super::testing_view::TEST_RESULTS_VIEW_ID => format!("{}.state", super::testing_view::TEST_RESULTS_VIEW_ID),
other => format!("workbench.view.extension.{other}.state"),
}
}
impl Workbench {
/// `isViewDescriptorVisible`: the stored `isHidden`, else `hideByDefault`.
pub(super) fn view_hidden(&self, container: &str, id: &str) -> bool {
let entries = self.views_visibility_state(container);
match entries.iter().find(|entry| entry["id"] == id).and_then(|entry| entry["isHidden"].as_bool()) {
Some(hidden) => hidden,
None => id == OPEN_EDITORS_VIEW || id == super::view_panes::SCM_REPOSITORIES_VIEW || self.tree_views.views.iter().any(|view| view.id == id && view.hide_by_default),
}
}
/// The container's `.hidden` profile state: `{ id, isHidden, order? }` per view it has seen.
pub(super) fn views_visibility_state(&self, container: &str) -> Vec<Value> {
let key = format!("{}.hidden", container_storage_id(container));
let stored = self.profile_storage.lock().unwrap().get(&key).and_then(|raw| serde_json::from_str::<Vec<Value>>(raw).ok());
stored.unwrap_or_default()
}
/// `toggleViewVisibility`: the view's entry flips, the others stay.
pub(super) fn toggle_view_visibility(&mut self, container: &str, id: &str, cx: &mut Context<Self>) {
let hidden = !self.view_hidden(container, id);
let mut entries = self.views_visibility_state(container);
match entries.iter_mut().find(|entry| entry["id"] == id) {
Some(entry) => entry["isHidden"] = json!(hidden),
None => entries.push(json!({ "id": id, "isHidden": hidden })),
}
let key = format!("{}.hidden", container_storage_id(container));
self.profile_storage.lock().unwrap().set(&key, Value::Array(entries).to_string());
cx.notify();
}
/// The view container id of a pane container key.
fn container_id<'a>(&'a self, container: &'a str) -> &'a str {
match container {
"explorer" => super::view_locations::EXPLORER_CONTAINER,
"scm" => super::view_locations::SCM_CONTAINER,
"search" => super::view_locations::SEARCH_CONTAINER,
"debug" => super::debug_view::DEBUG_CONTAINER,
"test" => super::view_locations::TESTING_CONTAINER,
other => self.tree_views.containers.iter().find(|contributed| contributed.key == other).map_or(other, |contributed| contributed.id),
}
}
/// viewMenuActions.ts `ViewContainerMenuActions`: the key context its `MenuId.ViewContainerTitle` is read with.
pub(super) fn view_container_context(&self, container: &str, window: &Window) -> HashMap<String, Value> {
let container_id = self.container_id(container);
let mut context = self.key_context(window);
context.insert("viewContainerLocation".into(), json!(super::view_locations::location_name(self.container_location(container_id))));
context.insert("viewContainer".into(), json!(container_id));
context
}
/// The container's `MenuId.ViewContainerTitle` items outside `navigation`, as its `...` lists them.
pub(super) fn view_container_secondary_menu(&self, context: &HashMap<String, Value>) -> Vec<MenuAction> {
crate::menus::menu_group_actions(&self.menus, MenuId::ViewContainerTitle, context, |group| group != "navigation")
}
/// `activeViewDescriptors` of the container in their order, hidden ones included.
fn container_view_entries(&self, container: &str) -> Vec<ViewEntry> {
let container_id = self.container_id(container);
let mut entries = Vec::new();
for view in self.views_in(container_id) {
// A view lists while its `when` holds, hidden or not.
if self.view_when_holds(&view) {
// explorerViewlet.ts and search.contribution.ts: Folders and Search set `canToggleVisibility: false`.
entries.push(ViewEntry { id: view.id, name: view.name.into(), can_toggle: view.id != FILE_VIEW && view.id != super::view_locations::SEARCH_VIEW });
}
}
entries
}
/// The `ViewsSubMenu` toggles: a view's toggle is disabled while it is the container's last visible one.
pub(super) fn views_submenu(&mut self, container: &'static str) -> Vec<MenuAction> {
for entry in self.container_view_entries(container) {
let command = format!("{}.toggleVisibility", entry.id);
if self.commands.get(&command).is_none() {
let id = entry.id;
self.commands.register(command, move |workbench, _, _, cx| {
workbench.toggle_view_visibility(container, id, cx);
Outcome::done()
});
}
}
self.view_toggles(container)
}
/// The Views submenu's items, their `<view id>.toggleVisibility` commands registered by `views_submenu`.
fn view_toggles(&self, container: &str) -> Vec<MenuAction> {
let entries = self.container_view_entries(container);
let shown: Vec<bool> = entries.iter().map(|entry| !entry.can_toggle || !self.view_hidden(container, entry.id)).collect();
let visible_count = shown.iter().filter(|shown| **shown).count();
let mut actions = Vec::new();
// debugViewlet.ts: Debug Console in group `3_toggleRepl`, before the view toggles, which have no group and sort last.
if self.container_id(container) == super::debug_view::DEBUG_CONTAINER {
let checked = self.panel_view_visible(super::debug_console::DEBUG_PANEL_ID);
actions.push(MenuAction::Command { id: "debug.toggleReplIgnoreFocus".into(), title: "Debug Console".into(), enabled: true, checked, alt: None });
actions.push(MenuAction::Separator);
}
for (entry, &checked) in entries.iter().zip(&shown) {
let enabled = entry.can_toggle && (!checked || visible_count > 1);
actions.push(MenuAction::Command { id: format!("{}.toggleVisibility", entry.id), title: entry.name.clone(), enabled, checked, alt: None });
}
actions
}
/// Whether the Views submenu shows: `getSecondaryActions` drops it while none of its toggles is enabled.
pub(super) fn has_view_toggle(&self, container: &str) -> bool {
self.view_toggles(container).iter().any(|action| matches!(action, MenuAction::Command { enabled: true, .. }))
}
/// The container title's "..." (`MenuId.ViewContainerTitle`): the Views submenu.
pub(super) fn view_container_more_actions(&self, container: &'static str, cx: &mut Context<Self>) -> Stateful<Div> {
let tracked = self.container_more_bounds.clone();
let open = self.context_menu.as_ref().is_some_and(|menu| self.container_more_menu == Some((container, menu.shown)));
self.icon("ellipsis", 22., 16., self.foreground_or("icon.foreground"))
.id(gpui::SharedString::from(format!("{container}-more")))
.debug_selector(move || format!("{container}-more"))
.relative()
.rounded(px(4.))
.when(open, |action| action.bg(self.color("toolbar.activeBackground")))
.cursor_pointer()
.hover(|action| action.bg(self.color("toolbar.hoverBackground")))
.on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _: &MouseDownEvent, window: &mut Window, cx| {
cx.stop_propagation();
workbench.show_views_submenu(container, window, cx);
}))
// Enter and Space on the focused item: gpui's keyboard click.
.on_click(cx.listener(move |workbench, event: &gpui::ClickEvent, window, cx| {
cx.stop_propagation();
if event.is_keyboard() {
workbench.show_views_submenu(container, window, cx);
}
}))
.child(gpui::canvas(move |bounds, _, _| _ = tracked.borrow_mut().insert(container, bounds), |_, _, _, _| {}).absolute().size_full())
.child(self.hover_target(gpui::SharedString::from(format!("{container}-more-hover")), super::hover::HoverContent::Text("Views and More Actions...".into()), super::hover::HoverOptions::action_item()))
}
/// panecomposite.ts `getSecondaryActions`: the Views submenu while one of its toggles is enabled, flat when the
/// container's "..." has nothing else, else before a separator and the merged view's own actions.
fn container_secondary_actions(&mut self, container: &'static str, mut menu_actions: Vec<MenuAction>, view_actions: Vec<MenuAction>) -> Vec<MenuAction> {
let views = self.views_submenu(container);
if views.iter().any(|action| matches!(action, MenuAction::Command { enabled: true, .. })) {
if menu_actions.is_empty() && view_actions.is_empty() {
return views;
}
menu_actions.insert(0, MenuAction::Submenu { title: "Views".into(), actions: views, checked: false });
}
if menu_actions.is_empty() {
return view_actions;
}
if !view_actions.is_empty() {
menu_actions.push(MenuAction::Separator);
menu_actions.extend(view_actions);
}
menu_actions
}
/// The "..." actions of `view`'s title: with the Views submenu while the view is merged with its container
/// (`isViewMergedWithContainer`, the container's one visible view).
pub(super) fn view_secondary_actions(&mut self, view: &str, actions: Vec<MenuAction>) -> Vec<MenuAction> {
let mut containers = vec![PaneContainer::Explorer, PaneContainer::Scm];
containers.extend(self.generated_panes.keys().map(|&container| super::view_locations::pane_container(container)));
let merged = containers.into_iter().find(|&container| self.panes(container).view.as_ref().is_some_and(|panes| panes.ids() == [view]));
match merged {
Some(container) => self.container_secondary_actions(container.key(), Vec::new(), actions),
None => actions,
}
}
/// Below the `...`: compositePart.ts `getTitleAreaDropDownAnchorAlignment` right aligns it, sidebarPart.ts left
/// aligns it in a side bar on the left.
fn show_views_submenu(&mut self, container: &'static str, window: &mut Window, cx: &mut Context<Self>) {
let context = self.view_container_context(container, window);
let menu_actions = self.view_container_secondary_menu(&context);
let actions = self.container_secondary_actions(container, menu_actions, Vec::new());
let anchor = self.container_more_bounds.borrow()[container];
let left_side_bar = self.container_location(self.container_id(container)) == super::layout::Part::SideBar && self.arrangement().side_bar == super::layout::Position::Left;
match left_side_bar {
true => self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx),
false => self.show_dropdown_menu_actions(actions, &context, anchor, Vec::new(), window, cx),
}
self.container_more_menu = Some((container, self.context_menus_shown));
}
}
/// `convertInitialVisibility`: `(hideByDefault, collapsed)` of a `contributes.views` entry.
pub(super) fn initial_visibility(view: &Value) -> (bool, bool) {
match view["visibility"].as_str() {
Some("hidden") => (true, false),
Some("collapsed") => (false, true),
_ => (false, false),
}
}