Skip to content

Visual Studio Code, rebuilt in Rust

Rust
67.0 KB
Raw Blame
//! The panel and the secondary side bar (panelPart.ts, auxiliaryBarPart.ts, paneCompositePart.ts): floating cards
//! with a composite title (the views' tabs, the active view's actions, maximize and close) over the active view.
//! Panel views register here with `register_panel_view`; a view container dragged onto the other part moves there
//! (viewDescriptorService.ts `moveViewContainerToLocation`, stored in `views.customizations`).

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use gpui::{
    AnyElement, AppContext, Bounds, Context, Div, DragMoveEvent, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Render, Rgba, SharedString, Stateful, StatefulInteractiveElement, Styled, TextRun, Window, div,
    prelude::FluentBuilder, px, svg,
};
use serde_json::json;

use super::Workbench;
use crate::theme::ThemeKind;
use super::activity::{BadgeContent, visible_badge};
use super::hover::{HoverContent, HoverOptions, HoverPosition};
use super::layout::{Alignment, Part, Position};
use super::view_locations::{is_generated_container, location_code};
use crate::commands::Outcome;
use crate::menus::MenuAction;

/// paneCompositePart.ts `ACTIVE_PANEL_SETTINGS_KEY` of the panel and of the secondary side bar, in workspace storage.
const ACTIVE_PANEL_KEY: &str = "workbench.panelpart.activepanelid";
const ACTIVE_AUXILIARY_BAR_KEY: &str = "workbench.auxiliarybar.activepanelid";
/// The composite title's height (`--vscode-workbench-titleHeight` of a pane composite part).
const TITLE_HEIGHT: f32 = 32.;
/// connectedPaneTabs.css `.action-item.icon`: `spacing-size360`.
const ICON_TAB_WIDTH: f32 = 36.;
/// views.css `.viewpane-filter-container` `max-width` in a panel title.
const FILTER_MAX_WIDTH: f32 = 200.;
const FILTER_MIN_WIDTH: f32 = 150.;
/// The "..." item as drawn: 6px padding each side of its 16px codicon.
const OVERFLOW_ITEM_WIDTH: f32 = 28.;
/// paneCompositePart.ts `MIN_COMPOSITE_BAR_WIDTH`.
const MIN_COMPOSITE_BAR_WIDTH: f32 = 50.;

/// A view container in the panel: its tab title, its content and its title actions (`MenuId.ViewTitle`).
pub struct PanelView {
    pub id: &'static str,
    /// The container's single view, whose `<view id>.focus` command opens it (viewsService.ts `registerFocusViewAction`).
    pub view_id: &'static str,
    pub title: &'static str,
    /// `openPaneComposite(id, true)`: shows the view and focuses its content.
    pub open: fn(&mut Workbench, &mut Window, &mut Context<Workbench>),
    pub render: fn(&mut Workbench, &mut Window, &mut Context<Workbench>) -> AnyElement,
    pub actions: fn(&Workbench, &mut Window, &mut Context<Workbench>) -> AnyElement,
    /// A `hideIfEmpty` container shows its tab only while one of its views' `when` holds.
    pub visible: fn(&Workbench) -> bool,
    /// The activity count the view's tab shows (`IActivity.badge`).
    pub badge: fn(&Workbench) -> Option<NumberBadge>,
}

/// activity.ts `NumberBadge`: a count with the description its tab's hover appends.
pub struct NumberBadge {
    pub number: usize,
    pub description: String,
}

/// A pane composite part's tab strip, title actions and content as last painted.
#[derive(Default)]
struct CompositeBar {
    title_bounds: Rc<Cell<Bounds<Pixels>>>,
    actions_bounds: Rc<Cell<Bounds<Pixels>>>,
    /// The active view whose title actions `actions_bounds` measured: a layout is kept only once they are its own.
    actions_view: Cell<Option<&'static str>>,
    overflow_bounds: Rc<Cell<Bounds<Pixels>>>,
    /// The active view's filter box in the title, empty without one.
    filter_bounds: Rc<Cell<Bounds<Pixels>>>,
    /// The width the tabs leave free beside a 200px filter box.
    filter_room: Cell<f32>,
    /// The shown tabs, what they were laid out for and the title actions' width then.
    tab_layout: RefCell<Option<(TabLayoutKey, f32, Vec<&'static str>)>>,
    /// The view's area under the title, the pane body size `FilterViewPane` places its filter by.
    content_bounds: Rc<Cell<Bounds<Pixels>>>,
}

#[derive(Default)]
pub(super) struct Panel {
    pub(super) views: Vec<PanelView>,
    active: Option<&'static str>,
    auxiliary_active: Option<&'static str>,
    panel_bar: CompositeBar,
    auxiliary_bar: CompositeBar,
    /// The part a dragged view container is over (`CompositeDragAndDropObserver` `onDragEnter`).
    pub(super) drop_target: Option<Part>,
    /// The bar item a drag has been over since the timer started (dnd.ts `DelayedDragHandler`).
    pub(super) delayed_drag_open: Option<(&'static str, gpui::Task<()>)>,
    /// The bar and item a drag can drop on, and whether before it: compositeBarActions.ts `updateFromDragging`.
    pub(super) bar_insert: Option<(&'static str, &'static str, bool)>,
}

/// A part title's action bars (actionbar.ts), one tab stop each: the composite bar's tabs and the global actions.
pub(super) const PANEL_TITLE_BARS: [&str; 2] = ["panel-composite-bar", "panel-global-actions"];
pub(super) const AUXILIARY_BAR_TITLE_BARS: [&str; 2] = ["auxiliarybar-composite-bar", "auxiliarybar-global-actions"];

fn title_bars(part: Part) -> [&'static str; 2] {
    if part == Part::AuxiliaryBar { AUXILIARY_BAR_TITLE_BARS } else { PANEL_TITLE_BARS }
}

/// A global title action: its codicon, tooltip, command and whether it is toggled.
type GlobalAction = (&'static str, &'static str, &'static str, bool);

/// The title width, the tabs, the active view and whether it has a filter box.
type TabLayoutKey = (Pixels, Vec<&'static str>, Option<&'static str>, bool);

/// A composite bar item being dragged (`CompositeDragAndDropData` of type `composite`), drawn as the browser's drag
/// image of its element: an activity item's icon, a tab's label.
#[derive(Clone)]
pub(super) struct DraggedComposite {
    pub id: &'static str,
    pub label: SharedString,
    /// The SVG of an activity item's icon.
    pub icon: Option<SharedString>,
    pub foreground: Rgba,
    pub background: Rgba,
}

impl Render for DraggedComposite {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        if let Some(icon) = &self.icon {
            return div().debug_selector(|| "dragged-composite-icon".into()).size(px(36.)).flex().items_center().justify_center().opacity(0.8).child(svg().external_path(icon.clone()).size(px(24.)).text_color(self.foreground));
        }
        div().h(px(TITLE_HEIGHT)).px(px(16.)).flex().items_center().text_size(px(13.)).text_color(self.foreground).bg(self.background).opacity(0.8).child(self.label.clone())
    }
}

impl Workbench {
    pub(super) fn register_panel_view(&mut self, view: PanelView) {
        let open = view.open;
        self.commands.register(format!("{}.focus", view.view_id), move |workbench, _, window, cx| {
            open(workbench, window, cx);
            Outcome::done()
        });
        self.panel.views.push(view);
    }

