Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.4 KB
Raw Blame
//! breadcrumbsControl.ts: the focus mode (breadcrumbsWidget.ts `_focus`), a click or Enter selecting an item, which
//! shows its picker (breadcrumbsPicker.ts, breadcrumbs/picker.rs) or with `breadcrumbs.useQuickPick` Quick Open, and
//! Space revealing the focused item.

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

use gpui::{Bounds, Context, FocusHandle, Pixels, Window};
use serde_json::json;

use super::Workbench;
use crate::commands::Outcome;

mod picker;
#[cfg(test)]
mod tests;

pub(super) use picker::Picker;

pub(super) struct Breadcrumbs {
    /// The widget's DOM focus, `breadcrumbsActive`.
    pub focus: FocusHandle,
    /// The group whose breadcrumbs have a focused item, and that item.
    focused: Option<(u32, usize)>,
    /// The picker of the selected item, `_breadcrumbsPickerShowing`.
    pub picker: Option<Picker>,
    /// The painted bounds of each group's items, the picker's anchor.
    pub item_bounds: Rc<RefCell<HashMap<(u32, usize), Bounds<Pixels>>>>,
}

impl Breadcrumbs {
    pub fn new(cx: &mut gpui::App) -> Self {
        Self { focus: cx.focus_handle().tab_stop(true), focused: None, picker: None, item_bounds: Rc::default() }
    }
}

/// What an item reveals: breadcrumbsControl.ts `FileItem` and `OutlineItem`.
enum BreadcrumbElement {
    /// The resource's scheme and path.
    File(String, PathBuf),
    /// The resource's scheme, a folder of its path and whether it is a FileKind.ROOT_FOLDER (`~` or a workspace folder).
    Folder(String, PathBuf, bool),
    /// An outline symbol by id; the `…` item and a notebook's cells have none.
    Symbol(Option<String>),
}

/// `IBreadcrumbsItemEvent.payload`: what selecting an item does.
#[derive(Clone, Copy, PartialEq)]
enum Payload {
    /// `Payload_Pick` or a click at the window x: the item's picker.
    Pick(Option<f32>),
    /// `Payload_Reveal`.
    Reveal,
}

impl Workbench {
    pub(super) fn register_breadcrumbs_commands(&mut self) {
        for (id, select) in [("breadcrumbs.focus", false), ("breadcrumbs.focusAndSelect", true)] {
            self.commands.register(id, move |workbench, _, window, cx| {
                workbench.focus_and_select_breadcrumbs(select, window, cx);
                Outcome::done()
            });
        }
        // Enabled only while the breadcrumbs are off, which it turns on before it focuses and selects.
        self.commands.register("breadcrumbs.toggleToOn", |workbench, _, window, cx| {
            if workbench.setting("breadcrumbs.enabled") == json!(false) {
                workbench.update_user_setting("breadcrumbs.enabled", json!(true));
            }
            workbench.focus_and_select_breadcrumbs(true, window, cx);
            Outcome::done()
        });
        for (id, step) in [("breadcrumbs.focusNext", 1), ("breadcrumbs.focusPrevious", -1), ("breadcrumbs.focusNextWithPicker", 1), ("breadcrumbs.focusPreviousWithPicker", -1)] {
            self.commands.register(id, move |workbench, _, window, cx| {
                workbench.move_breadcrumbs_focus(step, window, cx);
                Outcome::done()
            });
        }
        self.commands.register("breadcrumbs.selectFocused", |workbench, _, window, cx| {
            workbench.select_focused_breadcrumb(Payload::Pick(None), window, cx);
            Outcome::done()
        });
        self.commands.register("breadcrumbs.revealFocused", |workbench, _, window, cx| {
            workbench.select_focused_breadcrumb(Payload::Reveal, window, cx);
            Outcome::done()
        });
        self.commands.register("breadcrumbs.revealFocusedFromTreeAside", |workbench, _, window, cx| {
            workbench.open_breadcrumbs_picker_row(true, window, cx);
            Outcome::done()
        });
        self.commands.register("breadcrumbs.selectEditor", |workbench, _, window, cx| {
            workbench.breadcrumbs.focused = None;
            workbench.hide_breadcrumbs_picker(false, window, cx);
            workbench.focus_group(workbench.editors.id, window, cx);
            Outcome::done()
        });
    }

