Skip to content

Visual Studio Code, rebuilt in Rust

Rust
23.6 KB
Raw Blame
//! base/browser/ui/icons/iconSelectBox.ts `IconSelectBox` and workbench/services/userDataProfile/browser/iconSelectBox.ts
//! `WorkbenchIconSelectBox`: the "Search icons" input over a grid of icons. The Profiles editor's `ProfileIconRenderer`
//! shows userDataProfileIcons.ts `ICONS` in a sticky hover below the profile's icon; iconPicker.ts `IconPicker` (Terminal:
//! Change Icon) shows every codicon in a quick widget, with the focused icon's name and a reset button.

use std::cell::Cell;
use std::rc::Rc;
use std::sync::LazyLock;

use gpui::{AnyElement, Bounds, Context, FocusHandle, Keystroke, Pixels, ScrollHandle, Size, Window, div, point, prelude::*, px};

use super::Workbench;
use super::hover::{HoverOptions, layout_hover};
use super::input_box_view::{InputId, InputLook, InputView};
use crate::commands::Outcome;
use crate::input_box::InputBox;

/// userDataProfileIcons.ts `ICONS`, as codicon ids.
pub const ICONS: [&str; 83] = [
    "vm", "server", "record-keys", "device-mobile", "watch", "vr", "piano", "ruby", "code", "coffee", "snake", "project", "window", "library", "extensions", "terminal",
    "terminal-debian", "terminal-linux", "terminal-ubuntu", "beaker", "package", "cloud", "book", "globe", "database", "notebook", "robot", "game", "chip", "music",
    "remote-explorer", "github", "azure", "vscode", "copilot", "gift", "send", "bookmark", "briefcase", "megaphone", "comment", "telescope", "credit-card", "map",
    "device-camera-video", "unmute", "law", "graph-line", "heart", "home", "inbox", "mortar-board", "rocket", "magnet", "lock", "milestone", "tag", "pulse",
    "radio-tower", "smiley", "zap", "squirrel", "symbol-color", "mail", "key", "pie-chart", "organization", "preview", "wand", "star-empty", "lightbulb",
    "symbol-ruler", "dashboard", "calendar", "shield", "verified", "debug", "flame", "compass", "paintcan", "archive", "mic", "jersey",
];

/// iconPicker.ts `pickIcons`' icons: the codicons but `blank`, one id per font character, from
/// port/tools/gen-icon-registry.ts.
static PICKER_ICONS: LazyLock<Vec<String>> = LazyLock::new(|| serde_json::from_str(include_str!("../icon_picker.json")).expect("icon_picker.json is a list of ids"));

/// userDataProfileIcons.ts `DEFAULT_ICON` (`settings-view-bar-icon`, drawn as the settings gear).
pub const DEFAULT_ICON: &str = "settings-view-bar-icon";

/// `ProfileIconRenderer`'s `iconSelectBox.layout(new Dimension(486, 292))`.
const WIDTH: f32 = 486.;
const HEIGHT: f32 = 292.;
/// `IconPicker`'s `grid.layout(new Dimension(width, 300))`.
const PICKER_HEIGHT: f32 = 300.;
/// `iconContainerWidth` and `iconContainerHeight`.
const ICON_BOX: f32 = 36.;
/// codicon.css sets the glyph's own 16px over `.icon-container`'s 20px.
const GLYPH_SIZE: f32 = 16.;

/// What the picker sets the icon of: an existing profile by id, the new profile form, or a terminal instance.
#[derive(Clone, Debug, PartialEq)]
pub enum IconTarget {
    Profile(String),
    NewProfile,
    Terminal(u32),
}

/// The shown picker and the focus handles of its input and icons, kept across pickers.
#[derive(Default)]
pub struct IconSelect {
    pub picker: Option<IconSelectBox>,
    pub search_focus: Option<FocusHandle>,
    pub grid_focus: Option<FocusHandle>,
}

