Skip to content

Visual Studio Code, rebuilt in Rust

Rust
42.9 KB
Raw Blame
//! activitybarPart.ts `fillContextMenuActions`: the activity bar's context menu. compositeBar.ts `getContextMenuActions`
//! lists the view containers, checked while pinned, then globalCompositeBar.ts's Accounts toggle and
//! `getActivityBarContextMenuActions`.

use std::collections::HashMap;

use gpui::{App, AppContext, Bounds, Context, Div, DragMoveEvent, InteractiveElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Point, SharedString, Stateful, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px};
use serde_json::{Value, json};

use super::Workbench;
use super::layout::Part;
use super::panel::DraggedComposite;
use super::search_view::SideBarView;
use super::side_bar::VIEW_CONTAINERS;
use super::view_locations::{TESTING_CONTAINER, location_code};
use crate::commands::Outcome;
use crate::menus::{MenuAction, MenuId, menu_actions};

/// compositeBar.ts `CompositeBarModel` items, stored by paneCompositeBar.ts as `{ id, pinned, visible }`.
const PINNED_CONTAINERS_KEY: &str = "workbench.activity.pinnedViewlets2";
const PINNED_PANELS_KEY: &str = "workbench.panel.pinnedPanels";
const PINNED_AUXILIARY_KEY: &str = "workbench.auxiliarybar.pinnedPanels";
/// globalCompositeBar.ts `ACCOUNTS_VISIBILITY_PREFERENCE_KEY`.
const ACCOUNTS_VISIBILITY_KEY: &str = "workbench.activity.showAccounts";
/// viewDescriptorService.ts `viewContainerBadgeEnablementStates` of `views.customizations`.
const BADGE_STATES: &str = "viewContainerBadgeEnablementStates";
/// paneCompositeBar.ts `moveViewContainerTo${location}` and `resetLocationAction`, run with the item's id
/// (`getActionsContext`).
const MOVE_CONTAINER_PREFIX: &str = "moveViewContainerTo";
const RESET_LOCATION: &str = "resetLocationAction";
/// compositeBarActions.ts `ToggleCompositePinnedAction` and `ToggleCompositeBadgeAction`, run with the item's id.
const TOGGLE_COMPOSITE_PINNED: &str = "show.toggleCompositePinned";
const TOGGLE_COMPOSITE_BADGE: &str = "show.toggleCompositeBadge";
const PANEL_SHOW_LABELS: &str = "workbench.action.panel.toggleShowLabels";
const AUXILIARY_BAR_SHOW_LABELS: &str = "workbench.action.auxiliarybar.toggleShowLabels";
/// The Testing activity item's id, its open command; its container is `TESTING_CONTAINER`.
const TESTING_ITEM: &str = "workbench.view.testing";

fn pinned_key(part: Part) -> &'static str {
    match part {
        Part::Panel => PINNED_PANELS_KEY,
        Part::AuxiliaryBar => PINNED_AUXILIARY_KEY,
        _ => PINNED_CONTAINERS_KEY,
    }
}

/// The command of a bar's pin toggle for `id`; upstream's is an action without a command (`getContextMenuActions`).
fn toggle_pinned_command(part: Part, id: &str) -> String {
    let bar = match part {
        Part::Panel => "panel",
        Part::AuxiliaryBar => "auxiliaryBar",
        _ => "activityBar",
    };
    format!("workbench.action.{bar}.togglePinned.{id}")
}

/// `openCommandActionDescriptor.id` of the containers that have one (viewContainerModel.ts `keybindingId`).
fn container_open_command(container: &'static str) -> Option<&'static str> {
    match container {
        "workbench.view.explorer" | "workbench.view.debug" | "workbench.view.extensions" => Some(container),
        // views.ts `registerViewContainer` gives an extension's container `{ id: viewContainer.id }`, Testing's included.
        extension if extension.starts_with("workbench.view.extension.") => Some(extension),
        _ => None,
    }
}

/// `openCommandActionDescriptor.id` of the views that have one: a container without its own takes its first view's.
fn view_open_command(view: &str) -> Option<&'static str> {
    match view {
        super::view_locations::SEARCH_VIEW => Some("workbench.view.search"),
        super::view_panes::SCM_CHANGES_VIEW => Some("workbench.view.scm"),
        super::problems_view::MARKERS_VIEW_ID => Some("workbench.actions.view.problems"),
        super::output_view::OUTPUT_VIEW_ID => Some("workbench.action.output.toggleOutput"),
        super::debug_commands::REPL_VIEW_ID => Some("workbench.debug.action.toggleRepl"),
        super::terminal_view::TERMINAL_VIEW_ID => Some("workbench.action.terminal.toggleTerminal"),
        _ => None,
    }
}

fn composite_container(item: &'static str) -> &'static str {
    if item == TESTING_ITEM { TESTING_CONTAINER } else { item }
}

fn before_in(bar: &str, bounds: Bounds<Pixels>, pointer: Point<Pixels>) -> bool {
    if bar == "activity" { pointer.y <= bounds.center().y } else { pointer.x <= bounds.center().x }
}

fn composite_arg(args: &[Value]) -> Option<&'static str> {
    args.first().and_then(Value::as_str).map(super::tree_view::static_id)
}