    /// panelActions.ts and auxiliaryBarActions.ts.
    pub(super) fn register_panel_actions(&mut self) {
        self.commands.register("workbench.action.togglePanel", |workbench, _, _, cx| {
            match workbench.is_part_visible(Part::Panel) {
                true => workbench.hide_panel(cx),
                false => workbench.show_panel(cx),
            }
            Outcome::done()
        });
        self.commands.register("workbench.action.closePanel", |workbench, _, _, cx| {
            workbench.hide_panel(cx);
            Outcome::done()
        });
        for (command, source, destination) in [("workbench.action.movePanelToSecondarySideBar", Part::Panel, Part::AuxiliaryBar), ("workbench.action.moveSecondarySideBarToPanel", Part::AuxiliaryBar, Part::Panel)] {
            self.commands.register(command, move |workbench, _, _, cx| {
                workbench.move_views_between_panels(source, destination, cx);
                Outcome::done()
            });
        }
        // panelActions.ts: maximizing needs a centered panel or one on a side.
        self.commands.register("workbench.action.toggleMaximizedPanel", |workbench, _, _, cx| {
            let arrangement = workbench.arrangement();
            if arrangement.alignment != Alignment::Center && arrangement.panel.is_horizontal() {
                workbench.notify_warning("Maximizing the panel is only supported when it is center aligned.");
                return Outcome::done();
            }
            if !workbench.is_part_visible(Part::Panel) {
                workbench.show_panel(cx);
                if !workbench.is_panel_maximized() {
                    workbench.toggle_maximized_panel(cx);
                }
            } else {
                workbench.toggle_maximized_panel(cx);
            }
            Outcome::done()
        });
        self.commands.register("workbench.action.toggleAuxiliaryBar", |workbench, _, _, cx| {
            let visible = workbench.is_part_visible(Part::AuxiliaryBar);
            workbench.set_part_hidden(Part::AuxiliaryBar, visible, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.closeAuxiliaryBar", |workbench, _, _, cx| {
            workbench.set_part_hidden(Part::AuxiliaryBar, true, cx);
            Outcome::done()
        });
        // The preconditions of MaximizeAuxiliaryBar and RestoreAuxiliaryBar are the setter's early return.
        self.commands.register("workbench.action.maximizeAuxiliaryBar", |workbench, _, _, cx| {
            workbench.set_auxiliary_bar_maximized(true, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.restoreAuxiliaryBar", |workbench, _, _, cx| {
            workbench.set_auxiliary_bar_maximized(false, cx);
            Outcome::done()
        });
        self.commands.register("workbench.action.toggleMaximizedAuxiliaryBar", |workbench, _, _, cx| {
            let maximized = workbench.is_auxiliary_bar_maximized();
            workbench.set_auxiliary_bar_maximized(!maximized, cx);
            Outcome::done()
        });
    }

    /// `moveViewContainerToLocation` and `openViewContainer(id, true)` of a container moved to `part`. Only moved
    /// containers keep an entry (`saveViewCustomizations` skips the default location).
    pub(super) fn move_view_container(&mut self, id: &'static str, part: Part, window: &mut Window, cx: &mut Context<Self>) {
        let at_default = part == self.default_container_location(id) && !is_generated_container(id);
        let mut customizations = self.view_customizations();
        let locations = customizations["viewContainerLocations"].as_object_mut().expect("normalized");
        match at_default {
            true => drop(locations.remove(id)),
            false => drop(locations.insert(id.to_owned(), json!(location_code(part)))),
        }
        self.save_view_customizations(&customizations);
        self.leave_moved_side_bar_container();
        match self.panel.views.iter().find(|view| view.id == id) {
            Some(view) => (view.open)(self, window, cx),
            None => {
                self.show_view_container(id, cx);
                self.focus_pane_composite(part, window, cx);
            }
        }
    }

    /// `openPaneComposite` where the container is: shows its part with the view and stores it as the last active one.
    /// A panel container's view moved to another container opens there (`viewsService.openView`).
    pub(super) fn open_panel_view(&mut self, id: &'static str, cx: &mut Context<Self>) {
        if let Some(view) = self.moved_panel_view(id) {
            self.open_moved_view(view, cx);
            return;
        }
        self.show_view_container(id, cx);
    }

    /// The view of a built-in panel container when it is no longer in it.
    fn moved_panel_view(&self, container: &str) -> Option<&'static str> {
        let view = self.panel.views.iter().find(|view| view.id == container)?;
        let moved = self.views_in(container).iter().all(|in_container| in_container.id != view.view_id);
        moved.then_some(view.view_id)
    }

    /// `openViewContainer`: shows the container in its part, the side bar or a panel that keeps it as its last active one.
    pub(super) fn show_view_container(&mut self, id: &'static str, cx: &mut Context<Self>) {
        let part = self.container_location(id);
        if part == Part::SideBar {
            self.side_bar_view = super::view_locations::side_bar_view_of(id);
            self.set_part_hidden(Part::SideBar, false, cx);
            return self.editors_changed(cx);
        }
        let key = match part {
            Part::AuxiliaryBar => {
                self.panel.auxiliary_active = Some(id);
                ACTIVE_AUXILIARY_BAR_KEY
            }
            _ => {
                self.panel.active = Some(id);
                ACTIVE_PANEL_KEY
            }
        };
        self.workspace_storage.lock().unwrap().set(key, id.to_string());
        if !self.is_part_visible(part) {
            self.set_part_hidden(part, false, cx);
        }
        self.editors_changed(cx);
    }

    /// `setPanelHidden(false)`: opens the last active view, or the default one.
    fn show_panel(&mut self, cx: &mut Context<Self>) {
        self.set_part_hidden(Part::Panel, false, cx);
        if let Some(id) = self.active_container_in(Part::Panel) {
            self.show_view_container(id, cx);
        }
    }

    /// `isViewVisible`: the view's part shows and `id` is its active view.
    pub(super) fn panel_view_visible(&self, id: &str) -> bool {
        if let Some(view) = self.moved_panel_view(id) {
            return self.is_view_visible(view);
        }
        let part = self.container_location(id);
        self.is_part_visible(part) && self.active_container_in(part) == Some(id)
    }

    /// `viewsService.closeView`: the view's part hides when the view is its active one.
    pub(super) fn close_panel_view(&mut self, id: &str, cx: &mut Context<Self>) {
        if !self.panel_view_visible(id) {
            return;
        }
        let container = match self.moved_panel_view(id).and_then(|view| self.movable_views().into_iter().find(|movable| movable.id == view)) {
            Some(view) => self.view_container(&view),
            None => id,
        };
        match self.container_location(container) {
            Part::SideBar => self.set_part_hidden(Part::SideBar, true, cx),
            Part::AuxiliaryBar => self.set_part_hidden(Part::AuxiliaryBar, true, cx),
            _ => self.hide_panel(cx),
        }
    }

    /// `setPanelHidden(true)`: a maximized panel gives the editor back first.
    pub(super) fn hide_panel(&mut self, cx: &mut Context<Self>) {
        self.set_part_hidden(Part::Panel, true, cx);
        self.editors_changed(cx);
    }

    /// panelActions.ts `MoveViewsBetweenPanelsAction`: every container of `source` moves to `destination`, which shows,
    /// and opens `source`'s active one when `destination` had none.
    fn move_views_between_panels(&mut self, source: Part, destination: Part, cx: &mut Context<Self>) {
        let moving = self.part_containers(source);
        if moving.is_empty() {
            return;
        }
        let active = self.is_part_visible(source).then(|| self.active_container_in(source)).flatten();
        let destination_was_empty = self.part_containers(destination).is_empty();
        let mut customizations = self.view_customizations();
        let locations = customizations["viewContainerLocations"].as_object_mut().expect("normalized");
        for tab in moving {
            // Only moved containers keep an entry (`saveViewCustomizations` skips the default location).
            match destination == self.default_container_location(tab.id) && !is_generated_container(tab.id) {
                true => drop(locations.remove(tab.id)),
                false => drop(locations.insert(tab.id.to_owned(), json!(location_code(destination)))),
            }
        }
        self.save_view_customizations(&customizations);
        // paneCompositePart.ts: a part left without containers hides.
        self.set_part_hidden(source, true, cx);
        self.set_part_hidden(destination, false, cx);
        match active.filter(|_| destination_was_empty) {
            Some(id) => self.show_view_container(id, cx),
            None => self.editors_changed(cx),
        }
    }

    /// `getActivePaneComposite(ViewContainerLocation.Panel)`, while the panel shows.
    pub(super) fn active_panel_id(&self) -> Option<&'static str> {
        self.is_part_visible(Part::Panel).then(|| self.active_container_in(Part::Panel)).flatten()
    }