/// The picker: its search, the icons matching it and the focused one.
pub struct IconSelectBox {
    pub target: IconTarget,
    pub search: InputBox,
    pub search_view: InputView,
    icons: Vec<&'static str>,
    rendered: Vec<&'static str>,
    focused: Option<usize>,
    /// The icons container has the keyboard focus, not the search input.
    pub grid_focused: bool,
    scroll: ScrollHandle,
}

/// `layout`'s grid for a box `width` wide: `floor((width - 30) / 36)` icons per row, the space left over spread as a
/// right margin on each icon and the rest as the container's padding.
#[derive(Debug, PartialEq)]
struct Grid {
    per_row: usize,
    margin: f32,
    padding_left: f32,
}

fn grid(width: f32) -> Grid {
    let icons_width = width - 30.;
    let per_row = ((icons_width / ICON_BOX).floor() as usize).max(1);
    let extra = icons_width % ICON_BOX;
    let margin = (extra / per_row as f32).floor();
    Grid { per_row, margin, padding_left: ((extra % per_row as f32) / 2.).floor() }
}

impl IconSelectBox {
    /// `clearInput` then `focus`: every icon, the first one focused, the input focused.
    pub fn new(target: IconTarget) -> Self {
        let icons = match target {
            IconTarget::Terminal(_) => PICKER_ICONS.iter().map(String::as_str).collect(),
            IconTarget::Profile(_) | IconTarget::NewProfile => ICONS.to_vec(),
        };
        IconSelectBox { target, search: InputBox::new(String::new()), search_view: InputView::default(), rendered: icons.clone(), icons, focused: Some(0), grid_focused: false, scroll: ScrollHandle::new() }
    }

    /// `onDidChange` of the input: the icons whose id contains the value (`matchesContiguous`); the focused icon
    /// stays focused when it still shows, else the first one is.
    pub fn filter(&mut self) {
        let previous = self.focused.and_then(|index| self.rendered.get(index).copied());
        let query = self.search.value.to_lowercase();
        self.rendered = self.icons.iter().copied().filter(|icon| icon.contains(&query)).collect();
        let index = previous.and_then(|icon| self.rendered.iter().position(|rendered| *rendered == icon)).unwrap_or(0);
        self.focus_icon(index as isize);
    }

    /// `focusIcon`: clamped to the rendered icons, none when there are none, scrolled into view (`reveal`).
    fn focus_icon(&mut self, index: isize) {
        self.focused = match self.rendered.len() {
            0 => None,
            len => Some(index.clamp(0, len as isize - 1) as usize),
        };
        if let Some(index) = self.focused {
            self.scroll.scroll_to_item(index);
        }
    }

    fn focused_index(&self) -> isize {
        self.focused.map_or(-1, |index| index as isize)
    }

    pub fn focus_next(&mut self) {
        self.focus_icon(self.focused_index() + 1);
    }

    pub fn focus_previous(&mut self) {
        self.focus_icon(self.focused_index() - 1);
    }

    /// `focusNextRow`: from the input to the icons, else one row of `per_row` icons down.
    pub fn focus_next_row(&mut self, per_row: usize) {
        if !self.rendered.is_empty() && !self.grid_focused {
            self.grid_focused = true;
            return;
        }
        self.focus_icon(self.focused_index() + per_row as isize);
    }

    /// `focusPreviousRow`: from the first row to the input, else one row up.
    pub fn focus_previous_row(&mut self, per_row: usize) {
        if self.focused_index() < per_row as isize {
            self.grid_focused = false;
            return;
        }
        self.focus_icon(self.focused_index() - per_row as isize);
    }

    pub fn focus_first(&mut self) {
        self.focus_icon(0);
    }

    pub fn focus_last(&mut self) {
        self.focus_icon(self.rendered.len() as isize - 1);
    }