    /// breadcrumbsControl.ts `update`: every editor with a resource has breadcrumbs but untitled and merge editors.
    pub(super) fn breadcrumbs_possible(&self, editor: &crate::editor::OpenEditor) -> bool {
        !matches!(editor.document().scheme.as_str(), "untitled" | super::terminal_editor::TERMINAL_EDITOR_SCHEME) && self.editors.active_merge().is_none()
    }

    pub(super) fn breadcrumbs_visible(&self, editor: &crate::editor::OpenEditor) -> bool {
        self.breadcrumbs_possible(editor) && !self.drawing_compact_part() && self.setting("breadcrumbs.enabled") != json!(false)
    }

    /// `_updateCkBreadcrumbsActive`: the widget has the focus or its picker shows.
    pub(super) fn breadcrumbs_active(&self, window: &Window) -> bool {
        self.breadcrumbs.focus.is_focused(window) || self.breadcrumbs.picker.is_some()
    }

    /// The focused item of the breadcrumbs of the group being drawn.
    pub(super) fn breadcrumbs_focused(&self) -> Option<usize> {
        self.breadcrumbs.focused.filter(|(group, _)| *group == self.editors.id).map(|(_, index)| index)
    }

    /// The item of the group being drawn whose picker shows, `.selected`.
    pub(super) fn breadcrumbs_selected(&self) -> Option<usize> {
        self.breadcrumbs.picker.as_ref().filter(|picker| picker.group == self.editors.id).map(|picker| picker.item)
    }

    /// `focusAndSelectHandler`: the active group's last item, and with `select` its picker.
    fn focus_and_select_breadcrumbs(&mut self, select: bool, window: &mut Window, cx: &mut Context<Self>) {
        let Some(editor) = self.editors.active() else { return };
        if !self.breadcrumbs_visible(editor) {
            return;
        }
        let last = self.breadcrumb_elements().len() - 1;
        self.focus_breadcrumb(last, window, cx);
        if select {
            self.select_breadcrumb(last, Payload::Pick(None), window, cx);
        }
    }

    /// breadcrumbsWidget.ts `_focus` and `_onFocusEvent`: with a picker showing, the newly focused item shows its own.
    fn focus_breadcrumb(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        self.breadcrumbs.focused = Some((self.editors.id, index));
        window.focus(&self.breadcrumbs.focus, cx);
        if self.breadcrumbs.picker.is_some() {
            self.select_breadcrumb(index, Payload::Pick(None), window, cx);
        }
        cx.notify();
    }

    /// breadcrumbsWidget.ts `focusNext` and `focusPrev`: the focus stops at either end.
    fn move_breadcrumbs_focus(&mut self, step: isize, window: &mut Window, cx: &mut Context<Self>) {
        let Some(focused) = self.breadcrumbs_focused() else { return };
        let Some(next) = focused.checked_add_signed(step).filter(|next| *next < self.breadcrumb_elements().len()) else { return };
        self.focus_breadcrumb(next, window, cx);
    }

    fn select_focused_breadcrumb(&mut self, payload: Payload, window: &mut Window, cx: &mut Context<Self>) {
        let Some(focused) = self.breadcrumbs_focused() else { return };
        self.select_breadcrumb(focused, payload, window, cx);
    }

    /// breadcrumbsWidget.ts `_onClick`: a click focuses and selects the item under the pointer; a click on the item
    /// whose picker shows closes it (`_breadcrumbsPickerIgnoreOnceItem`).
    pub(super) fn breadcrumb_clicked(&mut self, index: usize, x: f32, window: &mut Window, cx: &mut Context<Self>) {
        if self.breadcrumbs_selected() == Some(index) {
            return self.hide_breadcrumbs_picker(false, window, cx);
        }
        self.breadcrumbs.focused = Some((self.editors.id, index));
        window.focus(&self.breadcrumbs.focus, cx);
        self.select_breadcrumb(index, Payload::Pick(Some(x)), window, cx);
    }