    /// The tabs of the part's composite bar: its pinned items and the active one (compositeBar.ts
    /// `updateCompositeSwitcher`).
    pub(super) fn part_tabs(&self, part: Part) -> Vec<CompositeTab> {
        let unpinned = self.unpinned_containers(part);
        let active = self.active_container_in(part);
        self.part_composites(part).into_iter().filter(|tab| !unpinned.iter().any(|id| id == tab.id) || Some(tab.id) == active).collect()
    }

    /// The part's composite bar items, pinned or not (`visibleItems`): the built-in containers by registration order
    /// while their view is in them, then the generated ones.
    pub(super) fn part_composites(&self, part: Part) -> Vec<CompositeTab> {
        let tabs = self.part_containers(part).into_iter().filter(|tab| self.panel.views.iter().find(|view| view.view_id == tab.view).is_none_or(|view| (view.visible)(self))).collect();
        self.in_bar_order(part, tabs, |tab| tab.id)
    }

    /// The part's containers that hold a view, shown or not.
    fn part_containers(&self, part: Part) -> Vec<CompositeTab> {
        let mut tabs = Vec::new();
        for view in &self.panel.views {
            if self.container_location(view.id) == part && self.moved_panel_view(view.id).is_none() {
                tabs.push(CompositeTab { id: view.id, title: view.title, view: view.view_id });
            }
        }
        // viewsExtensionPoint.ts: an extension's panel containers order after the built-in ones and `hideIfEmpty`.
        for id in self.tree_views.containers.iter().map(|container| container.id).collect::<Vec<_>>() {
            if self.container_location(id) == part && let Some(view) = self.views_in(id).into_iter().find(|view| self.view_when_holds(view)) {
                let title = self.tree_views.containers.iter().find(|container| container.id == id).expect("a contributed container").title.as_str();
                tabs.push(CompositeTab { id, title: super::tree_view::static_id(title), view: view.id });
            }
        }
        // The side bar's Extensions and Testing moved here.
        if self.container_location(super::extensions_view::VIEWLET_ID) == part {
            tabs.push(CompositeTab { id: super::extensions_view::VIEWLET_ID, title: "Extensions", view: super::extensions_view::VIEW_IDS[0] });
        }
        if self.testing_container_shown() && self.container_location(super::view_locations::TESTING_CONTAINER) == part {
            tabs.push(CompositeTab { id: super::view_locations::TESTING_CONTAINER, title: "Testing", view: super::testing_view::TESTING_VIEW });
        }
        for id in self.generated_containers_in(part) {
            let view = self.generated_container_view(id).expect("a container with a view");
            tabs.push(CompositeTab { id, title: super::tree_view::static_id(&self.container_title(id)), view: view.id });
        }
        tabs
    }

    /// The extensions' `viewsContainers.panel` containers.
    pub(super) fn contributed_panel_containers(&self) -> Vec<&'static str> {
        self.tree_views.containers.iter().filter(|container| container.location == Part::Panel).map(|container| container.id).collect()
    }

    /// The part's last active view, else its default: Terminal in the panel (terminal.contribution.ts registers it
    /// with `isDefault`), the first container in the secondary side bar.
    pub(super) fn active_container_in(&self, part: Part) -> Option<&'static str> {
        let (active, key) = match part {
            Part::AuxiliaryBar => (self.panel.auxiliary_active, ACTIVE_AUXILIARY_BAR_KEY),
            _ => (self.panel.active, ACTIVE_PANEL_KEY),
        };
        let stored = self.workspace_storage.lock().unwrap().get(key).map(str::to_owned);
        let id = active.map(str::to_owned).or(stored);
        let containers = self.part_containers(part);
        let default = match part {
            Part::AuxiliaryBar => containers.first(),
            _ => containers.iter().find(|tab| tab.id == super::terminal_view::TERMINAL_VIEW_ID),
        };
        containers.iter().find(|tab| Some(tab.id) == id.as_deref()).or(default).map(|tab| tab.id)
    }

    /// panelpart.css: a left, right or top panel turns its split and maximize icons to face the editor.
    pub(super) fn panel_title_icon_turns(&self) -> f32 {
        match self.arrangement().panel {
            Position::Bottom => 0.,
            Position::Right => -0.25,
            Position::Left => 0.25,
            Position::Top => 0.5,
        }
    }