    /// The `showIconInfo` label: "Icon name: <id>" with the search's match in the id, empty without a focused icon.
    fn icon_info(&self) -> (String, Vec<std::ops::Range<usize>>) {
        let Some(icon) = self.focused.and_then(|index| self.rendered.get(index)) else { return (String::new(), Vec::new()) };
        let label = format!("Icon name: {icon}");
        let offset = label.len() - icon.len();
        let query = self.search.value.to_lowercase();
        let highlights = match icon.find(&query) {
            Some(start) if !query.is_empty() => vec![offset + start..offset + start + query.len()],
            _ => Vec::new(),
        };
        (label, highlights)
    }

    /// What a key does in `onKeyDown`; `None` leaves the key to the input and the keybindings.
    fn key_action(&self, keystroke: &Keystroke) -> Option<KeyAction> {
        let key = keystroke.key.as_str();
        let modifiers = keystroke.modifiers;
        // ProfileIconRenderer's own listener on the box, and the quick widget's Escape, close the picker.
        if key == "escape" && !modifiers.modified() {
            return Some(KeyAction::Close);
        }
        let input_focused = !self.grid_focused;
        if input_focused && matches!(key, "left" | "right" | "home" | "end") {
            return None;
        }
        if modifiers.alt || modifiers.control || modifiers.platform || modifiers.shift {
            return None;
        }
        if input_focused && !matches!(key, "down" | "up" | "enter") {
            return None;
        }
        Some(match key {
            "down" => KeyAction::NextRow,
            "up" => KeyAction::PreviousRow,
            "right" => KeyAction::Next,
            "left" => KeyAction::Previous,
            "home" => KeyAction::First,
            "end" => KeyAction::Last,
            "enter" | "space" => KeyAction::Select,
            _ => return None,
        })
    }
}

#[derive(Debug, PartialEq)]
enum KeyAction {
    Close,
    NextRow,
    PreviousRow,
    Next,
    Previous,
    First,
    Last,
    Select,
}

impl Workbench {
    /// iconSelectBox.ts's `iconSelectBox.*` commands, run on the shown picker.
    pub(super) fn register_icon_select_box_commands(&mut self) {
        let commands: [(&str, fn(&mut IconSelectBox, usize)); 6] = [
            ("iconSelectBox.focusUp", IconSelectBox::focus_previous_row),
            ("iconSelectBox.focusDown", IconSelectBox::focus_next_row),
            ("iconSelectBox.focusNext", |picker, _| picker.focus_next()),
            ("iconSelectBox.focusPrevious", |picker, _| picker.focus_previous()),
            ("iconSelectBox.focusFirst", |picker, _| picker.focus_first()),
            ("iconSelectBox.focusLast", |picker, _| picker.focus_last()),
        ];
        for (id, focus) in commands {
            self.commands.register(id, move |workbench, _, window, cx| {
                let per_row = workbench.icon_select_grid(window).per_row;
                if let Some(picker) = workbench.icon_select.picker.as_mut() {
                    focus(picker, per_row);
                    workbench.focus_icon_select_box(window, cx);
                }
                Outcome::done()
            });
        }
        self.commands.register("iconSelectBox.selectFocused", |workbench, _, window, cx| {
            workbench.select_focused_icon(window, cx);
            Outcome::done()
        });
    }

    /// `showIconSelectBox`: the picker of `target`, its input focused.
    pub(super) fn show_icon_select_box(&mut self, target: IconTarget, window: &mut Window, cx: &mut Context<Self>) {
        let icon_select = &mut self.icon_select;
        icon_select.picker = Some(IconSelectBox::new(target));
        let focus = icon_select.search_focus.get_or_insert_with(|| cx.focus_handle()).clone();
        icon_select.grid_focus.get_or_insert_with(|| cx.focus_handle());
        window.focus(&focus, cx);
        self.blink_caret(InputId::IconSelectSearch, window, cx);
        cx.notify();
    }