    /// `_onSelectEvent`: Reveal opens a file or reveals a symbol, else `breadcrumbs.useQuickPick` opens Quick Open,
    /// else the item's picker shows.
    fn select_breadcrumb(&mut self, index: usize, payload: Payload, window: &mut Window, cx: &mut Context<Self>) {
        let element = self.breadcrumb_elements().swap_remove(index);
        let group = self.editors.id;
        if payload == Payload::Reveal {
            return self.reveal_breadcrumb(index, element, window, cx);
        }
        if self.setting("breadcrumbs.useQuickPick") == json!(true) {
            self.breadcrumbs.focused = None;
            self.hide_breadcrumbs_picker(false, window, cx);
            let prefix = if matches!(element, BreadcrumbElement::Symbol(_)) { "@" } else { "" };
            return self.show_quick_access(prefix, false, false, window, cx);
        }
        let Payload::Pick(click_x) = payload else { unreachable!("Reveal returned above") };
        self.breadcrumbs.picker = None;
        let picker = self.new_breadcrumbs_picker(group, index, element, click_x, window, cx);
        window.focus(&picker.focus, cx);
        self.breadcrumbs.picker = Some(picker);
        cx.notify();
    }

    /// `_revealInEditor`: a file opens in the group, a symbol is revealed at the start of its name, and a folder
    /// focuses and picks the next item.
    fn reveal_breadcrumb(&mut self, index: usize, element: BreadcrumbElement, window: &mut Window, cx: &mut Context<Self>) {
        let group = self.editors.id;
        match element {
            BreadcrumbElement::Folder(..) => {
                self.breadcrumbs.focused = Some((group, index + 1));
                return self.select_breadcrumb(index + 1, Payload::Pick(None), window, cx);
            }
            BreadcrumbElement::File(scheme, path) => {
                self.breadcrumbs.focused = None;
                self.focus_group(group, window, cx);
                self.open_file_in_active_group(&scheme, path, false, window, cx);
            }
            BreadcrumbElement::Symbol(id) => {
                self.breadcrumbs.focused = None;
                self.focus_group(group, window, cx);
                if let Some(id) = id {
                    self.reveal_outline_symbol(&id, false, window, cx);
                }
            }
        }
        cx.notify();
    }

    /// The items of the active group's breadcrumbs, as `breadcrumbs_widget` draws them.
    fn breadcrumb_elements(&self) -> Vec<BreadcrumbElement> {
        let editor = self.active_text_editor_control().or(self.editors.active()).expect("breadcrumbs of an editor");
        let foreground = self.color("breadcrumb.foreground");
        let (notebook_path, notebook_items) = self.notebook_breadcrumbs_of(editor, foreground, super::editor_view::BREADCRUMBS_HEIGHT).unzip();
        let (scheme, path) = self.breadcrumbs_resource(editor, notebook_path);
        let (segments, _, has_root_folder) = self.breadcrumb_file_segments(&scheme, &path);
        let file = segments.len() - 1;
        // Each item above the file is the folder as many levels up, `~` the home and a workspace's name its folder.
        let mut elements: Vec<_> = (0..file).map(|index| BreadcrumbElement::Folder(scheme.clone(), path.ancestors().nth(file - index).expect("an ancestor per item").to_path_buf(), has_root_folder && index == 0)).collect();
        elements.push(BreadcrumbElement::File(scheme, path));
        match notebook_items {
            Some(items) => elements.extend(items.iter().map(|_| BreadcrumbElement::Symbol(None))),
            None => {
                let mut ids = self.breadcrumb_symbol_ids(editor).into_iter();
                elements.extend(self.breadcrumb_symbols(editor).iter().map(|_| BreadcrumbElement::Symbol(ids.next())));
            }
        }
        elements
    }
}