impl Workbench {
    /// The containers the activity bar can show (`visibleItems`), pinned or not, in its order: id and title.
    pub(super) fn activity_bar_containers(&self) -> Vec<(&'static str, &'static str)> {
        let mut containers: Vec<_> = VIEW_CONTAINERS.into_iter().filter(|(_, _, _, command, _)| !self.container_hidden_if_empty(command) && self.container_location(command) == super::layout::Part::SideBar).map(|(_, _, title, command, _)| (command, title)).collect();
        if self.testing_container_shown() && self.container_location(super::view_locations::TESTING_CONTAINER) == super::layout::Part::SideBar {
            containers.push(("workbench.view.testing", "Testing"));
        }
        for container in &self.tree_views.containers {
            if self.container_location(container.id) == super::layout::Part::SideBar && !self.shown_views_of(&container.key).is_empty() {
                containers.push((container.id, super::tree_view::static_id(&container.title)));
            }
        }
        for id in self.generated_containers_in(super::layout::Part::SideBar) {
            containers.push((id, super::tree_view::static_id(&self.container_title(id))));
        }
        self.in_bar_order(Part::SideBar, containers, |(id, _)| id)
    }

    /// The composite bar's items, pinned or not: id and title.
    fn bar_items(&self, part: Part) -> Vec<(&'static str, &'static str)> {
        match part {
            Part::SideBar => self.activity_bar_containers(),
            _ => self.part_composites(part).into_iter().map(|tab| (tab.id, tab.title)).collect(),
        }
    }

    /// The containers unpinned from the part's composite bar.
    pub(super) fn unpinned_containers(&self, part: Part) -> Vec<String> {
        self.stored_bar_items(part).into_iter().filter(|item| item["pinned"] == false).filter_map(|item| item["id"].as_str().map(str::to_owned)).collect()
    }

    fn stored_bar_items(&self, part: Part) -> Vec<Value> {
        let storage = self.profile_storage.lock().unwrap();
        storage.get(pinned_key(part)).and_then(|stored| serde_json::from_str(stored).ok()).unwrap_or_default()
    }

    /// `CompositeBarModel.items` order: the stored items take the places they hold among `items` in their stored
    /// order, the others keep their registration place.
    pub(super) fn in_bar_order<T>(&self, part: Part, items: Vec<T>, id: impl Fn(&T) -> &str) -> Vec<T> {
        let stored: Vec<String> = self.stored_bar_items(part).into_iter().filter_map(|item| item["id"].as_str().map(str::to_owned)).collect();
        let stored_index = |item: &T| stored.iter().position(|other| other == id(item));
        let slots: Vec<usize> = (0..items.len()).filter(|index| stored_index(&items[*index]).is_some()).collect();
        let mut by_stored = slots.clone();
        by_stored.sort_by_key(|index| stored_index(&items[*index]));
        let mut order: Vec<usize> = (0..items.len()).collect();
        for (slot, index) in slots.into_iter().zip(by_stored) {
            order[slot] = index;
        }
        let mut items: Vec<Option<T>> = items.into_iter().map(Some).collect();
        order.into_iter().map(|index| items[index].take().expect("each item once")).collect()
    }

    /// paneCompositeBar.ts `saveCachedViewContainers`: the bar's items in order with their pinned state.
    fn save_bar_items(&self, part: Part, ids: &[&str], unpinned: &[String]) {
        let stored: Vec<_> = ids.iter().map(|id| json!({ "id": id, "pinned": !unpinned.iter().any(|other| other == id), "visible": true })).collect();
        self.profile_storage.lock().unwrap().set(pinned_key(part), json!(stored).to_string());
    }