    /// The picker closes: the Profiles editor takes the focus back, a terminal's quick widget hides.
    pub(super) fn hide_icon_select_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let Some(picker) = self.icon_select.picker.take() else { return };
        match picker.target {
            IconTarget::Terminal(_) => {
                if let Some(id) = self.quick_inputs.find_id(|owner| matches!(owner, crate::main_thread_quick_open::Owner::Terminal(super::terminal_view::TerminalInput::Icon))) {
                    self.dispose_quick_input(id, window, cx);
                }
            }
            IconTarget::Profile(_) | IconTarget::NewProfile => {
                if let Some(focus) = self.user_data_profiles.editor.focus.clone() {
                    window.focus(&focus, cx);
                }
            }
        }
        cx.notify();
    }

    fn focus_icon_select_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let icon_select = &self.icon_select;
        let Some(picker) = &icon_select.picker else { return };
        let focus = if picker.grid_focused { icon_select.grid_focus.clone() } else { icon_select.search_focus.clone() };
        if let Some(focus) = focus {
            window.focus(&focus, cx);
        }
        cx.notify();
    }

    pub(super) fn edit_icon_select_search(&mut self, edit: impl FnOnce(&mut InputBox), cx: &mut Context<Self>) {
        let Some(picker) = self.icon_select.picker.as_mut() else { return };
        edit(&mut picker.search);
        picker.filter();
        cx.notify();
    }

    /// The grid of the shown picker: the hover's fixed width, or the quick widget's.
    fn icon_select_grid(&self, window: &Window) -> Grid {
        match self.icon_select.picker.as_ref().map(|picker| &picker.target) {
            Some(IconTarget::Terminal(_)) => grid(super::quick_input_view::widget_width(f32::from(window.viewport_size().width))),
            _ => grid(WIDTH),
        }
    }

    /// The box's key listener, ahead of the keybindings as its DOM listener runs before the window's.
    pub(super) fn icon_select_box_key(&mut self, keystroke: &Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
        let icon_select = &self.icon_select;
        let Some(picker) = &icon_select.picker else { return false };
        let in_box = [&icon_select.search_focus, &icon_select.grid_focus].into_iter().flatten().any(|focus| focus.is_focused(window));
        if !in_box {
            return false;
        }
        let Some(action) = picker.key_action(keystroke) else { return false };
        let per_row = self.icon_select_grid(window).per_row;
        let picker = self.icon_select.picker.as_mut().expect("checked above");
        match action {
            KeyAction::Close => {
                self.hide_icon_select_box(window, cx);
                return true;
            }
            KeyAction::Select => {
                self.select_focused_icon(window, cx);
                return true;
            }
            KeyAction::NextRow => picker.focus_next_row(per_row),
            KeyAction::PreviousRow => picker.focus_previous_row(per_row),
            KeyAction::Next => picker.focus_next(),
            KeyAction::Previous => picker.focus_previous(),
            KeyAction::First => picker.focus_first(),
            KeyAction::Last => picker.focus_last(),
        }
        self.focus_icon_select_box(window, cx);
        true
    }

    fn select_focused_icon(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let Some(picker) = &self.icon_select.picker else { return };
        let Some(icon) = picker.focused.and_then(|index| picker.rendered.get(index).copied()) else { return };
        self.select_icon(Some(icon), window, cx);
    }

    /// `onDidSelect`, or `onDidReset` with `None`: the picker closes and its target takes the icon.
    pub(super) fn select_icon(&mut self, icon: Option<&'static str>, window: &mut Window, cx: &mut Context<Self>) {
        let Some(picker) = &self.icon_select.picker else { return };
        let target = picker.target.clone();
        self.hide_icon_select_box(window, cx);
        match (target, icon) {
            (IconTarget::Terminal(id), icon) => self.set_terminal_icon(id, icon.map(str::to_owned), cx),
            (target, Some(icon)) => self.set_profile_icon(&target, icon, cx),
            (_, None) => {}
        }
    }

    /// The sticky hover with the picker, below `target` with its pointer, over the modal editor.
    pub(super) fn icon_select_box_widget(&self, target: Bounds<Pixels>, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
        let picker = self.icon_select.picker.as_ref().filter(|picker| !matches!(picker.target, IconTarget::Terminal(_)))?;
        let viewport = window.viewport_size();
        let target = Bounds { origin: point(f32::from(target.origin.x), f32::from(target.origin.y)), size: Size { width: f32::from(target.size.width), height: f32::from(target.size.height) } };
        // The 1px hover border around the 486x292 box.
        let size = Size { width: WIDTH + 2., height: HEIGHT + 2. };
        let layout = layout_hover(Size { width: f32::from(viewport.width), height: f32::from(viewport.height) }, target, size, &HoverOptions::sticky_below(), None);
        let high_contrast = self.theme.kind.is_high_contrast();
        let radius = 3.;
        let panel = div()
            .id("icon-select-box")
            .absolute()
            .left(px(layout.origin.x))
            .top(px(layout.origin.y))
            .w(px(size.width))
            .h(px(size.height))
            .border_1()
            .border_color(self.color("editorHoverWidget.border"))
            .rounded(px(radius))
            .text_color(self.color("editorHoverWidget.foreground"))
            .when(high_contrast, |panel| panel.bg(self.color("editorHoverWidget.background")))
            .when(!high_contrast, |panel| panel.child(self.frosted_glass("editorHoverWidget.background", radius)))
            .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
            // A sticky hover hides on a mouse down outside it.
            .on_mouse_down_out(cx.listener(|workbench, _, window, cx| workbench.hide_icon_select_box(window, cx)))
            .child(div().relative().mx(px(15.)).my(px(10.)).flex().flex_col().child(self.icon_select_search(window, cx)).child(self.icon_grid(picker, grid(WIDTH), HEIGHT - 40., window, cx)));
        let caret = layout.pointer.map(|offset| self.hover_pointer(layout.side, layout.origin, size, offset));
        Some(div().absolute().inset_0().child(panel).children(caret).into_any_element())
    }

    /// `IconPicker`'s `picker.widget`: the box `width` wide with the focused icon's name, then the reset button.
    pub(super) fn icon_picker_quick_widget(&self, width: f32, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
        let picker = self.icon_select.picker.as_ref().filter(|picker| matches!(picker.target, IconTarget::Terminal(_)))?;
        let (info, info_highlights) = picker.icon_info();
        let foreground = self.foreground_or("quickInput.foreground");
        let info_label = self.highlighted_label(&info, &info_highlights, self.color("list.highlightForeground"), 16., foreground).debug_selector(|| "icon-select-id-label".into());
        let reset = div()
            .id("icon-select-reset")
            .cursor_pointer()
            .min_h(px(22.))
            .px(px(6.))
            .flex()
            .items_center()
            .rounded(px(4.))
            .text_color(foreground)
            .hover(|button| button.bg(self.color("list.hoverBackground")))
            .child("Reset to default")
            .on_click(cx.listener(|workbench, _, window, cx| workbench.select_icon(None, window, cx)));
        let container = div()
            .mx(px(15.))
            .my(px(10.))
            .flex()
            .flex_col()
            .child(self.icon_select_search(window, cx))
            .child(self.icon_grid(picker, grid(width), PICKER_HEIGHT - 80., window, cx))
            // `.icon-select-id-label`: 24px tall with 10px padding, at 0.8 opacity, in the workbench's 1.4em line.
            .child(div().h(px(44.)).p(px(10.)).opacity(0.8).line_height(px(18.2)).child(info_label));
        let footer = div().mx(px(6.)).mb(px(6.)).child(div().my(px(6.)).border_t_1().border_color(self.color("pickerGroup.border"))).child(reset);
        Some(div().id("icon-select-box").child(container).child(footer).into_any_element())
    }

    /// The "Search icons" input with its 10px gap to the icons.
    fn icon_select_search(&self, window: &Window, cx: &mut Context<Self>) -> impl IntoElement + use<> {
        let search_focused = self.icon_select.search_focus.as_ref().is_some_and(|focus| focus.is_focused(window));
        let input_border = if search_focused { self.color("focusBorder") } else { self.theme.color("input.border").unwrap_or_default() };
        // A bare `.monaco-inputbox`: 4px padding around a 15px normal line and its 1px border, with 4px corners.
        let search = div()
            .debug_selector(|| "icon-select-search".into())
            .h(px(25.))
            .rounded(px(4.))
            .flex()
            .items_center()
            .px(px(6.))
            .border_1()
            .border_color(input_border)
            .bg(self.color("input.background"))
            .child(self.input_text(InputId::IconSelectSearch, InputLook { password: false, placeholder: Some("Search icons".into()), focused: search_focused }, cx));
        div().pb(px(10.)).child(search)
    }

    fn icon_grid(&self, picker: &IconSelectBox, grid: Grid, height: f32, window: &Window, cx: &mut Context<Self>) -> impl IntoElement + use<> {
        let grid_focus = self.icon_select.grid_focus.clone();
        let grid_focused = grid_focus.as_ref().is_some_and(|focus| focus.is_focused(window));
        let foreground = self.color("editorHoverWidget.foreground");
        let focused_background = self.color("list.inactiveSelectionBackground");
        let focused_foreground = self.theme.color("list.inactiveSelectionForeground").unwrap_or(foreground);
        let hover_background = self.color("toolbar.hoverBackground");
        let mut icons = div().id("icon-select-icons").pl(px(grid.padding_left)).flex().flex_wrap().content_start();
        if let Some(focus) = &grid_focus {
            icons = icons.track_focus(focus);
        }
        if picker.rendered.is_empty() {
            icons = icons.child("No results");
        }
        for (index, &icon) in picker.rendered.iter().enumerate() {
            let focused = picker.focused == Some(index);
            let color = if focused { focused_foreground } else { foreground };
            let cell = self
                .icon(icon, ICON_BOX, GLYPH_SIZE, color)
                .id(("icon-select-icon", index))
                .mr(px(grid.margin))
                .rounded(px(5.))
                .cursor_pointer()
                .when(focused, |cell| cell.bg(focused_background))
                .when(focused && grid_focused, |cell| cell.border_1().border_color(self.color("focusBorder")))
                .when(!focused, |cell| cell.hover(|cell| cell.bg(hover_background)))
                .on_click(cx.listener(move |workbench, _, window, cx| workbench.select_icon(Some(icon), window, cx)));
            icons = icons.child(cell);
        }
        self.scrollable("icon-select-icons", Some(&picker.scroll), icons, cx).h(px(height))
    }

    /// The Icon row of a profile that is not the default one: the icon that opens the picker, and its description.
    pub(super) fn profile_icon_row(&self, icon: Option<&str>, target: IconTarget, bounds: Rc<Cell<Bounds<Pixels>>>, cx: &mut Context<Self>) -> impl IntoElement + use<> {
        let foreground = self.color("foreground");
        let button = self
            .icon(profile_icon_file(icon), 20., 16., foreground)
            .id("profile-icon")
            .mr(px(4.))
            .rounded(px(5.))
            .cursor_pointer()
            .hover(|button| button.bg(self.color("toolbar.hoverBackground")))
            .child(super::output_view::bounds_tracker(bounds))
            .child(self.hover_target("profile-icon-hover", super::hover::HoverContent::Text("Click to change icon".into()), HoverOptions::element()))
            .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
            .on_click(cx.listener(move |workbench, _, window, cx| workbench.show_icon_select_box(target.clone(), window, cx)));
        div().flex().items_center().line_height(px(22.)).child(button).child(div().mt(px(-1.)).opacity(0.9).child("Profile icon to be shown in the activity bar"))
    }
}

/// The codicon file of a profile icon id: `DEFAULT_ICON` and a missing icon draw the settings gear, `zap` shares
/// `symbol-event`'s glyph (codiconsLibrary.ts).
pub fn profile_icon_file(icon: Option<&str>) -> &str {
    match icon {
        None | Some(DEFAULT_ICON) => "settings-gear",
        Some("zap") => "symbol-event",
        Some(icon) => icon,
    }
}

#[cfg(test)]
mod tests;