    /// The panel card: the views' tabs, maximize and close, and the active view.
    pub(super) fn panel_part(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Div {
        let (maximize_icon, maximize_title) = match self.is_panel_maximized() {
            true => ("screen-normal", "Restore Panel Size"),
            false => ("screen-full", "Maximize Panel Size"),
        };
        let arrangement = self.arrangement();
        // panelActions.ts `panelMaximizationSupportedWhen`.
        let maximizes = arrangement.alignment == Alignment::Center || !arrangement.panel.is_horizontal();
        let mut actions = vec![(maximize_icon, maximize_title, "workbench.action.toggleMaximizedPanel", false), ("close", "Hide Panel", "workbench.action.closePanel", false)];
        if !maximizes {
            actions.remove(0);
        }
        self.pane_composite_part(Part::Panel, actions, window, cx)
    }

    /// The secondary side bar card: `MenuId.AuxiliaryBarTitle`'s Toggle Maximized Secondary Side Bar (toggled: the
    /// other tooltip and the toolbar's `highlightToggledItems` background), then Hide Secondary Side Bar while
    /// `workbench.activityBar.location` is `default`.
    pub(super) fn auxiliary_bar_part(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Div {
        let maximized = self.is_auxiliary_bar_maximized();
        let maximize_title = if maximized { "Restore Secondary Side Bar" } else { "Maximize Secondary Side Bar" };
        let mut actions = vec![("screen-full", maximize_title, "workbench.action.toggleMaximizedAuxiliaryBar", maximized)];
        if self.setting("workbench.activityBar.location") == "default" {
            actions.push(("close", "Hide Secondary Side Bar", "workbench.action.closeAuxiliaryBar", false));
        }
        self.pane_composite_part(Part::AuxiliaryBar, actions, window, cx)
    }

    /// paneCompositePart.ts: the tabs that fit and the "..." item, the active view's actions and the part's global
    /// actions over the active view, or the empty message. Dropping a dragged tab anywhere on the part moves its
    /// container here; over a part without an active view the title and the message take `editorGroup.dropBackground`.
    fn pane_composite_part(&mut self, part: Part, actions: Vec<GlobalAction>, window: &mut Window, cx: &mut Context<Self>) -> Div {
        let active = self.active_container_in(part);
        let shown = self.tabs_that_fit(part, active, window);
        self.composite_bar(part).actions_view.set(active);
        let background = if part == Part::AuxiliaryBar { "sideBar.background" } else { "panel.background" };
        let tabs_bar = title_bars(part)[0];
        let mut tabs: Vec<AnyElement> = Vec::new();
        let mut overflowing = Vec::new();
        let mut previous_inactive = false;
        let icon_bar = self.icon_composite_bar(part);
        for tab in self.part_tabs(part) {
            match shown.contains(&tab.id) {
                true => {
                    let checked = Some(tab.id) == active;
                    let divider = previous_inactive && !checked;
                    previous_inactive = !checked;
                    let tab_element = match icon_bar {
                        Some(footer) => self.icon_composite_tab(&tab, checked, tabs.is_empty(), footer, window, cx),
                        None => self.panel_tab(&tab, checked, tabs.is_empty(), divider, background, window, cx),
                    };
                    let item = self.action_bar_item(tabs_bar, tab.id, tab_element, cx);
                    let item = self.with_composite_menu(item, tabs_bar, tab.id, part, cx);
                    tabs.push(self.with_composite_drop(item, tabs_bar, tab.id, part, cx).into_any_element());
                }
                false => overflowing.push(MenuAction::Command { id: format!("{}.focus", tab.view), title: panel_tab_label(&tab, self), enabled: true, checked: Some(tab.id) == active, alt: None }),
            }
        }
        if !overflowing.is_empty() {
            tabs.push(self.action_bar_item(tabs_bar, "additionalComposites.action", self.panel_overflow_action(part, overflowing, cx), cx).into_any_element());
        }
        let drop_feedback = active.is_none() && self.panel.drop_target == Some(part);
        let (content, view_actions) = match active {
            Some(container) => self.panel_container_content(container, window, cx),
            None => (self.empty_pane_message(drop_feedback).into_any_element(), None),
        };
        let content_bounds = self.composite_bar(part).content_bounds.clone();
        // part.css: the composite progress bar at the title's bottom 2px; a merged view's own bar sits there too.
        let merged_view = active.and_then(|container| match self.views_in(container).iter().filter(|view| self.movable_view_shown(view)).collect::<Vec<_>>()[..] {
            [view] => Some(view.id),
            _ => None,
        });
        let progress_bars = active.into_iter().chain(merged_view).filter_map(|scope| self.scoped_progress_bar(scope)).map(|bar| bar.top(px(-2.)));
        let view_actions = merged_view.or(active).zip(view_actions);
        let content = div().relative().flex_1().min_h_0().flex().flex_col().child(size_tracker(content_bounds)).child(content).children(progress_bars);
        let card = self.pane_composite_card(part, background)
            .on_drag_move(cx.listener(move |workbench, event: &DragMoveEvent<DraggedComposite>, _, cx| {
                workbench.track_part_drop_target(part, event.bounds.contains(&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.can_move_view(event.drag(cx).id);
                workbench.track_part_drop_target(part, over, cx);
            }))
            // paneCompositePart.ts `createEmptyPaneMessage` registers the whole part as a composite bar drop target.
            .on_drop(cx.listener(move |workbench, dragged: &DraggedComposite, window, cx| {
                workbench.panel.drop_target = None;
                workbench.drop_composite(dragged.id, part, None, window, cx);
            }))
            .on_drop(cx.listener(move |workbench, dragged: &super::view_panes::DraggedPane, _, cx| {
                workbench.panel.drop_target = None;
                workbench.drop_view_on_location(dragged.id, part, None, cx);
            }));
        let Some(footer) = icon_bar else {
            return card.child(self.with_bar_end_drop(self.pane_composite_title(part, tabs, view_actions, actions, drop_feedback, cx), part, cx)).child(content);
        };
        let strip = self.with_bar_end_drop(self.icon_composite_strip(part, tabs, footer, cx), part, cx);
        let label = active.and_then(|container| self.part_tabs(part).into_iter().find(|tab| tab.id == container)).map(|tab| self.view_header_text(tab.title, false));
        let title = self.icon_bar_title(part, label, view_actions, actions, drop_feedback, cx);
        match footer {
            false => card.child(strip).child(title).child(content),
            true => card.child(title).child(content).child(strip),
        }
    }

    /// auxiliaryBarPart.ts `resolveConfiguration`: with the activity bar on top or at the bottom the secondary side bar
    /// cannot show labels; its composite bar is a header (`false`) or a footer (`true`) of icons.
    pub(super) fn icon_composite_bar(&self, part: Part) -> Option<bool> {
        if part != Part::AuxiliaryBar {
            return None;
        }
        self.compact_activity_bar_location()
    }

    /// The header or footer composite bar: the side bar's compact activity bar strip with the part's icon tabs.
    fn icon_composite_strip(&self, part: Part, tabs: Vec<AnyElement>, footer: bool, cx: &mut Context<Self>) -> Div {
        let line = div().absolute().left_0().right_0().h(px(1.)).bg(self.connected_pane_tab_border());
        let line = if footer { line.top_0() } else { line.bottom_0() };
        let strip = div()
            .relative()
            .h(px(TITLE_HEIGHT))
            .flex_none()
            .flex()
            .bg(self.tab_strip_background())
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| workbench.show_bar_context_menu(part, event.position, window, cx)))
            .child(line)
            .child(size_tracker(self.composite_bar(part).title_bounds.clone()));
        self.action_bar(title_bars(part)[0], false, strip, cx).children(tabs)
    }

    /// compositeBarActions.ts `CompositeBarActionViewItem` with `icon: true`: the container's 16px icon in a 36px item,
    /// colored as the activity bar on top (`activityBarTop.*`).
    fn icon_composite_tab(&self, tab: &CompositeTab, active: bool, first: bool, footer: bool, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
        let id = tab.id;
        let color = if active { self.color("activityBarTop.foreground") } else { self.color("activityBarTop.inactiveForeground") };
        let hover_color = if active { color } else { self.foreground_or("modernTab.hoverForeground") };
        let hover_group = SharedString::from(super::ACTIVITY_ITEM_GROUP);
        let dragged = DraggedComposite { id, label: tab.title.into(), icon: Some(self.compact_activity_drag_icon(id)), foreground: color, background: self.color("sideBar.background") };
        div()
            .id(id)
            .debug_selector(move || id.to_owned())
            .relative()
            .h(px(TITLE_HEIGHT))
            .w(px(ICON_TAB_WIDTH))
            .flex_none()
            .cursor_pointer()
            .group(hover_group.clone())
            .when(active, |item| item.child(self.connected_pane_tab_fill(first, footer, "sideBar.background")))
            .when(!active, |item| item.child(self.inactive_pane_tab_hover(&hover_group, true)))
            .child(self.compact_activity_icon(id, color, hover_color).h(px(TITLE_HEIGHT)))
            .child(self.panel_tab_hover(tab, window))
            .on_drag(dragged, |dragged, _, _, cx| cx.new(|_| dragged.clone()))
            .on_click(cx.listener(move |workbench, _, window, cx| match workbench.panel.views.iter().find(|view| view.id == id) {
                Some(view) => (view.open)(workbench, window, cx),
                None => workbench.show_view_container(id, cx),
            }))
    }

    /// compositePart.ts title area under a header composite bar: the active container's title label, as the side
    /// bar's, and the title actions.
    fn icon_bar_title(&self, part: Part, label: Option<String>, view_actions: Option<(&'static str, AnyElement)>, actions: Vec<GlobalAction>, drop_feedback: bool, cx: &mut Context<Self>) -> Div {
        let background = if drop_feedback { self.color("editorGroup.dropBackground") } else { self.color("sideBar.background") };
        let label = label.map(|label| div().min_w_0().truncate().pl(px(8.)).line_height(px(TITLE_HEIGHT)).text_size(px(12.)).font_weight(gpui::FontWeight::SEMIBOLD).text_color(self.foreground_or("sideBarTitle.foreground")).child(label));
        div()
            .relative()
            .h(px(TITLE_HEIGHT))
            .flex_none()
            .flex()
            .items_center()
            .px(px(4.))
            .bg(background)
            .debug_selector(|| "pane-composite-title".into())
            .children(label)
            .child(self.pane_composite_actions(part, view_actions, actions, cx))
    }

    /// The container's content and title actions: a single view merged into it (its body, its actions in the
    /// composite title), several as panes with the container's "..." (`MenuId.ViewContainerTitle`).
    fn panel_container_content(&mut self, container: &'static str, window: &mut Window, cx: &mut Context<Self>) -> (AnyElement, Option<AnyElement>) {
        if container == super::extensions_view::VIEWLET_ID {
            let height = self.composite_bar(self.container_location(container)).content_bounds.get().size.height;
            self.layout_extensions_panes(f32::from(height), cx);
            return (self.extensions_view(window, cx).into_any_element(), Some(self.extensions_title_actions(cx).into_any_element()));
        }
        let mut views: Vec<&'static str> = self.views_in(container).into_iter().filter(|view| self.movable_view_shown(view)).map(|view| view.id).collect();
        // testing.contribution.ts: the Test Explorer comes first while `testing.providerCount > 0`.
        if container == super::view_locations::TESTING_CONTAINER && !self.testing.controllers.is_empty() {
            views.insert(0, super::testing_view::TESTING_VIEW);
        }
        if container == super::view_locations::TESTING_CONTAINER && self.selected_coverage().is_some() {
            let after_explorer = usize::from(views.first() == Some(&super::testing_view::TESTING_VIEW));
            views.insert(after_explorer, super::testing_coverage_view::TEST_COVERAGE_VIEW);
        }
        // viewPaneContainer.ts `orientation`: a top or bottom panel lays its panes side by side.
        let part = self.container_location(container);
        let horizontal = part == Part::Panel && self.arrangement().panel.is_horizontal();
        let panes_of = super::view_locations::pane_container(container);
        if let [view] = views[..] {
            let pane = self.movable_view_pane(view, window, cx);
            let body = div().id(view).relative().flex_1().min_h_0().flex().flex_col().child(pane.body);
            return (self.with_pane_drop(body, panes_of, view, horizontal, cx).into_any_element(), pane.actions);
        }
        let content = self.composite_bar(part).content_bounds.get().size;
        let size = f32::from(if horizontal { content.width } else { content.height });
        self.layout_panes(panes_of, size, views.iter().map(|&view| (view, self.view_collapsed_by_default(view))).collect(), horizontal, cx);
        let panes = views.into_iter().map(|view| self.movable_view_pane(view, window, cx)).collect();
        let ordered = self.ordered_panes(&self.panes(panes_of).view.as_ref().expect("laid out above").ids(), panes, window, cx);
        let more = self.has_view_toggle(panes_of.key()).then(|| self.action_bar_item(container, "more", self.view_container_more_actions(panes_of.key(), cx), cx).into_any_element());
        (self.pane_view_element(panes_of, ordered, window, cx).into_any_element(), more)
    }

    fn track_part_drop_target(&mut self, part: Part, over: bool, cx: &mut Context<Self>) {
        let target = if over { Some(part) } else { self.panel.drop_target.filter(|target| *target != part) };
        if self.panel.drop_target != target {
            self.panel.drop_target = target;
            cx.notify();
        }
    }

    fn composite_bar(&self, part: Part) -> &CompositeBar {
        match part {
            Part::AuxiliaryBar => &self.panel.auxiliary_bar,
            _ => &self.panel.panel_bar,
        }
    }

    fn pane_composite_card(&self, part: Part, background: &str) -> Div {
        let card = div().flex_1().min_w_0().flex().flex_col().overflow_hidden().border_1().bg(self.color(background));
        if !self.compact_density() {
            return card.rounded(px(8.)).border_color(self.color("surface.border"));
        }
        let stroke = if part == Part::Panel { "modernPanel.border" } else { "surface.border" };
        card.border_color(gpui::transparent_black()).child(self.compact_card_strokes(stroke, [false, true, true, self.part_at_left_edge(part)], true))
    }

    /// `.composite.title`: the tab strip's background with its bottom line, tabs on the left, then the active view's
    /// title actions, a separator (actionbar.css `.separator`) and the global actions on the right: three tab stops.
    fn pane_composite_title(&self, part: Part, tabs: Vec<AnyElement>, view_actions: Option<(&'static str, AnyElement)>, actions: Vec<GlobalAction>, drop_feedback: bool, cx: &mut Context<Self>) -> Div {
        let tabs_bar = title_bars(part)[0];
        let bottom_line = div().absolute().bottom_0().left_0().right_0().h(px(1.)).bg(self.connected_pane_tab_border());
        let bar = self.composite_bar(part);
        let background = if drop_feedback { self.color("editorGroup.dropBackground") } else { self.tab_strip_background() };
        div()
            .relative()
            .h(px(TITLE_HEIGHT))
            .flex_none()
            .flex()
            .pr(px(4.))
            .bg(background)
            .debug_selector(|| "pane-composite-title".into())
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| workbench.show_bar_context_menu(part, event.position, window, cx)))
            // connectedPaneTabs.css: the title inherits the part's 8px radius inside its 1px border, which leaves a
            // dark sliver between the two arcs; the card clips at its border box (overflow-clip-margin), not tighter.
            .when(!self.compact_density(), |title| title.rounded_t(px(8.)))
            .child(bottom_line)
            .child(size_tracker(bar.title_bounds.clone()))
            .child(self.action_bar(tabs_bar, false, div().h_full().flex().children(tabs), cx))
            .child(self.pane_composite_actions(part, view_actions, actions, cx))
    }

    /// The active view's title actions, a separator (actionbar.css `.separator`) and the part's global actions.
    fn pane_composite_actions(&self, part: Part, view_actions: Option<(&'static str, AnyElement)>, actions: Vec<GlobalAction>, cx: &mut Context<Self>) -> Div {
        let global_bar = title_bars(part)[1];
        let foreground = self.color("icon.foreground");
        let bar = self.composite_bar(part);
        // The actions keep their width: the tab layout measures them, so they must not shrink for tabs that overflow.
        div().relative().flex_none().ml_auto().h_full().flex().items_center().gap(px(4.)).child(size_tracker(bar.actions_bounds.clone())).when_some(view_actions, |bar, (view, view_actions)| {
                // The bar's 4px gap is the separator's right margin.
                bar.child(self.action_bar(view, false, div().flex().items_center().child(view_actions), cx)).child(div().w(px(1.)).h(px(16.)).ml(px(4.)).bg(self.color("disabledForeground")))
            }).child(self.action_bar(global_bar, false, div().flex().items_center().gap(px(4.)).children(actions.into_iter().map(|(icon, title, command, toggled)| {
                let toggled_background = self.theme.color("actionBar.toggledBackground").unwrap_or(self.color("inputOption.activeBackground"));
                let action = self.icon(icon, 22., 16., foreground).id(command).debug_selector(move || command.to_owned()).rounded(px(4.)).cursor_pointer().when(toggled, |action| action.bg(toggled_background)).child(self.action_hover(title, command, HoverOptions::managed())).on_click(cx.listener(
                    move |workbench, _, window, cx| {
                        workbench.execute_command(command, Vec::new(), window, cx);
                    },
                ));
                self.action_bar_item(global_bar, command, action, cx)
            })), cx))
    }

    /// A composite bar tab (`.action-item` with 16px padding); the checked one is the part's own fill, connected to
    /// the content. Its width is the fractional one Chromium lays out: GPUI rounds a text element's width up, which
    /// made the Problems tab with its badge 2px wider than the reference's.
    fn panel_tab(&self, view: &CompositeTab, active: bool, first: bool, divider: bool, background: &str, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
        let foreground = if active { self.foreground_or("panelTitle.activeForeground") } else { self.foreground_or("panelTitle.inactiveForeground") };
        let id = view.id;
        let hover_group = SharedString::from(format!("panel-tab-{id}"));
        // tabs.css `text-transform: none !important` on panel tabs; only the uppercase setting changes them.
        let label = self.view_header_text(view.title, true);
        let dragged = DraggedComposite { id, label: view.title.into(), icon: None, foreground, background: self.color(background) };
        let status_badge = self.tab_status_badge(view).and_then(|content| {
            let foreground = self.foreground_or("activityBarBadge.foreground");
            // paneCompositePart.css: a progress badge's 16px circle around the 13px mask, an icon badge's 3px padding
            // around the codicon at the `.badge-content` 10px font size.
            let glyph = match content {
                BadgeContent::Progress => super::activity::progress_badge_icon(foreground),
                BadgeContent::Icon(icon) => self.badge_icon(icon, 10., foreground),
                BadgeContent::Text(_) => return None,
            };
            Some(div().debug_selector(|| "panel-tab-status-badge".into()).ml(px(2.)).flex_none().size(px(16.)).flex().items_center().justify_center().rounded(px(8.)).bg(self.color("activityBarBadge.background")).child(glyph))
        });
        let badge = self.painted_tab_badge(view).filter(|_| status_badge.is_none()).map(|badge| {
            let count = badge.number;
            let text = count.to_string();
            let text_width = text_width(&text, 10., window);
            let width = badge_width(text_width);
            // paneCompositePart.css `.badge` 2px from the label, `.badge-content` 10px text centered with 3px 5px padding.
            div()
                .ml(px(2.))
                .flex_none()
                .w(px(width))
                .h(px(16.))
                .pl(px((width - text_width) / 2.))
                .flex()
                .items_center()
                .rounded(px(8.))
                .text_size(px(10.))
                .whitespace_nowrap()
                .bg(self.color("activityBarBadge.background"))
                .text_color(self.foreground_or("activityBarBadge.foreground"))
                .child(text)
        });
        div()
            .id(id)
            .relative()
            .h_full()
            .flex_none()
            .w(px(panel_tab_width(view, self, window)))
            .pl(px(16.))
            .flex()
            .items_center()
            .cursor_pointer()
            .text_color(foreground)
            .when(active, |tab| tab.child(self.connected_pane_tab_fill(first, false, background)))
            .when(!active, |tab| tab.hover(|tab| tab.text_color(self.foreground_or("modernTab.hoverForeground"))).child(self.inactive_pane_tab_hover(&hover_group, false)).group(hover_group.clone()))
            // connectedPaneTabs.css `.tab-divider`: 1x16px between two inactive tabs, transparent without `tab.divider`.
            .when_some(self.theme.tab_divider().filter(|_| divider), |tab, color| {
                tab.child(div().debug_selector(|| "panel-tab-divider".into()).absolute().left_0().top(px((TITLE_HEIGHT - 16.) / 2.)).w(px(1.)).h(px(16.)).bg(color))
            })
            .child(div().flex_none().w(px(text_width(&label, 13., window))).whitespace_nowrap().line_height(px(24.)).child(label))
            .children(status_badge)
            .children(badge)
            .child(self.panel_tab_hover(view, window))
            .on_drag(dragged, |dragged, _, _, cx| cx.new(|_| dragged.clone()))
            .on_click(cx.listener(move |workbench, _, window, cx| match workbench.panel.views.iter().find(|view| view.id == id) {
                Some(view) => (view.open)(workbench, window, cx),
                None => workbench.show_view_container(id, cx),
            }))
    }

    /// connectedPaneTabs.css `--modern-ui-connected-tab-border`: `modernPanel.border`, `contrastBorder` in high contrast.
    pub(super) fn connected_pane_tab_border(&self) -> Rgba {
        match self.theme.kind {
            ThemeKind::HighContrastDark | ThemeKind::HighContrastLight => self.color("contrastBorder"),
            _ => self.color("modernPanel.border"),
        }
    }

    /// modernUI tabs.css: a hovered inactive tab's `.active-item-indicator`, 24px high and inset 2px at the sides, in
    /// modernTab.hoverBackground; a dashed contrastActiveBorder outline in high contrast. An icon tab's is 24px square
    /// and centered (connectedPaneTabs.css).
    pub(super) fn inactive_pane_tab_hover(&self, group: &SharedString, icon: bool) -> Div {
        let indicator = div().absolute().top(px((TITLE_HEIGHT - 24.) / 2.)).h(px(24.)).rounded(px(4.));
        let indicator = if icon { indicator.left(px((ICON_TAB_WIDTH - 24.) / 2.)).w(px(24.)) } else { indicator.left(px(2.)).right(px(2.)) };
        if self.theme.kind.is_high_contrast() {
            let border = self.color("contrastActiveBorder");
            return indicator.border_1().border_dashed().border_color(gpui::transparent_black()).group_hover(group.clone(), move |indicator| indicator.border_color(border));
        }
        let background = self.color("modernTab.hoverBackground");
        indicator.group_hover(group.clone(), move |indicator| indicator.bg(background))
    }

    /// connectedPaneTabs.css: the checked tab's `.active-item-indicator` from `top: -strokeWidth` with its
    /// `.tab-connected-edge` and the 7px shoulders curving into the strip's bottom line. The first tab meets the part's
    /// corner: no left edge or shoulder, its outer left corner square in compact density. A footer's tab opens upward
    /// (`.footer`, `scaleY(-1)`).
    pub(super) fn connected_pane_tab_fill(&self, first: bool, footer: bool, background: &str) -> Div {
        let surface = self.color(background);
        let border = self.connected_pane_tab_border();
        let radius = px(7.);
        let fill = div().absolute().left_0().right_0().bg(surface).border_r_1().border_color(border).when(!first, |fill| fill.border_l_1());
        let round_left = !(first && self.compact_density());
        let fill = match footer {
            false => fill.top(px(-1.)).bottom_0().border_t_1().rounded_tr(radius).when(round_left, |fill| fill.rounded_tl(radius)),
            true => fill.top_0().bottom(px(-1.)).border_b_1().rounded_br(radius).when(round_left, |fill| fill.rounded_bl(radius)),
        };
        let shoulder = |piece: Div| match footer {
            false => piece.absolute().bottom_0().size(radius).bg(surface),
            true => piece.absolute().top_0().size(radius).bg(surface),
        };
        let strip_corner = || match footer {
            false => div().size_full().bg(self.tab_strip_background()).border_b_1().border_color(border),
            true => div().size_full().bg(self.tab_strip_background()).border_t_1().border_color(border),
        };
        let left_corner = if footer { strip_corner().border_r_1().rounded_tr(radius) } else { strip_corner().border_r_1().rounded_br(radius) };
        let right_corner = if footer { strip_corner().border_l_1().rounded_tl(radius) } else { strip_corner().border_l_1().rounded_bl(radius) };
        div()
            .absolute()
            .inset_0()
            .child(fill.debug_selector(|| "active-composite-tab".into()))
            .when(!first, |tab| tab.child(shoulder(div().left(-radius)).child(left_corner)))
            .child(shoulder(div().right(-radius)).child(right_corner))
    }

    /// compositeBarActions.ts `computeTitle`: the name and the keybinding of the open command of the container's
    /// first view that has one (viewContainerModel.ts `keybindingId`), above a bottom panel, else below.
    fn panel_tab_hover(&self, tab: &CompositeTab, window: &Window) -> impl IntoElement {
        let part = self.container_location(tab.id);
        let position = if part == Part::Panel && self.arrangement().panel == Position::Bottom && !self.is_panel_maximized() { HoverPosition::Above } else { HoverPosition::Below };
        let command = match tab.view {
            super::problems_view::MARKERS_VIEW_ID => Some("workbench.actions.view.problems"),
            super::output_view::OUTPUT_VIEW_ID => Some("workbench.action.output.toggleOutput"),
            "workbench.panel.repl.view" => Some("workbench.debug.action.toggleRepl"),
            "terminal" => Some("workbench.action.terminal.toggleTerminal"),
            _ => None,
        };
        // compositeBarActions.ts `computeTitle`: the name with its keybinding, then " - " and the badge's description.
        let content = match (command, self.tab_badge(tab)) {
            (Some(command), None) => HoverContent::Action { title: tab.title, command },
            (None, None) => HoverContent::Text(tab.title.to_string()),
            (command, Some(badge)) => {
                let title = command.map_or(tab.title.to_string(), |command| self.keybindings.resolver.append_keybinding(tab.title, command, &self.key_context(window)));
                HoverContent::Text(format!("{title} - {}", badge.description))
            }
        };
        self.hover_target(SharedString::from(format!("composite-tab-hover-{}", tab.id)), content, HoverOptions::composite_bar(position))
    }

    /// compositeBar.ts `updateCompositeSwitcher`: the tabs that fit before the title actions (the active one kept,
    /// room made for the overflow action), on the sizes painted last frame; every tab before the first paint. The tabs
    /// are laid out again when the title's width, the tabs or the active view change, and when the title actions grow
    /// (a started terminal's actions); not when they shrink, as the reference (View as Table drops Collapse All without
    /// bringing Terminal back).
    fn tabs_that_fit(&self, part: Part, active: Option<&'static str>, window: &Window) -> Vec<&'static str> {
        let icon_bar = self.icon_composite_bar(part).is_some();
        let tabs: Vec<(&'static str, f32)> = self.part_tabs(part).into_iter().map(|view| (view.id, if icon_bar { ICON_TAB_WIDTH } else { panel_tab_width(&view, self, window) })).collect();
        let bar = self.composite_bar(part);
        let title = bar.title_bounds.get().size.width;
        if title <= px(0.) {
            return tabs.into_iter().map(|(id, _)| id).collect();
        }
        // paneCompositePart.ts `layoutCompositeBar` outside the title: 8px padding and the part's 1px border, no
        // toolbars; auxiliaryBarPart.ts `overflowActionSize` 30.
        if icon_bar {
            return fitting_tabs(&tabs, active, (f32::from(title) - 9.).max(MIN_COMPOSITE_BAR_WIDTH), 30.);
        }
        // paneCompositePart.ts `layoutCompositeBar`: 16px title padding, the toolbars and their 8px padding. The filter
        // box counts at its 200px resting width: the reference lays the tabs out on resize, not when the box grows on focus.
        let filter = f32::from(bar.filter_bounds.replace(Bounds::default()).size.width);
        let filter_basis = if filter > 0. { FILTER_MAX_WIDTH } else { 0. };
        let other_actions = f32::from(bar.actions_bounds.get().size.width) - filter;
        let key = (title, tabs.iter().map(|(id, _)| *id).collect(), active, filter > 0.);
        let cached = bar.tab_layout.borrow().as_ref().filter(|(cached, actions, _)| *cached == key && other_actions <= *actions + 0.5).map(|(_, _, shown)| shown.clone());
        let shown = match cached {
            Some(shown) => shown,
            None => {
                let limit = f32::from(title) - 16. - (other_actions + filter_basis) - 8.;
                let shown = fitting_tabs(&tabs, active, limit.max(MIN_COMPOSITE_BAR_WIDTH), overflow_action_size(part));
                // The first frames paint the actions before they are measured, and a newly active view's actions a frame later.
                if other_actions > 0. && bar.actions_view.get() == active {
                    *bar.tab_layout.borrow_mut() = Some((key, other_actions, shown.clone()));
                }
                shown
            }
        };
        let tabs_width: f32 = tabs.iter().filter(|(id, _)| shown.contains(id)).map(|(_, width)| width).sum();
        bar.filter_room.set(filter_room(f32::from(title), tabs_width, shown.len() < tabs.len(), other_actions));
        shown
    }

    /// viewPane.ts `FilterViewPane.shouldShowFilterInHeader`: the filter leaves the title for the top of the view
    /// when the view is narrower than 600px and taller than 100px; before the first paint it is in the title.
    pub(super) fn view_filter_in_header(&self, container: &str) -> bool {
        let size = self.filter_view_size(container);
        !(size.width < px(600.) && size.height > px(100.))
    }

    /// viewFilter.ts `layout`: below 400px of view width the filter is `.small` and hides its badge.
    pub(super) fn view_filter_small(&self, container: &str) -> bool {
        let width = self.filter_view_size(container).width;
        width > px(0.) && width < px(400.)
    }

    /// The size of the panel container's view: the part's content, or its pane's share of it when the view lies
    /// among other views of a panel container.
    fn filter_view_size(&self, container: &str) -> gpui::Size<Pixels> {
        let mut size = self.composite_bar(self.container_location(container)).content_bounds.get().size;
        let Some(view) = self.panel.views.iter().find(|view| view.id == container).map(|view| view.view_id) else { return size };
        let Some(holder) = self.movable_view(view).map(|movable| self.view_container(&movable)) else { return size };
        if self.views_in(holder).iter().filter(|view| self.movable_view_shown(view)).count() < 2 {
            return size;
        }
        let Some(panes) = self.generated_panes.get(holder).and_then(|panes| panes.view.as_ref()) else { return size };
        let Some(index) = panes.ids().iter().position(|id| *id == view) else { return size };
        let pane = panes.sizes()[index];
        match panes.is_horizontal() {
            true => size.width = px(pane),
            false => size.height = px(pane - super::view_panes::HEADER_SIZE),
        }
        size
    }

    /// views.css `.viewpane-filter-container` in a panel title: 200px, and while focused up to 400px of the room the
    /// tabs leave.
    pub(super) fn panel_filter_width(&self, container: &str, focused: bool) -> f32 {
        match focused {
            true => self.composite_bar(self.container_location(container)).filter_room.get().clamp(FILTER_MIN_WIDTH, 400.),
            false => FILTER_MAX_WIDTH,
        }
    }

    /// Measures a view's filter box in the title for the tab layout.
    pub(super) fn panel_filter_tracker(&self, container: &str) -> impl IntoElement {
        super::output_view::bounds_tracker(self.composite_bar(self.container_location(container)).filter_bounds.clone())
    }

    /// compositeBarActions.ts `CompositeOverflowActivityActionViewItem`: the "..." item listing the tabs that do not fit.
    fn panel_overflow_action(&self, part: Part, actions: Vec<MenuAction>, cx: &mut Context<Self>) -> Stateful<Div> {
        let bounds = self.composite_bar(part).overflow_bounds.clone();
        let foreground = self.foreground_or("panelTitle.inactiveForeground");
        div()
            .id("additionalComposites.action")
            .relative()
            .h_full()
            .px(px(3.))
            .flex()
            .items_center()
            .cursor_pointer()
            .child(self.icon("ellipsis", 22., 16., foreground))
            .child(self.action_hover("Additional Views", "additionalComposites.action", HoverOptions::instant()))
            .child(super::output_view::bounds_tracker(bounds.clone()))
            .on_mouse_down(MouseButton::Left, cx.listener({
                let (actions, bounds) = (actions.clone(), bounds.clone());
                move |workbench, _: &MouseDownEvent, window, cx| {
                    cx.stop_propagation();
                    workbench.show_context_menu_actions(actions.clone(), &Default::default(), bounds.get(), Vec::new(), window, cx);
                }
            }))
            // Enter and Space on the focused item: gpui's keyboard click.
            .on_click(cx.listener(move |workbench, event: &gpui::ClickEvent, window, cx| {
                if event.is_keyboard() {
                    workbench.show_context_menu_actions(actions.clone(), &Default::default(), bounds.get(), Vec::new(), window, cx);
                }
            }))
    }

    /// paneCompositePart.ts `.empty-pane-message-area`, in `editorGroup.dropBackground` while a tab is dragged over the part.
    fn empty_pane_message(&self, drop_feedback: bool) -> Div {
        div()
            .flex_1()
            .flex()
            .items_center()
            .justify_center()
            .text_color(self.foreground_or("foreground"))
            .when(drop_feedback, |message| message.bg(self.color("editorGroup.dropBackground")))
            .child("Drag a view here to display.")
    }
}

/// A container's tab: its id, title and the view whose name and badge it shows.
pub(super) struct CompositeTab {
    pub id: &'static str,
    pub title: &'static str,
    pub view: &'static str,
}

impl Workbench {
    /// The activity count of the tab's view (`IActivity.badge`).
    fn tab_badge(&self, tab: &CompositeTab) -> Option<NumberBadge> {
        if let Some(view) = self.panel.views.iter().find(|view| view.view_id == tab.view) {
            return (view.badge)(self).filter(|badge| badge.number > 0);
        }
        // The side bar's Extensions and Testing moved here keep their number badges.
        match tab.id {
            super::extensions_view::VIEWLET_ID => self.extensions_badge().map(|(number, description)| NumberBadge { number, description }),
            super::view_locations::TESTING_CONTAINER => match self.testing_badge() {
                Some(super::activity::Badge::Number(number)) => Some(NumberBadge { number: number as usize, description: self.testing_badge_description(number) }),
                _ => None,
            },
            _ => None,
        }
    }

    /// compositeBarActions.ts `getVisibleBadges`: the container's progress badge, else its first icon badge, over its
    /// number badges.
    fn tab_status_badge(&self, tab: &CompositeTab) -> Option<BadgeContent> {
        let mut badges = self.container_badges(tab.id);
        if tab.id == super::view_locations::TESTING_CONTAINER {
            badges.extend(self.testing_badge());
        }
        visible_badge(&badges).filter(|content| !matches!(content, BadgeContent::Text(_)) && self.badges_enabled(tab.id))
    }

    /// compositeBarActions.ts `updateActivity`: the badge shows while the container's badges are enabled.
    fn painted_tab_badge(&self, tab: &CompositeTab) -> Option<NumberBadge> {
        self.tab_badge(tab).filter(|_| self.badges_enabled(tab.id))
    }
}

/// compositeBarActions.ts `getActions`: a tab's name with its number badge, "{0} ({1})".
fn panel_tab_label(view: &CompositeTab, workbench: &Workbench) -> String {
    match workbench.tab_badge(view) {
        Some(badge) => format!("{} ({})", view.title, badge.number),
        None => view.title.to_string(),
    }
}

/// The width `panel_tab` paints: 16px padding each side, the title, and the badge 2px after it.
fn panel_tab_width(view: &CompositeTab, workbench: &Workbench, window: &Window) -> f32 {
    let badge = match workbench.tab_status_badge(view) {
        Some(_) => 18.,
        None => workbench.painted_tab_badge(view).map_or(0., |badge| 2. + badge_width(text_width(&badge.number.to_string(), 10., window))),
    };
    32. + text_width(&workbench.view_header_text(view.title, true), 13., window) + badge
}

/// `.badge-content`: `min-width: 16px` around the text and its 5px side padding.
fn badge_width(text_width: f32) -> f32 {
    (text_width + 10.).max(16.)
}

/// panelPart.ts and auxiliaryBarPart.ts `overflowActionSize` with the composite bar in the title.
fn overflow_action_size(part: Part) -> f32 {
    match part {
        Part::AuxiliaryBar => 40.,
        _ => 44.,
    }
}

fn text_width(text: &str, size: f32, window: &Window) -> f32 {
    let run = TextRun { len: text.len(), font: window.text_style().font(), color: gpui::black(), background_color: None, underline: None, strikethrough: None };
    f32::from(window.text_system().shape_line(text.to_string().into(), px(size), &[run], None).width)
}

/// compositeBar.ts `updateCompositeSwitcher` on `(id, width)` tabs in order.
fn fitting_tabs(tabs: &[(&'static str, f32)], active: Option<&'static str>, limit: f32, overflow_action_size: f32) -> Vec<&'static str> {
    let width = |id: &str| tabs.iter().find(|(tab, _)| *tab == id).map_or(0., |(_, width)| *width);
    let mut size = 0.;
    let mut shown = Vec::new();
    for (id, width) in tabs {
        if size + width > limit {
            break;
        }
        size += width;
        shown.push(*id);
    }
    if let Some(active) = active.filter(|active| tabs.iter().any(|(id, _)| id == active) && !shown.contains(active)) {
        size += width(active);
        shown.push(active);
    }
    while size > limit && !shown.is_empty() {
        let removed = if shown.len() > 1 { shown.remove(shown.len() - 2) } else { shown.pop().unwrap() };
        size -= width(removed);
    }
    if tabs.len() > shown.len() {
        size += overflow_action_size;
    }
    while size > limit && !shown.is_empty() {
        let removed = if shown.len() > 1 && shown.last().copied() == active { shown.remove(shown.len() - 2) } else { shown.pop().unwrap() };
        size -= width(removed);
    }
    shown
}

/// Records the painted bounds and draws again when the size changed, so a layout reading them catches up at once.
fn size_tracker(bounds: Rc<Cell<Bounds<Pixels>>>) -> impl IntoElement {
    gpui::canvas(
        move |painted, window, cx| {
            if bounds.get().size != painted.size {
                super::part_view::redraw_after_frame(window, cx);
            }
            bounds.set(painted);
        },
        |_, _, _, _| {},
    )
    .absolute()
    .size_full()
}

/// The room of a focused filter box (`.grow`) once the DOM laid out the shown tabs, the 28px "..." item,
/// `.title-actions`' 4px left padding, the other title actions and the title's 4px right padding.
fn filter_room(title: f32, tabs: f32, overflow: bool, other_actions: f32) -> f32 {
    let overflow = if overflow { OVERFLOW_ITEM_WIDTH } else { 0. };
    title - tabs - overflow - 4. - other_actions - 4.
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_focused_filter_takes_the_room_the_tabs_leave() {
        // The reference at 1024x768: a 710px title, Problems, Output and Debug Console, the "..." item, the filter's
        // 4px margin, two actions, the separator and the global actions (port/results/problems.md).
        assert_eq!(filter_room(710., 306., true, 113.), 255.);
    }

    const TABS: [(&str, f32); 4] = [("problems", 100.), ("output", 80.), ("debug", 120.), ("terminal", 90.)];

    #[test]
    fn every_tab_shows_when_they_fit() {
        assert_eq!(fitting_tabs(&TABS, Some("problems"), 390., 44.), ["problems", "output", "debug", "terminal"]);
    }

    #[test]
    fn the_tail_overflows_with_room_for_the_overflow_action() {
        // 300 fits three tabs, the overflow action's 44px pushes the third out.
        assert_eq!(fitting_tabs(&TABS, Some("problems"), 300., 44.), ["problems", "output"]);
    }

    #[test]
    fn the_active_tab_stays_and_the_one_before_it_goes() {
        assert_eq!(fitting_tabs(&TABS, Some("terminal"), 300., 44.), ["problems", "terminal"]);
    }

    /// extensionsViewlet.ts and testingExplorerView.ts badge their container wherever it is: moved to the panel, the
    /// Extensions and Testing tabs show the counts the activity bar items showed.
    #[gpui::test]
    fn moved_extensions_and_testing_tabs_keep_their_badges(cx: &mut gpui::TestAppContext) {
        use crate::testing::{ResultState, TestResult};
        let (workbench, cx, ..) = crate::workbench::goto_symbol::tests::open(cx, "panel-moved-badges", "");
        workbench.update_in(cx, |workbench, window, cx| {
            let location = std::path::PathBuf::from("/pub.a");
            workbench.extensions_viewlet.installed = vec![exthost::scan::ScannedExtension { id: "pub.a".into(), location, description: json!({ "name": "a", "isBuiltin": false }) }];
            let mut result = TestResult::new("r1".into(), json!({}));
            result.add_task(&json!({ "id": "t", "name": "task", "ctrlId": "c" }));
            for id in ["a", "b"] {
                result.add_chain(&[json!({ "extId": id, "label": id })]);
                result.update_state(id, "t", ResultState::Failed, None);
            }
            result.mark_complete(1);
            workbench.testing.results.insert(0, result);
            workbench.testing.controllers.insert("port".into(), crate::workbench::testing_service::Controller { label: "Port".into(), capabilities: 0 });
            workbench.move_view_container(crate::workbench::extensions_view::VIEWLET_ID, Part::Panel, window, cx);
            workbench.move_view_container(crate::workbench::view_locations::TESTING_CONTAINER, Part::Panel, window, cx);
        });
        cx.run_until_parked();
        let labels = workbench.read_with(cx, |workbench, _| workbench.part_tabs(Part::Panel).iter().map(|tab| panel_tab_label(tab, workbench)).collect::<Vec<_>>());
        assert!(labels.contains(&"Extensions (1)".to_owned()) && labels.contains(&"Testing (2)".to_owned()), "{labels:?}");
        let descriptions = workbench.read_with(cx, |workbench, _| workbench.part_tabs(Part::Panel).iter().filter_map(|tab| workbench.tab_badge(tab)).map(|badge| badge.description).collect::<Vec<_>>());
        assert!(descriptions.contains(&"2 failed tests".to_owned()), "{descriptions:?}");
    }

    /// connectedPaneTabs.css `.title:first-child { border-top-left-radius: inherit }`: the title rounds its top corners
    /// at the part's 8px; square, it filled the card's corners outside the border (port/results/corners.md panel-tl).
    #[gpui::test]
    fn the_title_inherits_the_cards_radius(cx: &mut gpui::TestAppContext) {
        let (workbench, cx, ..) = crate::workbench::goto_symbol::tests::open(cx, "panel-title-corners", "");
        workbench.update(cx, |workbench, cx| {
            for part in [Part::Panel, Part::AuxiliaryBar] {
                let mut title = workbench.pane_composite_title(part, Vec::new(), None, Vec::new(), false, cx);
                let radii = &title.style().corner_radii;
                assert_eq!((radii.top_left, radii.top_right), (Some(px(8.).into()), Some(px(8.).into())));
            }
        });
    }

    /// connectedPaneTabs.css: the checked tab's indicator sits at `top: -strokeWidth`, so its top stroke covers the
    /// card's instead of drawing a second line under it, and it still reaches the title's bottom edge.
    #[gpui::test]
    fn the_active_tab_starts_on_the_cards_top_stroke(cx: &mut gpui::TestAppContext) {
        let (workbench, cx, ..) = crate::workbench::goto_symbol::tests::open(cx, "panel-active-tab", "");
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.terminal.new", Vec::new(), window, cx)));
        cx.run_until_parked();
        let title = cx.debug_bounds("pane-composite-title").unwrap();
        let tab = cx.debug_bounds("active-composite-tab").unwrap();
        assert_eq!((tab.top(), tab.bottom()), (title.top() - px(1.), title.bottom()));
    }
}