    /// compositeBar.ts `CompositeDragAndDrop.drop` of a composite on `part`'s bar, onto `target` (an item and whether
    /// it goes before it): on its own bar it moves there (`move`), from another bar it moves to the target's index
    /// (`getTargetIndex`, `CompositeBarModel.add`); either way it opens focused.
    pub(super) fn drop_composite(&mut self, container: &'static str, part: Part, target: Option<(&'static str, bool)>, window: &mut Window, cx: &mut Context<Self>) {
        let id = if part == Part::SideBar && container == TESTING_CONTAINER { TESTING_ITEM } else { container };
        if self.container_location(container) != part {
            self.move_view_container(container, part, window, cx);
            let Some((target, before)) = target else { return };
            self.place_bar_item(part, id, target, before);
            return cx.notify();
        }
        let Some((target, before)) = target else { return };
        let mut ids: Vec<_> = self.bar_items(part).into_iter().map(|(item, _)| item).collect();
        let (Some(from), Some(mut to)) = (ids.iter().position(|item| *item == id), ids.iter().position(|item| *item == target)) else { return };
        if !before && from > to {
            to += 1;
        }
        if before && from < to {
            to -= 1;
        }
        // compositeBar.ts `drop`: the composite opens focused even when the move leaves the order as it was.
        if to < ids.len() && to != from {
            ids.remove(from);
            ids.insert(to, id);
            // `CompositeBarModel.move`: a moved composite gets pinned.
            let mut unpinned = self.unpinned_containers(part);
            unpinned.retain(|other| other != id);
            self.save_bar_items(part, &ids, &unpinned);
        }
        self.open_bar_composite(id, part, window, cx);
        self.focus_pane_composite(part, window, cx);
    }

    /// `getTargetIndex`: `id` goes into `part`'s stored bar order before or after `target`.
    pub(super) fn place_bar_item(&self, part: Part, id: &'static str, target: &'static str, before: bool) {
        let mut ids: Vec<_> = self.bar_items(part).into_iter().map(|(item, _)| item).filter(|item| *item != id).collect();
        let index = ids.iter().position(|item| *item == target).map_or(ids.len(), |index| index + usize::from(!before));
        ids.insert(index, id);
        self.save_bar_items(part, &ids, &self.unpinned_containers(part));
    }

    /// viewDescriptorService.ts `getViewContainerBadgeEnablementState`.
    pub(super) fn badges_enabled(&self, container: &str) -> bool {
        self.view_customizations()[BADGE_STATES][container] != false
    }

    pub(super) fn show_activity_bar_context_menu(&mut self, position: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        self.show_bar_context_menu(Part::SideBar, position, window, cx);
    }

    /// compositeBar.ts's own `contextmenu` listener on the bar.
    pub(super) fn show_bar_context_menu(&mut self, part: Part, position: Point<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let context = self.key_context(window);
        let (actions, keybinding_commands) = self.bar_menu_actions(part, &context);
        self.show_context_menu_with_keybindings(actions, &keybinding_commands, &context, Bounds::new(position, Default::default()), Vec::new(), window, cx);
    }

    /// compositeBar.ts `getContextMenuActions` with the part's `fillExtraContextMenuActions`, and the commands whose
    /// keybindings the container items show.
    fn bar_menu_actions(&mut self, part: Part, context: &HashMap<String, Value>) -> (Vec<MenuAction>, HashMap<String, String>) {
        let (mut actions, keybinding_commands) = self.bar_pin_actions(part);
        match part {
            Part::SideBar => self.fill_activity_bar_menu(&mut actions, context),
            Part::Panel => self.fill_panel_menu(&mut actions, context),
            _ => self.fill_auxiliary_bar_menu(&mut actions, context),
        }
        (actions, keybinding_commands)
    }

    /// compositeBar.ts `getContextMenuActions`: the bar's items, checked while pinned; the last pinned one stays.
    fn bar_pin_actions(&mut self, part: Part) -> (Vec<MenuAction>, HashMap<String, String>) {
        let items = self.bar_items(part);
        let unpinned = self.unpinned_containers(part);
        let pinned_count = items.iter().filter(|(id, _)| !unpinned.iter().any(|other| other == id)).count();
        let mut actions = Vec::new();
        let mut keybinding_commands = HashMap::new();
        for (id, title) in items {
            let command = toggle_pinned_command(part, id);
            if self.commands.get(&command).is_none() {
                self.commands.register(command.clone(), move |workbench, _, window, cx| {
                    workbench.toggle_container_pinned(id, part, true, window, cx);
                    Outcome::done()
                });
            }
            let pinned = !unpinned.iter().any(|other| other == id);
            keybinding_commands.insert(command.clone(), id.to_owned());
            actions.push(MenuAction::Command { id: command, title: title.to_owned(), enabled: !pinned || pinned_count > 1, checked: pinned, alt: None });
        }
        (actions, keybinding_commands)
    }

    /// activitybarPart.ts `fillContextMenuActions` after the containers.
    fn fill_activity_bar_menu(&self, actions: &mut Vec<MenuAction>, context: &HashMap<String, Value>) {
        actions.push(MenuAction::Separator);
        // Unchecked unless toggled: the port has no accounts UI (port/notes.md), as if upstream's default were false.
        let accounts_visible = self.profile_storage.lock().unwrap().get(ACCOUNTS_VISIBILITY_KEY) == Some("true");
        actions.push(MenuAction::Command { id: "toggleAccountsVisibility".into(), title: "Accounts".into(), enabled: true, checked: accounts_visible, alt: None });
        actions.push(MenuAction::Separator);
        let position_actions = menu_actions(&self.menus, MenuId::ActivityBarPositionMenu, context).into_iter().filter(|action| !matches!(action, MenuAction::Separator)).collect();
        actions.push(MenuAction::Submenu { title: "Activity Bar Position".into(), actions: position_actions, checked: false });
        if self.setting("workbench.activityBar.location") == "default" {
            let compact = self.setting("workbench.activityBar.compact") == true;
            let size = |id: &str, title: &str, checked: bool| MenuAction::Command { id: id.into(), title: title.into(), enabled: true, checked, alt: None };
            let sizes = vec![size("workbench.action.activityBar.size.default", "Default", !compact), size("workbench.action.activityBar.size.compact", "Compact", compact)];
            actions.push(MenuAction::Submenu { title: "Activity Bar Size".into(), actions: sizes, checked: false });
        }
        let side_bar_right = self.arrangement().side_bar == super::layout::Position::Right;
        let title = if side_bar_right { "Move Primary Side Bar Left" } else { "Move Primary Side Bar Right" };
        actions.push(MenuAction::Command { id: "workbench.action.toggleSidebarPosition".into(), title: title.into(), enabled: true, checked: false, alt: None });
    }

    /// panelPart.ts `fillExtraContextMenuActions`.
    fn fill_panel_menu(&mut self, actions: &mut Vec<MenuAction>, context: &HashMap<String, Value>) {
        self.push_views_submenu(Part::Panel, actions);
        let submenu = |menu, title: &str| MenuAction::Submenu { title: title.into(), actions: menu_actions(&self.menus, menu, context).into_iter().filter(|action| !matches!(action, MenuAction::Separator)).collect(), checked: false };
        let position = submenu(MenuId::PanelPositionMenu, "Panel Position");
        let align = submenu(MenuId::PanelAlignmentMenu, "Align Panel");
        let labels = if self.setting("workbench.panel.showLabels") == false { "Show Labels" } else { "Show Icons" };
        let command = |id: &str, title: &str| MenuAction::Command { id: id.into(), title: title.into(), enabled: true, checked: false, alt: None };
        actions.extend([MenuAction::Separator, position, align, command(PANEL_SHOW_LABELS, labels), command("workbench.action.togglePanel", "Hide Panel")]);
    }

    /// auxiliaryBarPart.ts `fillExtraContextMenuActions`; labels show only beside a side activity bar (`canShowLabels`).
    fn fill_auxiliary_bar_menu(&mut self, actions: &mut Vec<MenuAction>, context: &HashMap<String, Value>) {
        self.push_views_submenu(Part::AuxiliaryBar, actions);
        let position_actions = menu_actions(&self.menus, MenuId::ActivityBarPositionMenu, context).into_iter().filter(|action| !matches!(action, MenuAction::Separator)).collect();
        let side_bar_left = self.arrangement().side_bar == super::layout::Position::Left;
        let move_title = if side_bar_left { "Move Secondary Side Bar Left" } else { "Move Secondary Side Bar Right" };
        let location = self.setting("workbench.activityBar.location");
        let can_show_labels = location != "top" && location != "bottom";
        let labels = if can_show_labels && self.setting("workbench.secondarySideBar.showLabels") != false { "Show Icons" } else { "Show Labels" };
        let command = |id: &str, title: &str, enabled: bool| MenuAction::Command { id: id.into(), title: title.into(), enabled, checked: false, alt: None };
        actions.extend([
            MenuAction::Separator,
            MenuAction::Submenu { title: "Activity Bar Position".into(), actions: position_actions, checked: false },
            command("workbench.action.toggleSidebarPosition", move_title, true),
            command(AUXILIARY_BAR_SHOW_LABELS, labels, can_show_labels),
            command("workbench.action.toggleAuxiliaryBar", "Hide Secondary Side Bar", true),
        ]);
    }

    /// paneCompositePart.ts `getViewsSubmenuAction`: the active container's Views submenu when it has more than one
    /// toggle and one is enabled.
    fn push_views_submenu(&mut self, part: Part, actions: &mut Vec<MenuAction>) {
        let Some(container) = self.active_container_in(part) else { return };
        let views = self.views_submenu(super::view_locations::pane_container(container).key());
        if views.len() > 1 && views.iter().any(|action| matches!(action, MenuAction::Command { enabled: true, .. })) {
            actions.push(MenuAction::Separator);
            actions.push(MenuAction::Submenu { title: "Views".into(), actions: views, checked: false });
        }
    }

    /// viewContainerModel.ts `keybindingId`: the container's open command, else its first view's that has one.
    fn composite_keybinding_command(&self, container: &'static str) -> Option<&'static str> {
        container_open_command(container).or_else(|| self.views_in(container).iter().find_map(|view| view_open_command(view.id)))
    }

    /// compositeBarActions.ts `CompositeActionViewItem.showContextMenu` of an activity bar item (`part` the side bar)
    /// or a panel tab: Configure Keybinding, Hide or Keep, Hide or Show Badge, paneCompositeBar.ts
    /// `getContextMenuActionsForComposite` (Move To, Reset Location), then the bar's own menu, anchored below the
    /// item's middle. `item` is the activity item's id, the container's but for Testing's.
    pub(super) fn show_composite_context_menu(&mut self, item: &'static str, part: Part, item_bounds: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let context = self.key_context(window);
        let container = composite_container(item);
        let command = |id: &str, title: String| MenuAction::Command { id: id.into(), title, enabled: true, checked: false, alt: None };
        let mut actions = Vec::new();
        if let Some(open_command) = self.composite_keybinding_command(container) {
            let id = format!("configureKeybinding/{open_command}");
            if self.commands.get(&id).is_none() {
                // menuService.ts `createConfigureKeybindingAction` without a `when`.
                self.commands.register(id.clone(), move |workbench, _, window, cx| {
                    workbench.execute_command(super::keybindings_editor_view::OPEN_COMMAND, vec![json!(format!("@command:{open_command}"))], window, cx)
                });
            }
            actions.push(command(&id, "Configure Keybinding".into()));
        }
        let items = self.bar_items(part);
        let unpinned = self.unpinned_containers(part);
        let name = items.iter().find(|(id, _)| *id == item).map_or(item, |(_, title)| *title);
        let pinned_count = items.iter().filter(|(id, _)| !unpinned.iter().any(|other| other == id)).count();
        actions.push(match unpinned.iter().any(|other| other == item) {
            true => command(TOGGLE_COMPOSITE_PINNED, format!("Keep '{name}'")),
            false => MenuAction::Command { id: TOGGLE_COMPOSITE_PINNED.into(), title: format!("Hide '{name}'"), enabled: pinned_count > 1, checked: false, alt: None },
        });
        let badge = if self.badges_enabled(container) { "Hide Badge" } else { "Show Badge" };
        actions.push(command(TOGGLE_COMPOSITE_BADGE, badge.into()));
        let current = self.container_location(container);
        let default = self.default_container_location(container);
        let moves = [(Part::SideBar, "Primary Side Bar"), (Part::AuxiliaryBar, "Secondary Side Bar"), (Part::Panel, "Panel")]
            .into_iter()
            .filter(|(location, _)| *location != current)
            .map(|(location, label)| command(&format!("{MOVE_CONTAINER_PREFIX}{}", location_code(location)), label.into()))
            .collect();
        actions.push(MenuAction::Separator);
        actions.push(MenuAction::Submenu { title: "Move To".into(), actions: moves, checked: false });
        if default != current || self.view_to_reset(container).is_some() {
            actions.push(command(RESET_LOCATION, "Reset Location".into()));
        }
        let (bar_actions, keybinding_commands) = self.bar_menu_actions(part, &context);
        actions.push(MenuAction::Separator);
        actions.extend(bar_actions);
        let anchor = Point::new(item_bounds.center().x.floor(), item_bounds.bottom());
        self.show_context_menu_with_keybindings(actions, &keybinding_commands, &context, Bounds::new(anchor, Default::default()), vec![json!(item)], window, cx);
    }

    /// compositeBarActions.ts `CompositeActionViewItem` of `bar`'s item `id` in `part`: its context menu.
    pub(super) fn with_composite_menu(&self, item: Stateful<Div>, bar: &'static str, id: &'static str, part: Part, cx: &mut Context<Self>) -> Stateful<Div> {
        item.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, _: &MouseDownEvent, window, cx| {
            cx.stop_propagation();
            let bounds = workbench.drawn_action_bar_item_bounds(bar, id, cx);
            workbench.show_composite_context_menu(id, part, bounds, window, cx);
        }))
    }

    /// An item of the activity bar, or of the compact one in the side bar, with its context menu and its drag as a
    /// `composite`, which the panel and the secondary side bar take.
    pub(super) fn activity_composite_item(&self, item: Stateful<Div>, bar: &'static str, id: &'static str, title: &'static str, icon: SharedString, active: bool, cx: &mut Context<Self>) -> Stateful<Div> {
        let foreground = self.color(if active { "modernActivityBarItem.activeForeground" } else { "activityBar.inactiveForeground" });
        let dragged = DraggedComposite { id: composite_container(id), label: title.into(), icon: Some(icon), foreground, background: self.color("modernActivityBar.background") };
        let item = item.when(bar == "activity", |item| item.child(self.activity_item_focus_indicator(id, active, cx)));
        let item = self.with_composite_menu(item, bar, id, Part::SideBar, cx).on_drag(dragged, |dragged, _, _, cx| cx.new(|_| dragged.clone()));
        self.with_composite_drop(item, bar, id, Part::SideBar, cx).group(super::ACTIVITY_ITEM_GROUP)
    }

    /// shortcut: the drag image draws the codicon, not a product icon theme's glyph; take `styled_icon`'s lookup when a
    /// product icon theme's drag matters.
    pub(super) fn codicon_svg(&self, name: &str) -> SharedString {
        let codicon = crate::codicons::icon_ids(name).last().copied().expect("icon_ids starts with the id");
        crate::codicons::svg_path(&self.app_root, crate::symbol_icons::svg_name(codicon)).to_string_lossy().into_owned().into()
    }

    /// compositeBarActions.ts `onDrop` on an item: the composite goes before it when the pointer is in the item's first
    /// half along the bar (`updateFromDragging`'s `preferTop` and `preferLeft`), where the insert line shows.
    pub(super) fn with_composite_drop(&self, item: Stateful<Div>, bar: &'static str, id: &'static str, part: Part, cx: &mut Context<Self>) -> Stateful<Div> {
        let insert = self.panel.bar_insert.filter(|&(insert_bar, insert_id, _)| insert_bar == bar && insert_id == id && cx.has_active_drag());
        let line = insert.map(|(.., before)| self.bar_insert_line(bar, part, before));
        item.on_drag_move(cx.listener(move |workbench, event: &DragMoveEvent<DraggedComposite>, _, cx| {
            let over = event.bounds.contains(&event.event.position);
            workbench.track_delayed_drag_open(part, id, over, cx);
            // compositeBar.ts `canDrop`: a composite over its own item in its own bar has no feedback.
            let dragged = event.drag(cx).id;
            let accepts = workbench.container_location(dragged) != part || dragged != composite_container(id);
            workbench.track_bar_insert(bar, id, (over && accepts).then(|| before_in(bar, event.bounds, event.event.position)), cx);
        }))
        .on_drag_move(cx.listener(move |workbench, event: &DragMoveEvent<super::view_panes::DraggedPane>, _, cx| {
            let over = event.bounds.contains(&event.event.position);
            workbench.track_delayed_drag_open(part, id, over, cx);
            let accepts = workbench.can_move_view(event.drag(cx).id);
            workbench.track_bar_insert(bar, id, (over && accepts).then(|| before_in(bar, event.bounds, event.event.position)), cx);
        }))
        .on_drop(cx.listener(move |workbench, dragged: &DraggedComposite, window, cx| {
            cx.stop_propagation();
            workbench.panel.bar_insert = None;
            let before = workbench.drops_before(bar, id, window, cx);
            workbench.drop_composite(dragged.id, part, Some((id, before)), window, cx);
        }))
        .on_drop(cx.listener(move |workbench, dragged: &super::view_panes::DraggedPane, window, cx| {
            cx.stop_propagation();
            workbench.panel.bar_insert = None;
            let before = workbench.drops_before(bar, id, window, cx);
            workbench.drop_view_on_location(dragged.id, part, Some((id, before)), cx);
        }))
        .children(line)
    }

    /// compositeBarActions.ts: a drag that stays over an unchecked item for 800ms runs it (dnd.ts `DelayedDragHandler`,
    /// cleared on `dragleave`, `drop` and `dragend`).
    fn track_delayed_drag_open(&mut self, part: Part, id: &'static str, over: bool, cx: &mut Context<Self>) {
        let pending = self.panel.delayed_drag_open.as_ref().map(|(pending, _)| *pending);
        if !over {
            if pending == Some(id) {
                self.panel.delayed_drag_open = None;
            }
            return;
        }
        if pending == Some(id) || self.bar_item_checked(part, id) {
            return;
        }
        let timer = cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(std::time::Duration::from_millis(800)).await;
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.panel.delayed_drag_open = None;
                if cx.has_active_drag() {
                    workbench.open_bar_item(part, id, cx);
                }
            });
        });
        self.panel.delayed_drag_open = Some((id, timer));
    }

    fn bar_item_checked(&self, part: Part, id: &'static str) -> bool {
        if !self.is_part_visible(part) {
            return false;
        }
        match part {
            Part::SideBar => self.compact_activity_view(id) == self.side_bar_view,
            _ => self.active_container_in(part) == Some(id),
        }
    }

    fn open_bar_item(&mut self, part: Part, id: &'static str, cx: &mut Context<Self>) {
        match part {
            Part::SideBar => {
                self.side_bar_view = self.compact_activity_view(id);
                self.set_part_hidden(Part::SideBar, false, cx);
            }
            _ => self.show_view_container(id, cx),
        }
        cx.notify();
    }

    /// compositeBar.ts `CompositeBarDndCallbacks.onDrop`: a composite or a view dropped on `part`'s bar past its items
    /// goes after the last one.
    pub(super) fn with_bar_end_drop<E: InteractiveElement>(&self, bar: E, part: Part, cx: &mut Context<Self>) -> E {
        let last = move |workbench: &Self| {
            let unpinned = workbench.unpinned_containers(part);
            workbench.bar_items(part).into_iter().map(|(id, _)| id).rfind(|id| !unpinned.iter().any(|other| other == id)).map(|id| (id, false))
        };
        bar.on_drop(cx.listener(move |workbench, dragged: &DraggedComposite, window, cx| {
            cx.stop_propagation();
            workbench.panel.drop_target = None;
            workbench.drop_composite(dragged.id, part, last(workbench), window, cx);
        }))
        .on_drop(cx.listener(move |workbench, dragged: &super::view_panes::DraggedPane, _, cx| {
            cx.stop_propagation();
            workbench.drop_view_on_location(dragged.id, part, last(workbench), cx);
        }))
    }

    /// Whether the pointer is in the first half of `bar`'s item `id`; the activity bar is the one vertical bar.
    fn drops_before(&self, bar: &'static str, id: &'static str, window: &Window, cx: &App) -> bool {
        before_in(bar, self.drawn_action_bar_item_bounds(bar, id, cx), window.mouse_position())
    }

    /// Sets the insert line of `bar`'s item `id` (`before` it, or after), or clears it when the drag left that item.
    fn track_bar_insert(&mut self, bar: &'static str, id: &'static str, before: Option<bool>, cx: &mut Context<Self>) {
        let insert = match before {
            Some(before) => Some((bar, id, before)),
            None if self.panel.bar_insert.is_some_and(|(insert_bar, insert_id, _)| insert_bar == bar && insert_id == id) => None,
            None => return,
        };
        if self.panel.bar_insert != insert {
            self.panel.bar_insert = insert;
            cx.notify();
        }
    }

    /// paneCompositePart.css: a 2x24px `--insert-border-color` line at the item's side; activityaction.css: a 2px one
    /// across the vertical activity bar's item at its top or bottom.
    fn bar_insert_line(&self, bar: &'static str, part: Part, before: bool) -> Div {
        let color = match part {
            _ if bar == "activity" => "activityBar.dropBorder",
            Part::Panel => "panel.dropBorder",
            Part::AuxiliaryBar if self.icon_composite_bar(part).is_none() => "panel.dropBorder",
            _ => "activityBarTop.dropBorder",
        };
        let line = div().absolute().bg(self.color(color)).debug_selector(move || format!("bar-insert-{}", if before { "before" } else { "after" }));
        if bar == "activity" {
            return line.left_0().right_0().h(px(2.)).when(before, |line| line.top_0()).when(!before, |line| line.bottom_0());
        }
        line.top(gpui::relative(0.5)).mt(px(-12.)).w(px(2.)).h(px(24.)).when(before, |line| line.left(px(-1.))).when(!before, |line| line.right(px(-1.)))
    }

    /// paneCompositeBar.ts: a container at its default location with one view whose default container is another
    /// (a generated one) resets that view.
    fn view_to_reset(&self, container: &str) -> Option<super::view_locations::MovableView> {
        match self.views_in(container)[..] {
            [view] if view.default_container != container => Some(view),
            _ => None,
        }
    }

    pub(super) fn register_activity_bar_context_menu_commands(&mut self) {
        for part in [Part::SideBar, Part::Panel, Part::AuxiliaryBar] {
            self.commands.register(format!("{MOVE_CONTAINER_PREFIX}{}", location_code(part)), move |workbench, args, window, cx| {
                if let Some(container) = composite_arg(&args).map(composite_container) {
                    workbench.move_view_container(container, part, window, cx);
                }
                Outcome::done()
            });
        }
        self.commands.register(RESET_LOCATION, |workbench, args, window, cx| {
            let Some(container) = composite_arg(&args).map(composite_container) else { return Outcome::done() };
            let default = workbench.default_container_location(container);
            if workbench.container_location(container) != default {
                workbench.move_view_container(container, default, window, cx);
            } else if let Some(view) = workbench.view_to_reset(container) {
                workbench.move_view_to_container(view.id, view.default_container, cx);
                // `openViewContainer(viewContainer.id)` finds nothing once a generated container is cleaned up.
                if !super::view_locations::is_generated_container(container) {
                    workbench.show_view_container(container, cx);
                }
            }
            Outcome::done()
        });
        self.commands.register("toggleAccountsVisibility", |workbench, _, _, cx| {
            let mut storage = workbench.profile_storage.lock().unwrap();
            let visible = storage.get(ACCOUNTS_VISIBILITY_KEY) == Some("true");
            storage.set(ACCOUNTS_VISIBILITY_KEY, (!visible).to_string());
            drop(storage);
            cx.notify();
            Outcome::done()
        });
        for (command, compact) in [("workbench.action.activityBar.size.default", false), ("workbench.action.activityBar.size.compact", true)] {
            self.commands.register(command, move |workbench, _, _, cx| {
                workbench.update_setting("workbench.activityBar.compact", json!(compact));
                cx.notify();
                Outcome::done()
            });
        }
        self.commands.register(TOGGLE_COMPOSITE_PINNED, |workbench, args, window, cx| {
            let Some(item) = composite_arg(&args) else { return Outcome::done() };
            let part = workbench.container_location(composite_container(item));
            workbench.toggle_container_pinned(item, part, false, window, cx);
            Outcome::done()
        });
        self.commands.register(TOGGLE_COMPOSITE_BADGE, |workbench, args, _, cx| {
            let Some(container) = composite_arg(&args).map(composite_container) else { return Outcome::done() };
            let mut customizations = workbench.view_customizations();
            customizations[BADGE_STATES][container] = json!(!workbench.badges_enabled(container));
            workbench.save_view_customizations(&customizations);
            cx.notify();
            Outcome::done()
        });
        for (command, setting) in [(PANEL_SHOW_LABELS, "workbench.panel.showLabels"), (AUXILIARY_BAR_SHOW_LABELS, "workbench.secondarySideBar.showLabels")] {
            self.commands.register(command, move |workbench, _, _, cx| {
                let shown = workbench.setting(setting) != false;
                workbench.update_setting(setting, json!(!shown));
                cx.notify();
                Outcome::done()
            });
        }
    }

    /// compositeBar.ts `pin` (opening the container when `open_on_pin`) and `unpin`; unpinning the open container
    /// opens the default one, else the next shown one (`resetActiveComposite`).
    fn toggle_container_pinned(&mut self, id: &'static str, part: Part, open_on_pin: bool, window: &mut Window, cx: &mut Context<Self>) {
        let items = self.bar_items(part);
        let mut unpinned = self.unpinned_containers(part);
        let was_pinned = !unpinned.iter().any(|other| other == id);
        match was_pinned {
            true => unpinned.push(id.to_owned()),
            false => unpinned.retain(|other| other != id),
        }
        let ids: Vec<_> = items.iter().map(|(container, _)| *container).collect();
        self.save_bar_items(part, &ids, &unpinned);
        if !was_pinned && open_on_pin {
            self.open_bar_composite(id, part, window, cx);
        }
        if was_pinned && self.active_bar_composite(part) == Some(id) {
            let default = match part {
                Part::SideBar => Some(VIEW_CONTAINERS[0].3),
                Part::Panel => Some(super::terminal_view::TERMINAL_VIEW_ID),
                _ => None,
            };
            let pinned = |container: &&str| *container != id && !unpinned.iter().any(|other| other == container);
            let next = default.filter(pinned).or_else(|| items.iter().map(|(container, _)| *container).find(pinned));
            if let Some(next) = next {
                self.open_bar_composite(next, part, window, cx);
            }
        }
        cx.notify();
    }

    /// `openComposite`: an activity item runs its open command, a tab opens its container.
    fn open_bar_composite(&mut self, id: &'static str, part: Part, window: &mut Window, cx: &mut Context<Self>) {
        if part == Part::SideBar {
            self.execute_command(id, Vec::new(), window, cx);
            return;
        }
        match self.panel.views.iter().find(|view| view.id == id) {
            Some(view) => (view.open)(self, window, cx),
            None => self.show_view_container(id, cx),
        }
    }

    /// The bar's active item (`model.activeItem`) while its part shows.
    fn active_bar_composite(&self, part: Part) -> Option<&'static str> {
        if part != Part::SideBar {
            return self.is_part_visible(part).then(|| self.active_container_in(part)).flatten();
        }
        if !self.side_bar_visible() {
            return None;
        }
        match self.side_bar_view {
            SideBarView::Testing => Some("workbench.view.testing"),
            SideBarView::Contributed(id) | SideBarView::Generated(id) => Some(id),
            view => VIEW_CONTAINERS.into_iter().find(|container| container.4 == Some(view)).map(|container| container.3),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;
    use std::sync::{Arc, Mutex};

    use exthost::scan::scan_extension;
    use gpui::{Modifiers, MouseButton, TestAppContext, VisualTestContext};
    use storage::Storage;

    use crate::host_sync::HostSync;
    use crate::languages::Languages;
    use crate::menus::MenuAction;
    use crate::theme::load_theme;
    use crate::workbench::Workbench;

    /// Right-clicks the bar below its items, as activity-bar-menu.json does; an item shows its own menu.
    fn right_click_activity_bar(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<(String, bool, bool, Option<String>)> {
        cx.update(|window, cx| drop(window.draw(cx)));
        let icon = cx.debug_bounds("workbench.view.explorer").expect("the Explorer icon");
        let below = gpui::point(icon.center().x, icon.bottom() + gpui::px(400.));
        cx.simulate_mouse_down(below, MouseButton::Right, Modifiers::none());
        cx.simulate_mouse_up(below, MouseButton::Right, Modifiers::none());
        cx.run_until_parked();
        let items = workbench.read_with(cx, |workbench, _| {
            let menu = workbench.context_menu.as_ref().expect("a context menu shows");
            menu.levels[0].actions.iter().map(|action| match action {
                MenuAction::Command { id, title, enabled, checked, .. } => (title.clone(), *enabled, *checked, menu.keybindings.get(id).cloned()),
                MenuAction::Submenu { title, .. } => (format!("{title} >"), true, false, None),
                MenuAction::Separator => ("---".into(), false, false, None),
            }).collect()
        });
        cx.simulate_keystrokes("escape");
        items
    }

    /// activitybarPart.ts `fillContextMenuActions` as the reference shows it (port/fixtures/ui-pair/icons/activity-bar-menu.json):
    /// the containers checked while pinned with their keybindings, Accounts, then the activity bar's own actions.
    /// Unpinning a container hides its icon and leaves the last pinned one disabled.
    #[gpui::test]
    fn the_activity_bar_context_menu_pins_view_containers(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let dir = std::env::temp_dir().join(format!("code-gpui-activity-bar-menu-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
            workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("keybindings.json"));
            let storage = Arc::new(Mutex::new(Storage::in_memory()));
            workbench.restore_profile_state(storage.clone(), storage);
            workbench
        });
        cx.run_until_parked();
        let item = |title: &str, checked: bool, keybinding: Option<&str>| (title.to_owned(), true, checked, keybinding.map(str::to_owned));
        let separator = ("---".to_owned(), false, false, None);
        let rest = [separator.clone(), item("Accounts", false, None), separator, item("Activity Bar Position >", false, None), item("Activity Bar Size >", false, None), item("Move Primary Side Bar Right", false, None)];
        let keys = if matches!(crate::keybindings::OS, crate::keybindings::Os::Macintosh) { ["⇧⌘E", "⇧⌘F", "⌃⇧G", "⇧⌘D", "⇧⌘X"] } else { ["Ctrl+Shift+E", "Ctrl+Shift+F", "Ctrl+Shift+G", "Ctrl+Shift+D", "Ctrl+Shift+X"] };
        let containers = [item("Explorer", true, Some(keys[0])), item("Search", true, Some(keys[1])), item("Source Control", true, Some(keys[2])), item("Run and Debug", true, Some(keys[3])), item("Extensions", true, Some(keys[4]))];
        assert_eq!(right_click_activity_bar(&workbench, cx), [containers.as_slice(), rest.as_slice()].concat());

        workbench.update_in(cx, |workbench, window, cx| {
            let _ = workbench.execute_command("workbench.action.activityBar.togglePinned.workbench.view.search", Vec::new(), window, cx);
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        assert!(cx.debug_bounds("workbench.view.search").is_none(), "an unpinned container leaves the bar");
        assert_eq!(right_click_activity_bar(&workbench, cx)[1], item("Search", false, Some(keys[1])));

        for id in ["workbench.view.scm", "workbench.view.debug", "workbench.view.extensions"] {
            workbench.update_in(cx, |workbench, window, cx| {
                let _ = workbench.execute_command(&format!("workbench.action.activityBar.togglePinned.{id}"), Vec::new(), window, cx);
            });
        }
        assert_eq!(right_click_activity_bar(&workbench, cx)[0], ("Explorer".to_owned(), false, true, Some("⇧⌘E".to_owned())), "the last pinned container stays");
    }
}