Skip to content

Visual Studio Code, rebuilt in Rust

Rust
9.4 KB
Raw Blame
//! actionbar.ts keyboard navigation: each bar's items take the focus one at a time, the arrows of the bar's
//! orientation, Home and End move it, Enter and Space press the focused item, and showHover shows its hover.
//! A bar is one tab stop (roving tabindex): the item it last focused, else its first.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use gpui::{App, BorderStyle, Bounds, Context, Div, FocusHandle, InteractiveElement, KeyDownEvent, MouseButton, ParentElement, Pixels, Stateful, Styled, IntoElement, Window, canvas, fill, outline, px};

use super::Workbench;

#[derive(Default)]
pub(super) struct ActionBars {
    pub(super) handles: RefCell<HashMap<(&'static str, String), FocusHandle>>,
    /// Each bar's items in the last frame's order, with their bounds.
    drawn: Rc<RefCell<HashMap<&'static str, Vec<DrawnItem>>>>,
    /// Each bar's items from the last frame that drew any, for the roving tab stop of a bar cleared before its items.
    previous: RefCell<HashMap<&'static str, Vec<DrawnItem>>>,
    /// actionbar.ts `focusedItem`: the item the bar gives the focus back to.
    last: HashMap<&'static str, FocusHandle>,
    /// The names of an editor window's own bars, by the main window's name and the window's part.
    part_bars: RefCell<HashMap<(&'static str, u32), &'static str>>,
}

struct DrawnItem {
    focus: FocusHandle,
    bounds: Bounds<Pixels>,
}

impl Workbench {
    /// The bar's container with its key handler; rendering it forgets the items the last frame drew.
    pub(super) fn action_bar(&self, bar: &'static str, vertical: bool, container: Div, cx: &mut Context<Self>) -> Div {
        self.forget_action_bar_items(bar);
        container.on_key_down(cx.listener(move |workbench, event: &KeyDownEvent, window, cx| workbench.action_bar_key(bar, vertical, event, window, cx)))
    }

    /// One item of the bar: it takes the focus, keeps a mouse press from taking it (actionViewItems.ts stops the
    /// mouse down), and draws the focused label's 1px `focusBorder` outline (workbench.css) inside it. `own_tab_stop`:
    /// the item is a tab stop of its own, as each tab's close actions (one action bar per tab).
    pub(super) fn action_bar_item(&self, bar: &'static str, key: &str, item: Stateful<Div>, cx: &App) -> Stateful<Div> {
        self.action_bar_item_with_tab_stop(bar, key, false, item, cx)
    }

    pub(super) fn action_bar_item_with_tab_stop(&self, bar: &'static str, key: &str, own_tab_stop: bool, item: Stateful<Div>, cx: &App) -> Stateful<Div> {
        let focus = self.action_bar_focus(bar, key, cx);
        let tab_stop = own_tab_stop || self.is_roving_tab_stop(bar, &focus);
        let drawn = self.action_bars.drawn.clone();
        let border = self.theme.color("focusBorder");
        let painted = focus.clone();
        // `activity_item_focus_indicator` draws the activity bar's, which depends on the item being checked.
        let own_indicator = bar == "activity";
        item.relative()
            .track_focus(&focus.clone().tab_stop(tab_stop))
            .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
            .child(
                canvas(move |bounds, _, _| drawn.borrow_mut().entry(bar).or_default().push(DrawnItem { focus, bounds }), move |bounds, _, window, _| {
                    if let Some(border) = border.filter(|_| !own_indicator && painted.is_focused(window)) {
                        window.paint_quad(outline(bounds, border, BorderStyle::Solid));
                    }
                })
                .absolute()
                .top_0()
                .left_0()
                .size_full(),
            )
    }

    /// actionbar.ts `setFocusable`/`focus`: the item with `tabIndex = 0`, the bar's `focusedItem`, else its first item.
    /// A bar not drawn yet makes every item a stop for its first frame.
    fn is_roving_tab_stop(&self, bar: &'static str, focus: &FocusHandle) -> bool {
        let drawn = self.action_bars.drawn.borrow();
        let previous = self.action_bars.previous.borrow();
        let Some(items) = drawn.get(bar).filter(|items| !items.is_empty()).or_else(|| previous.get(bar)) else { return true };
        let last = self.action_bars.last.get(bar).filter(|last| items.iter().any(|item| &item.focus == *last));
        last.unwrap_or(&items[0].focus) == focus
    }

    /// activityaction.css: a focused checked activity item's label has a rounded `focusBorder` outline outside it, an
    /// unchecked one the 2px `activityBar.activeBorder` indicator on its left edge.
    pub(super) fn activity_item_focus_indicator(&self, key: &str, checked: bool, cx: &App) -> impl IntoElement {
        let focus = self.action_bar_focus("activity", key, cx);
        let border = self.theme.color("focusBorder");
        let indicator = self.theme.color("activityBar.activeBorder");
        canvas(|_, _, _| {}, move |bounds, _, window, _| {
            if !focus.is_focused(window) {
                return;
            }
            let quad = match (checked, border, indicator) {
                (true, Some(border), _) => outline(bounds.dilate(px(1.)), border, BorderStyle::Solid).corner_radii(px(4.)),
                (false, _, Some(indicator)) => fill(Bounds::new(bounds.origin, gpui::size(px(2.), bounds.size.height)), indicator),
                _ => return,
            };
            window.paint_quad(quad);
        })
        .absolute()
        .top_0()
        .left_0()
        .size_full()
    }

    pub(super) fn action_bar_focus(&self, bar: &'static str, key: &str, cx: &App) -> FocusHandle {
        self.action_bars.handles.borrow_mut().entry((bar, key.to_owned())).or_insert_with(|| cx.focus_handle()).clone()
    }

    /// `bar` of an editor window's part, with its own items and focus.
    pub(super) fn part_action_bar(&self, bar: &'static str, part: u32) -> &'static str {
        // shortcut: leaks one short name per bar and editor window opened; make bar names owned if windows churn.
        self.action_bars.part_bars.borrow_mut().entry((bar, part)).or_insert_with(|| format!("{bar}-{part}").leak())
    }

    /// Forgets the items the last frame drew in a bar drawn without `action_bar`'s container.
    pub(super) fn forget_action_bar_items(&self, bar: &'static str) {
        let drawn = self.action_bars.drawn.borrow_mut().insert(bar, Vec::new());
        if let Some(drawn) = drawn.filter(|items| !items.is_empty()) {
            self.action_bars.previous.borrow_mut().insert(bar, drawn);
        }
    }

    /// Where the last frame drew the bar's item `key`.
    pub(super) fn drawn_action_bar_item_bounds(&self, bar: &'static str, key: &str, cx: &App) -> Bounds<Pixels> {
        let focus = self.action_bar_focus(bar, key, cx);
        self.action_bars.drawn.borrow()[bar].iter().find(|item| item.focus == focus).expect("an item the last frame drew").bounds
    }

    /// The bar's items the last frame drew, in their order.
    #[cfg(test)]
    pub(super) fn drawn_action_bar_items(&self, bar: &'static str) -> Vec<FocusHandle> {
        self.action_bars.drawn.borrow().get(bar).map(|items| items.iter().map(|item| item.focus.clone()).collect()).unwrap_or_default()
    }

    /// actionbar.ts `focus()`: the item that last had the focus, else the first.
    pub(super) fn focus_action_bar(&mut self, bar: &'static str, window: &mut Window, cx: &mut Context<Self>) -> bool {
        let drawn = self.action_bars.drawn.borrow();
        let Some(items) = drawn.get(bar).filter(|items| !items.is_empty()) else { return false };
        let last = self.action_bars.last.get(bar).and_then(|last| items.iter().find(|item| &item.focus == last));
        let focus = last.unwrap_or(&items[0]).focus.clone();
        drop(drawn);
        window.focus(&focus, cx);
        self.action_bars.last.insert(bar, focus);
        true
    }

    /// actionbar.ts `onKeyDown`: the previous and next keys of the orientation loop around, Home and End jump.
    fn action_bar_key(&mut self, bar: &'static str, vertical: bool, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
        let drawn = self.action_bars.drawn.borrow();
        let Some(items) = drawn.get(bar) else { return };
        let Some(current) = items.iter().position(|item| item.focus.is_focused(window)) else { return };
        let (previous, next) = if vertical { ("up", "down") } else { ("left", "right") };
        let last = items.len() - 1;
        let target = match event.keystroke.key.as_str() {
            key if key == previous => if current == 0 { last } else { current - 1 },
            key if key == next => if current == last { 0 } else { current + 1 },
            "home" => 0,
            "end" => last,
            _ => return,
        };
        let focus = items[target].focus.clone();
        drop(drawn);
        cx.stop_propagation();
        window.focus(&focus, cx);
        self.action_bars.last.insert(bar, focus);
        self.dismiss_hover(cx);
        self.hover_focused_action_item(window, cx);
    }

    /// The bar holding the focused item.
    pub(super) fn focused_action_bar(&self, window: &Window) -> Option<&'static str> {
        let drawn = self.action_bars.drawn.borrow();
        drawn.iter().find(|(_, items)| items.iter().any(|item| item.focus.is_focused(window))).map(|(bar, _)| *bar)
    }

    /// The focused bar item's bounds as last drawn.
    pub(super) fn focused_action_bar_item(&self, window: &Window) -> Option<Bounds<Pixels>> {
        let drawn = self.action_bars.drawn.borrow();
        drawn.values().flatten().find(|item| item.focus.is_focused(window)).map(|item| item.bounds)
    }
}