Skip to content

Visual Studio Code, rebuilt in Rust

Rust
41.2 KB
Raw Blame
//! outlinePane.ts with documentSymbolsOutline.ts and documentSymbolsTree.ts: the Explorer's Outline view, the
//! document symbols of the active editor as a tree, in position order; a symbol opens at its name.

use std::collections::HashSet;
use std::time::Duration;

use gpui::{AnyElement, ClickEvent, Context, Div, FocusHandle, KeyDownEvent, Task, Window, div, prelude::*, px};

use super::Workbench;
use super::custom_editors::custom_navigation;
use super::hover::{HoverContent, HoverOptions};
use super::outline_actions::SortOrder;
use super::quick_access::goto_symbol::position_of;
use super::model_events::Cursor;
use crate::editor::Reveal;
use crate::editor::{Selection, VerticalReveal};
use crate::outline_model::{OutlineChildren, OutlineElement, OutlineMarker, OutlineModel, Range};

/// documentSymbolsTree.ts `DocumentSymbolVirtualDelegate.getHeight`.
const ROW_HEIGHT: f32 = 22.;
/// MarkerSeverity.Error.
const ERROR: u32 = 8;
/// SymbolTag.Deprecated.
const DEPRECATED: u64 = 1;
/// `DocumentSymbolFilter.kindToConfigName`, by `SymbolKind`.
const SHOW_KIND: [&str; 26] = [
    "showFiles", "showModules", "showNamespaces", "showPackages", "showClasses", "showMethods", "showProperties", "showFields", "showConstructors",
    "showEnums", "showInterfaces", "showFunctions", "showVariables", "showConstants", "showStrings", "showNumbers", "showBooleans", "showArrays",
    "showObjects", "showKeys", "showNull", "showEnumMembers", "showStructs", "showEvents", "showOperators", "showTypeParameters",
];

pub(super) struct OutlinePane {
    pub(super) focus: FocusHandle,
    /// The active editor's model and version the outline was asked for.
    key: Option<(u32, u32)>,
    pub(super) status: Status,
    /// The rows whose expansion differs from `outline.collapseItems`, per model.
    pub(super) toggled: HashSet<(u32, String)>,
    pub(super) selected: Vec<String>,
    /// The tree's focus trait: the keys and the find move it, Enter and a click select it.
    pub(super) focused: Option<String>,
    pub(super) find: super::outline_find::OutlineFind,
    pub(super) view_state: super::outline_actions::OutlineViewState,
    /// The model and cursor `revealActiveElement` last followed.
    followed: Option<(u32, (usize, usize))>,
    pub(super) scroll: gpui::ScrollHandle,
    _request: Option<Task<()>>,
    _loading: Option<Task<()>>,
}

pub(super) enum Status {
    NoProvider,
    /// `Loading document symbols for '{0}'...`, shown 100ms after the request.
    Loading(String),
    Ready { model_id: u32, name: String, outline: OutlineModel },
}

impl OutlinePane {
    pub(super) fn new(cx: &mut Context<Workbench>) -> Self {
        OutlinePane { focus: cx.focus_handle().tab_stop(true), key: None, status: Status::NoProvider, toggled: HashSet::new(), selected: Vec::new(), focused: None, find: super::outline_find::OutlineFind::new(cx), view_state: Default::default(), followed: None, scroll: gpui::ScrollHandle::new(), _request: None, _loading: None }
    }
}

/// A visible row: its depth, its id, and the group label or the element.
pub(super) struct Row<'a> {
    pub(super) depth: usize,
    pub(super) id: &'a str,
    pub(super) group: Option<&'a str>,
    pub(super) element: Option<&'a OutlineElement>,
    pub(super) has_children: bool,
}

impl Row<'_> {
    /// `DocumentSymbolNavigationLabelProvider`: the group's label or the symbol's name.
    pub(super) fn label(&self) -> &str {
        match (self.group, self.element) {
            (Some(label), _) => label,
            (None, Some(element)) => &element.symbol.name,
            (None, None) => "",
        }
    }
}

const NO_EDITOR_MESSAGE: &str = "The active editor cannot provide outline information.";

impl Workbench {
    /// outlinePane.ts listens to `IOutlineService.onDidChange`: a provider registered after the editor opened
    /// builds the outline again.
    pub(super) fn outline_providers_changed(&mut self, cx: &mut Context<Self>) {
        self.outline_pane.key = None;
        self.refresh_outline_pane(cx);
    }

    /// `_handleEditorControlChanged` and `_createOutline`: a new model or version of the active editor asks the
    /// outline again; the previous tree stays until the answer, the loading message shows after 100ms.
    pub(super) fn refresh_outline_pane(&mut self, cx: &mut Context<Self>) {
        self.reveal_outline_active_element(false, cx);
        // documentSymbolsOutline.ts `canCreateOutline`: a custom editor once its navigation resolved.
        let has_outline = |editor: &&crate::editor::OpenEditor| self.custom_editor_over(editor).is_none_or(|panel| custom_navigation(panel).is_some());
        let key = self.editors.pane_editor().filter(has_outline).map(|editor| (editor.model_id, editor.text_model().version_id));
        if self.outline_pane.key == key {
            return;
        }
        // `_handleEditorChanged`: another editor gets a new tree, without the find widget and its history.
        if self.outline_pane.key.map(|(model_id, _)| model_id) != key.map(|(model_id, _)| model_id) {
            self.outline_pane.find = super::outline_find::OutlineFind::new(cx);
        }
        self.outline_pane.key = key;
        self.outline_pane._loading = None;
        let Some((model_id, _)) = key.filter(|(model_id, _)| self.has_document_symbol_provider(*model_id)) else {
            self.outline_pane.status = Status::NoProvider;
            self.outline_pane._request = None;
            return;
        };
        let name = self.editors.pane_editor().expect("checked above").document().name();
        if !matches!(&self.outline_pane.status, Status::Ready { model_id: shown, .. } if *shown == model_id) {
            let name = name.clone();
            self.outline_pane._loading = Some(cx.spawn(async move |workbench, cx| {
                cx.background_executor().timer(Duration::from_millis(100)).await;
                let _ = workbench.update(cx, |workbench, cx| {
                    workbench.outline_pane.status = Status::Loading(name);
                    cx.notify();
                });
            }));
        }
        let outline = self.outline_model(model_id, cx);
        self.outline_pane._request = Some(cx.spawn(async move |workbench, cx| {
            let Some(outline) = outline.await else { return };
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.outline_pane._loading = None;
                workbench.outline_pane.status = Status::Ready { model_id, name, outline };
                workbench.reveal_outline_active_element(true, cx);
                cx.notify();
            });
        }));
    }

    pub(super) fn outline_view_pane(&self, window: &Window, cx: &mut Context<Self>) -> super::view_panes::ViewPane {
        // outlinePane.ts draws while its body is visible (`onDidChangeBodyVisibility`): a collapsed pane is its header.
        if !self.is_view_visible(super::view_panes::OUTLINE_VIEW) {
            return super::view_panes::ViewPane { id: super::view_panes::OUTLINE_VIEW, title: "Outline".into(), description: None, actions: None, draws_more: true, show_actions: false, body: div().into_any_element() };
        }
        let show_actions = self.outline_pane.focus.is_focused(window) || self.outline_pane.find.focus.is_focused(window);
        super::view_panes::ViewPane { id: super::view_panes::OUTLINE_VIEW, title: "Outline".into(), description: None, actions: Some(self.outline_title_actions(window, cx).into_any_element()), draws_more: true, show_actions, body: self.outline_pane_body(window, cx) }
    }

    /// outlinePane.ts `_showMessage`: the text shown in place of the tree, which it hides.
    pub(super) fn outline_message(&self) -> Option<String> {
        // `EditorResourceAccessor.getOriginalUri` has no uri for a diff input; the breadcrumbs still use the outline.
        if self.editors.active_diff().is_some() {
            return Some(NO_EDITOR_MESSAGE.into());
        }
        match &self.outline_pane.status {
            Status::NoProvider => Some(NO_EDITOR_MESSAGE.into()),
            Status::Loading(name) => Some(format!("Loading document symbols for '{name}'...")),
            Status::Ready { name, outline, .. } if outline.groups.is_empty() => Some(format!("No symbols found in document '{name}'")),
            Status::Ready { .. } => None,
        }
    }

    /// `.outline-pane`: the message, or the tree of the active editor's symbols.
    pub(super) fn outline_pane_body(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {
        if let Some(body) = self.notebook_outline_pane_body(window, cx) {
            return body;
        }
        let message = |text: String| div().pt(px(10.)).px(px(22.)).opacity(0.5).line_height(px(18.2)).child(text).into_any_element();
        if let Some(text) = self.outline_message() {
            return message(text);
        }
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { unreachable!("outline_message covers the other states") };
        let (model_id, outline) = (*model_id, self.outline_with_markers(*model_id, outline));
        let focused = self.outline_pane.focus.is_focused(window);
        let rows = self.outline_rows(model_id, &outline);
        let query = self.outline_query();
        let focused_row = self.outline_pane.focused.as_deref();
        let selected_rows = &self.outline_pane.selected;
        let active: Vec<usize> = (0..rows.len()).filter(|&index| Some(rows[index].id) == focused_row || selected_rows.iter().any(|id| id == rows[index].id)).collect();
        let group = gpui::SharedString::from("outline-tree");
        let guides = self.tree_guides_in_group(group.clone(), rows.iter().map(|row| row.depth).collect(), &active);
        let inset = self.pane_row_inset();
        // listView.ts renders only the rows in view; the window's height bounds the view before its first paint.
        let list_scroll = self.outline_list_scroll(rows.len());
        let first = ((list_scroll.scroll_top.max(0.) / ROW_HEIGHT) as usize).min(rows.len());
        let end = (first + (f32::from(window.viewport_size().height) / ROW_HEIGHT).ceil() as usize + 1).min(rows.len());
        let mut elements = vec![div().h(px(ROW_HEIGHT * first as f32)).flex_none().into_any_element()];
        for (index, row) in rows.iter().enumerate().take(end).skip(first) {
            elements.push(div().relative().flex_none().child(self.outline_row(model_id, row, index, focused, focused_row == Some(row.id), query.as_ref(), cx)).children(guides.row(index, inset)).into_any_element());
        }
        elements.push(div().h(px(ROW_HEIGHT * (rows.len() - end) as f32)).flex_none().into_any_element());
        let list = super::list_scroll::ListId::Outline;
        let sticky = if self.outline_pane.find.is_open() { Vec::new() } else { self.tree_sticky_rows(list, &rows.iter().map(|row| row.depth).collect::<Vec<_>>()) };
        let sticky_elements = sticky.iter().map(|sticky_row| self.outline_row(model_id, &rows[sticky_row.index], sticky_row.index, focused, focused_row == Some(rows[sticky_row.index].id), query.as_ref(), cx)).collect();
        let sticky_container = self.tree_sticky_container(list, &sticky, sticky_elements, cx);
        let tree = div()
            .id("outline-tree")
            .group(group)
            .track_focus(&self.outline_pane.focus)
            .size_full()
            .overflow_y_scroll()
            .track_scroll(&self.outline_pane.scroll)
            // `AbstractFindController.open`: `paddingTop: 30` under the widget.
            .when(self.outline_pane.find.is_open(), |tree| tree.pt(px(30.)))
            .line_height(px(ROW_HEIGHT))
            .children(elements)
            .on_key_down(cx.listener(|workbench, event: &KeyDownEvent, window, cx| {
                if workbench.outline_key_down(event.keystroke.key.as_str(), window, cx) {
                    cx.stop_propagation();
                }
            }));
        div().relative().size_full().child(tree).child(self.list_scroll_layer(list, cx)).children(sticky_container).children(self.outline_find_widget(window, cx)).into_any_element()
    }

    /// `_applyMarkersToOutline`: the errors and warnings of the model counted per element, with `problems.visibility`
    /// and `outline.problems.enabled`.
    fn outline_with_markers(&self, model_id: u32, outline: &OutlineModel) -> OutlineModel {
        let mut outline = outline.clone();
        let editor = self.editors.editor_by_id(model_id);
        let (Some(editor), true, true) = (editor, self.setting("problems.visibility") != false, self.setting("outline.problems.enabled") != false) else { return outline };
        let markers: Vec<OutlineMarker> = editor
            .text_model()
            .markers
            .iter()
            .filter(|decoration| decoration.marker.severity >= 4)
            .map(|decoration| {
                let marker = &decoration.marker;
                OutlineMarker { range: Range::new(marker.start_line, marker.start_column, marker.end_line, marker.end_column), severity: marker.severity as u32 }
            })
            .collect();
        outline.update_markers(&markers);
        outline
    }

    /// The rows the tree shows: the groups of several providers, then each element below its expanded parent,
    /// siblings in the Sort By order (`OutlineTreeSorter`).
    pub(super) fn outline_rows<'a>(&self, model_id: u32, outline: &'a OutlineModel) -> Vec<Row<'a>> {
        // Read each setting once: a lookup per symbol made the rows of a large outline cost a frame.
        let collapsed_by_default = self.setting("outline.collapseItems") == "alwaysCollapse";
        let expanded = |id: &str| collapsed_by_default == self.outline_pane.toggled.contains(&(model_id, id.to_string()));
        let shown_kinds: Vec<bool> = (0..SHOW_KIND.len() as u64).map(|kind| self.shows_symbol_kind("outline", kind)).collect();
        let shown_kind = |element: &OutlineElement| shown_kinds.get(element.symbol.kind as usize).copied().unwrap_or(true);
        let filter = self.outline_query().filter(|query| query.filter_mode);
        let shown = |element: &OutlineElement| shown_kind(element) && filter.as_ref().is_none_or(|query| query.keeps(element, &shown_kind));
        let sort_by = self.outline_pane.view_state.sort_by;
        let mut rows = Vec::new();
        let push_elements = |rows: &mut Vec<Row<'a>>, elements, depth| push_elements(rows, elements, depth, sort_by, &expanded, &shown);
        match outline.children {
            OutlineChildren::Elements => push_elements(&mut rows, &outline.groups[0].children, 0),
            OutlineChildren::Groups => {
                for group in &outline.groups {
                    if filter.as_ref().is_some_and(|query| query.matches(&group.label).is_none() && !group.children.iter().any(|element| shown(element))) {
                        continue;
                    }
                    rows.push(Row { depth: 0, id: &group.id, group: Some(&group.label), element: None, has_children: true });
                    if expanded(&group.id) {
                        push_elements(&mut rows, &group.children, 1);
                    }
                }
            }
        }
        rows
    }

    /// `DocumentSymbolRenderer`: twistie, colored symbol icon, name and detail, and the problem badge.
    fn outline_row(&self, model_id: u32, row: &Row, index: usize, tree_focused: bool, row_focused: bool, query: Option<&super::outline_find::OutlineQuery>, cx: &mut Context<Self>) -> AnyElement {
        let highlights = query.and_then(|query| query.matches(row.label())).unwrap_or_default();
        let id = row.id.to_string();
        let selected = self.outline_pane.selected.iter().any(|id| id == row.id);
        let indent = self.tree_indent();
        let twistie = match row.has_children {
            true => {
                let expanded = self.outline_row_expanded(model_id, &id);
                let chevron = if expanded { "chevron-down" } else { "chevron-right" };
                let toggled = id.clone();
                self.icon(chevron, 16., 16., self.foreground_or("icon.foreground")).id(("outline-twistie", index)).cursor_pointer().on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
                    cx.stop_propagation();
                    workbench.toggle_outline_row(model_id, &toggled, cx);
                }))
            }
            false => div().id(("outline-twistie", index)).size(px(16.)).flex_none(),
        };
        let content = match (row.group, row.element) {
            (Some(label), _) => div().child(self.find_highlighted_text(label.to_string(), &highlights)),
            (None, Some(element)) => self.outline_element_label(element, &highlights, row_focused || selected, (tree_focused && selected).then(|| self.list_selection_icon_color())),
            (None, None) => div(),
        };
        let (selection, selection_foreground) = match tree_focused {
            true => (self.color("list.activeSelectionBackground"), self.theme.color("list.activeSelectionForeground")),
            false => (self.color("list.inactiveSelectionBackground"), self.theme.color("list.inactiveSelectionForeground")),
        };
        // listWidget.ts `style`: the focused tree outlines its focused row, `listFocusAndSelectionOutline` when selected.
        let focus_border = self.theme.color("list.focusOutline").or(self.theme.color("focusBorder"));
        let focus_outline = match selected {
            true => self.theme.color("list.focusAndSelectionOutline").or(self.theme.color("contrastActiveBorder")).or(focus_border),
            false => focus_border,
        }
        .filter(|_| tree_focused && row_focused);
        let focus_background = self.theme.color("list.focusBackground").filter(|_| tree_focused && row_focused && !selected);
        let clicked = id.clone();
        div()
            .id(("outline-row", index))
            .debug_selector(move || format!("outline-row-{index}"))
            .relative()
            .h(px(ROW_HEIGHT))
            .flex_none()
            .flex()
            .items_center()
            .cursor_pointer()
            .mx(px(self.pane_row_inset()))
            .rounded(px(4.))
            // monaco-tl-twistie: 3px row inset and 8px base indent, then the indent per level. Its box is 16px and 6px
            // padding-right, drawn translateX(3px), so the contents start 3px after the drawn chevron.
            .pl(px(11. + indent * row.depth as f32))
            .when(!selected, |row| row.hover(|row| row.bg(self.color("list.hoverBackground"))))
            .when(selected, |row| row.bg(selection).when_some(selection_foreground, |row, color| row.text_color(color)))
            .when_some(focus_background, |row, color| row.bg(color))
            .when_some(focus_outline, |row, color| row.child(div().absolute().inset_0().rounded(px(4.)).border_1().border_color(color)))
            .child(twistie)
            .child(content.debug_selector(move || format!("outline-row-contents-{index}")).ml(px(3.)).flex_1().min_w_0().flex().items_center())
            .on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| workbench.outline_row_clicked(&clicked, event.click_count() > 1, window, cx)))
            .into_any_element()
    }

    /// `icon_color` overrides the symbol color on a selected row of the focused tree; iconlabel.css shows the detail
    /// at full opacity on a focused or selected row.
    pub(super) fn outline_element_label(&self, element: &OutlineElement, highlights: &[std::ops::Range<usize>], focused_or_selected: bool, icon_color: Option<gpui::Rgba>) -> Div {
        let symbol = &element.symbol;
        let codicon = crate::symbol_icons::codicon(symbol.kind);
        let icon_color = icon_color.or_else(|| crate::symbol_icons::color_key(codicon).and_then(|key| self.theme.color(key))).unwrap_or(self.color("foreground"));
        let problems = element.marker.filter(|_| self.setting("problems.visibility") != false);
        let problem_color = problems.map(|(_, severity)| self.color(if severity == ERROR { "list.errorForeground" } else { "list.warningForeground" }));
        let label_color = problem_color.filter(|_| self.setting("outline.problems.colors") != false);
        let badge = problems.filter(|_| self.setting("outline.problems.badges") != false).map(|(count, _)| {
            let decoration = div().ml_auto().pl(px(5.)).flex_none().text_color(problem_color.expect("with problems"));
            match count {
                0 => decoration.pr(px(8.)).opacity(0.4).child(self.icon("circle-filled", 14., 14., problem_color.expect("with problems"))),
                _ => decoration.pr(px(12.)).opacity(0.75).text_size(px(11.7)).font_weight(gpui::FontWeight::SEMIBOLD).child(if count < 10 { count.to_string() } else { "+9".into() }),
            }
        });
        let deprecated = symbol.tags.contains(&DEPRECATED);
        let label = symbol.name.replace('\n', "⏎");
        let name = div().flex_none().when_some(label_color, |name, color| name.text_color(color)).when(deprecated, |name| name.line_through().opacity(0.66)).child(self.find_highlighted_text(label, highlights));
        let detail = (!symbol.detail.is_empty()).then(|| super::icon_label::label_description().debug_selector(|| "outline-detail".into()).opacity(if focused_or_selected { 1. } else { 0.7 }).min_w_0().overflow_hidden().text_ellipsis().child(symbol.detail.clone()));
        // iconLabel.ts `setupHover` on `.monaco-icon-label`, the name and detail without the symbol icon.
        let hover = self.hover_target(gpui::SharedString::from(format!("outline-hover-{}", element.id)), HoverContent::Text(outline_element_title(element)), HoverOptions::mouse());
        let icon_label = div().relative().flex().items_center().min_w_0().overflow_hidden().child(name).children(detail).child(hover);
        div()
            .overflow_hidden()
            .whitespace_nowrap()
            .when(self.setting("outline.icons") != false, |label| label.child(self.icon(codicon, 16., 16., icon_color).mr(px(6.)).flex_none()))
            .child(icon_label)
            .children(badge)
    }

    /// `DocumentSymbolFilter`: `<prefix>.show<Kind>` of the symbol's kind, shown when unset.
    pub(super) fn shows_symbol_kind(&self, prefix: &str, kind: u64) -> bool {
        let Some(name) = SHOW_KIND.get(kind as usize) else { return true };
        self.setting(&format!("{prefix}.{name}")) != false
    }

    /// `DocumentSymbolBreadcrumbsSource._computeBreadcrumbs` with `breadcrumbs.symbolPath`: the symbols around the
    /// cursor from the outermost, up to the first filtered one, as (kind, name); none around the cursor in a
    /// non-empty outline is `…` without a kind (breadcrumbsModel.ts `_getOutlineElements`).
    pub(super) fn breadcrumb_symbols(&self, editor: &crate::editor::OpenEditor) -> Vec<(Option<u64>, String)> {
        let Some((path, outline_is_empty)) = self.breadcrumb_outline_path(editor) else { return Vec::new() };
        if path.is_empty() && !outline_is_empty {
            return vec![(None, "\u{2026}".into())];
        }
        path.into_iter().map(|element| (Some(element.symbol.kind), element.symbol.name.clone())).collect()
    }

    /// The outline ids of `breadcrumb_symbols`' symbols; the `…` item has none.
    pub(super) fn breadcrumb_symbol_ids(&self, editor: &crate::editor::OpenEditor) -> Vec<String> {
        self.breadcrumb_outline_path(editor).map(|(path, _)| path.into_iter().map(|element| element.id.clone()).collect()).unwrap_or_default()
    }

    /// The breadcrumbs' outline elements and whether the outline is empty; none without an outline of `editor`.
    fn breadcrumb_outline_path(&self, editor: &crate::editor::OpenEditor) -> Option<(Vec<&crate::outline_model::OutlineElement>, bool)> {
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return None };
        let symbol_path = self.setting("breadcrumbs.symbolPath");
        // A custom editor diff has no code editor to outline.
        let custom_diff = self.editors.active_diff().is_some_and(|diff| diff.custom.is_some());
        if *model_id != editor.model_id || symbol_path == "off" || custom_diff {
            return None;
        }
        let position = self.outline_position(editor)?;
        let path = outline.item_enclosing_position(position, None).map(|item| outline.path_to(&item.id).expect("an element of the outline")).unwrap_or_default();
        let mut elements: Vec<_> = path.into_iter().take_while(|element| self.shows_symbol_kind("breadcrumbs", element.symbol.kind)).collect();
        if symbol_path == "last" {
            elements.drain(..elements.len().saturating_sub(1));
        }
        Some((elements, outline.groups.is_empty()))
    }

    /// listWidget.ts `.monaco-list:focus .monaco-list-row.selected .codicon`: `list.activeSelectionIconForeground`,
    /// unset in the default themes, so the row's foreground.
    pub(super) fn list_selection_icon_color(&self) -> gpui::Rgba {
        self.theme.color("list.activeSelectionIconForeground").or(self.theme.color("list.activeSelectionForeground")).unwrap_or(self.color("foreground"))
    }

    pub(super) fn outline_row_expanded(&self, model_id: u32, id: &str) -> bool {
        let collapsed_by_default = self.setting("outline.collapseItems") == "alwaysCollapse";
        collapsed_by_default == self.outline_pane.toggled.contains(&(model_id, id.to_string()))
    }

    /// Expands or collapses `id`, whatever it shows now.
    pub(super) fn set_outline_row_expanded(&mut self, model_id: u32, id: &str, expanded: bool) {
        let collapsed_by_default = self.setting("outline.collapseItems") == "alwaysCollapse";
        let key = (model_id, id.to_string());
        match expanded == collapsed_by_default {
            true => self.outline_pane.toggled.insert(key),
            false => self.outline_pane.toggled.remove(&key),
        };
    }

    /// outlinePane.ts `revealActiveElement`: with Follow Cursor, the element around the cursor of the shown model
    /// is revealed (its parents expanded) and selected, once per cursor move unless `force`.
    pub(super) fn reveal_outline_active_element(&mut self, force: bool, cx: &mut Context<Self>) {
        let Some(editor) = self.editors.pane_editor() else { return };
        let Some(position) = self.outline_position(editor) else { return };
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return };
        let followed = Some((*model_id, position));
        if !self.outline_pane.view_state.follow_cursor || *model_id != editor.model_id || (!force && self.outline_pane.followed == followed) {
            return;
        }
        self.outline_pane.followed = followed;
        let Some(item) = outline.item_enclosing_position(position, None) else { return };
        let path: Vec<String> = outline.path_to(&item.id).expect("an element of the outline").iter().map(|element| element.id.clone()).collect();
        let model_id = *model_id;
        let group = matches!(outline.children, OutlineChildren::Groups).then(|| outline.groups.iter().find(|group| item.id.starts_with(&format!("{}/", group.id))).map(|group| group.id.clone())).flatten();
        for id in group.iter().chain(&path[..path.len() - 1]) {
            self.set_outline_row_expanded(model_id, id, true);
        }
        let active = path.last().expect("an element of the outline");
        self.reveal_outline_row(active, true);
        self.outline_pane.focused = Some(active.clone());
        self.outline_pane.selected = vec![active.clone()];
        cx.notify();
    }

    /// The position the outline and breadcrumbs follow: the cursor, or the navigation selection's position of the
    /// custom editor over the tab (customTextEditorDocumentSymbolAdapter `getPosition`).
    fn outline_position(&self, editor: &crate::editor::OpenEditor) -> Option<(usize, usize)> {
        let Some(panel) = self.custom_editor_over(editor) else {
            let head = editor.selection().head;
            return Some((head.line + 1, crate::editor::utf16_column(&editor.document().lines[head.line], head.column) + 1));
        };
        let selection = custom_navigation(panel)?;
        Some((selection["positionLineNumber"].as_u64()? as usize, selection["positionColumn"].as_u64()? as usize))
    }

    /// listCommands.ts `list.showHover`: the focused symbol's title hover, placed by its label as the row draws it.
    pub(super) fn show_outline_focus_hover(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return };
        let rows = self.outline_rows(*model_id, outline);
        let Some(index) = self.outline_pane.focused.as_deref().and_then(|focused| rows.iter().position(|row| row.id == focused)) else { return };
        let Some(element) = rows[index].element else { return };
        let content = HoverContent::Text(outline_element_title(element));
        let list = self.outline_pane.scroll.bounds();
        let padding = if self.outline_pane.find.is_open() { 30. } else { 0. };
        let icon = if self.setting("outline.icons") != false { 22. } else { 0. };
        let inset = self.pane_row_inset();
        let left = inset + 11. + self.tree_indent() * rows[index].depth as f32 + 16. + 3. + icon;
        let top = list.top() + px(padding + ROW_HEIGHT * index as f32) + self.outline_pane.scroll.offset().y;
        let bounds = gpui::Bounds::new(gpui::point(list.left() + px(left), top), gpui::size(list.size.width - px(left + inset), px(ROW_HEIGHT)));
        let id = gpui::SharedString::from(format!("outline-hover-{}", element.id));
        self.show_managed_hover(id, content, HoverOptions::mouse(), bounds, window, cx);
    }

    /// The ids and depths of the symbol rows shown; none for a notebook's outline or a message.
    pub(super) fn outline_shown_rows(&self) -> Vec<(String, usize)> {
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return Vec::new() };
        if self.active_notebook_editor().is_some() || self.outline_message().is_some() {
            return Vec::new();
        }
        self.outline_rows(*model_id, outline).iter().map(|row| (row.id.to_string(), row.depth)).collect()
    }

    pub(super) fn reveal_outline_row(&self, id: &str, center: bool) {
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return };
        let rows = self.outline_rows(*model_id, outline);
        if let Some(index) = rows.iter().position(|row| row.id == id) {
            self.reveal_outline_index(index, rows.len(), center);
        }
    }

    fn toggle_outline_row(&mut self, model_id: u32, id: &str, cx: &mut Context<Self>) {
        let key = (model_id, id.to_string());
        if !self.outline_pane.toggled.remove(&key) {
            self.outline_pane.toggled.insert(key);
        }
        cx.notify();
    }

    /// `onDidOpen`: a click selects the row and opens the symbol at the start of its name keeping the focus in the
    /// tree; a double click selects the symbol's whole range in the focused editor.
    fn outline_row_clicked(&mut self, id: &str, double_click: bool, window: &mut Window, cx: &mut Context<Self>) {
        self.outline_pane.focused = Some(id.to_string());
        self.outline_pane.selected = vec![id.to_string()];
        window.focus(&self.outline_pane.focus, cx);
        self.reveal_outline_symbol(id, double_click, window, cx);
        cx.notify();
    }

    /// documentSymbolEditor.ts `reveal`: the selection near the top when outside the viewport.
    pub(super) fn reveal_outline_symbol(&mut self, id: &str, select: bool, window: &mut Window, cx: &mut Context<Self>) {
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return };
        let Some(element) = outline.path_to(id).and_then(|path| path.last().copied()) else { return };
        let range = element.symbol.range;
        let (start, end) = match select {
            true => (range.start, range.end),
            false => (element.symbol.selection_range.start, element.symbol.selection_range.start),
        };
        let model_id = *model_id;
        let custom_editor = self.editors.active().filter(|editor| editor.model_id == model_id).and_then(|editor| self.custom_editor_over(editor)).map(|panel| panel.handle.clone());
        if let Some(handle) = custom_editor {
            // customTextEditorDocumentSymbolAdapter `reveal`; the panel takes the focus once the host revealed.
            let Some(revealed) = self.reveal_custom_text_editor_range(&handle, range, Some(Range { start, end }), !select) else { return };
            if select {
                cx.spawn_in(window, async move |workbench, cx| {
                    if let Ok(Ok(_)) = revealed.await {
                        let _ = workbench.update_in(cx, |workbench, window, cx| workbench.focus_webview_panel(&handle, window, cx));
                    }
                })
                .detach();
            }
            return;
        }
        let viewport = self.editors.viewport;
        let Some(editor) = self.editors.active_mut().filter(|editor| editor.model_id == model_id) else { return };
        let (start, end) = (position_of(editor, start), position_of(editor, end));
        editor.set_selections(vec![Selection { anchor: start, head: end }]);
        editor.reveal_range(start, end, VerticalReveal::NearTopIfOutsideViewport, viewport);
        self.cursor_position_changed(Cursor { moved: true, source: "code.navigation", reveal: Reveal::Nothing }, cx);
        self.editor_scrolled(cx);
        if select {
            window.focus(&self.editor_focus, cx);
        }
    }

    /// The tree's keys: Up and Down move the selection, Left collapses or goes to the parent, Right expands or goes
    /// to the first child, Enter and Space open the selected symbol.
    pub(super) fn outline_key_down(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
        if self.active_notebook_editor().is_some() {
            return false;
        }
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return false };
        let model_id = *model_id;
        let rows = self.outline_rows(model_id, outline);
        let current = self.outline_pane.focused.as_deref().and_then(|focused| rows.iter().position(|row| row.id == focused));
        let target = match (key, current) {
            ("down", None) | ("home", _) => Some(0),
            ("up", None) | ("end", _) => Some(rows.len().saturating_sub(1)),
            ("down", Some(index)) => Some((index + 1).min(rows.len() - 1)),
            ("up", Some(index)) => Some(index.saturating_sub(1)),
            ("pagedown" | "pageup", _) if !rows.is_empty() => {
                let Some((target, scroll_top)) = crate::list_tree::page_focus(self.outline_list_scroll(rows.len()), key == "pagedown", current) else { return true };
                self.set_outline_scroll_top(scroll_top);
                Some(target)
            }
            ("left" | "right", Some(index)) => {
                let row = &rows[index];
                let expanded = self.outline_row_expanded(model_id, row.id);
                match (key, row.has_children && expanded, row.has_children) {
                    ("left", true, _) | ("right", false, true) => {
                        let id = row.id.to_string();
                        self.toggle_outline_row(model_id, &id, cx);
                        return true;
                    }
                    ("left", false, _) => rows[..index].iter().rposition(|parent| parent.depth + 1 == row.depth),
                    _ => rows.get(index + 1).filter(|child| child.depth > row.depth).map(|_| index + 1),
                }
            }
            // listCommands.ts `list.toggleExpand`: Space toggles a row with children, else selects as Enter does.
            ("space", Some(index)) if rows[index].has_children => {
                let id = rows[index].id.to_string();
                self.toggle_outline_row(model_id, &id, cx);
                return true;
            }
            ("enter" | "space", Some(index)) => {
                let id = rows[index].id.to_string();
                self.outline_pane.selected = vec![id.clone()];
                self.reveal_outline_symbol(&id, false, window, cx);
                if key == "enter" {
                    window.focus(&self.editor_focus, cx);
                }
                cx.notify();
                return true;
            }
            _ => return false,
        };
        if let Some(target) = target.filter(|_| !rows.is_empty()) {
            let count = rows.len();
            self.outline_pane.focused = Some(rows[target].id.to_string());
            self.reveal_outline_index(target, count, false);
            cx.notify();
        }
        true
    }

    /// listCommands.ts `list.focusParent`: the focus moves to the focused row's parent and into view.
    pub(super) fn focus_outline_parent(&mut self, cx: &mut Context<Self>) {
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return };
        let rows = self.outline_rows(*model_id, outline);
        let Some(index) = self.outline_pane.focused.as_deref().and_then(|focused| rows.iter().position(|row| row.id == focused)) else { return };
        let Some(parent) = rows[..index].iter().rposition(|parent| parent.depth + 1 == rows[index].depth) else { return };
        let count = rows.len();
        self.outline_pane.focused = Some(rows[parent].id.to_string());
        self.reveal_outline_index(parent, count, false);
        cx.notify();
    }

    /// listCommands.ts `list.collapseAllToFocus`: the focused row and every row below it collapse, and it is selected.
    pub(super) fn collapse_outline_focus_deep(&mut self, cx: &mut Context<Self>) {
        let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return };
        let Some(focused) = self.outline_pane.focused.clone() else { return };
        let model_id = *model_id;
        let group = outline.groups.iter().find(|group| group.id == focused);
        let mut ids: Vec<String> = group.iter().map(|group| group.id.clone()).collect();
        let mut stack: Vec<&OutlineElement> = match group {
            Some(group) => group.children.iter().collect(),
            None => outline.path_to(&focused).and_then(|path| path.last().copied()).into_iter().collect(),
        };
        while let Some(element) = stack.pop() {
            if !element.children.is_empty() {
                ids.push(element.id.clone());
            }
            stack.extend(&element.children);
        }
        for id in ids {
            self.set_outline_row_expanded(model_id, &id, false);
        }
        self.outline_pane.selected = vec![focused];
        cx.notify();
    }

    /// The tree's rows below the find widget's `paddingTop: 30`, as `ListScroll` sees them from the first row.
    pub(super) fn outline_list_scroll(&self, count: usize) -> crate::list_tree::ListScroll {
        let padding_top = if self.outline_pane.find.is_open() { 30. } else { 0. };
        let scroll = &self.outline_pane.scroll;
        crate::list_tree::ListScroll { count, row_height: ROW_HEIGHT, viewport: f32::from(scroll.bounds().size.height), scroll_top: -f32::from(scroll.offset().y) - padding_top }
    }

    /// Writes the scroll top of `outline_list_scroll`; at the first row the padding above it shows too.
    fn set_outline_scroll_top(&self, scroll_top: f32) {
        let padding_top = if self.outline_pane.find.is_open() && scroll_top > 0. { 30. } else { 0. };
        self.outline_pane.scroll.set_offset(gpui::point(px(0.), px(-(scroll_top + padding_top))));
    }

    /// abstractTree.ts `reveal`: scrolls the row into view, centered (`relativeTop` 0.5) when `center`.
    pub(super) fn reveal_outline_index(&self, index: usize, count: usize, center: bool) {
        let list = self.outline_list_scroll(count);
        // A collapsed or not yet painted Outline view has no viewport; any scroll top would be wrong there.
        if list.viewport <= 0. {
            return;
        }
        if let Some(scroll_top) = crate::list_tree::reveal_scroll_top(list, index, center) {
            self.set_outline_scroll_top(scroll_top);
        }
    }
}

/// documentSymbolsTree.ts `title.template`: "{name} ({kind})", `undefined` for a kind without a name.
fn outline_element_title(element: &OutlineElement) -> String {
    format!("{} ({})", element.symbol.name, crate::symbol_icons::kind_name(element.symbol.kind).unwrap_or("undefined"))
}

pub(super) fn push_elements<'a>(rows: &mut Vec<Row<'a>>, elements: &'a [OutlineElement], depth: usize, sort_by: SortOrder, expanded: &impl Fn(&str) -> bool, shown: &impl Fn(&OutlineElement) -> bool) {
    let mut sorted: Vec<&OutlineElement> = elements.iter().filter(|element| shown(element)).collect();
    sorted.sort_by(|a, b| compare_elements(a, b, sort_by));
    for element in sorted {
        // `hideTwistiesOfChildlessElements`.
        let has_children = !element.children.is_empty();
        rows.push(Row { depth, id: &element.id, group: None, element: Some(element), has_children });
        if has_children && expanded(&element.id) {
            push_elements(rows, &element.children, depth + 1, sort_by, expanded, shown);
        }
    }
}

/// `DocumentSymbolComparator`: names with `Intl.Collator(undefined, { numeric: true })`.
fn compare_elements(a: &OutlineElement, b: &OutlineElement, sort_by: SortOrder) -> std::cmp::Ordering {
    let by_position = || a.symbol.range.start.cmp(&b.symbol.range.start);
    let by_name = || crate::explorer::compare_file_names(&a.symbol.name, &b.symbol.name);
    match sort_by {
        SortOrder::ByPosition => by_position().then_with(by_name),
        SortOrder::ByName => by_name().then_with(by_position),
        SortOrder::ByKind => a.symbol.kind.cmp(&b.symbol.kind).then_with(by_name),
    }
}

#[cfg(test)]
mod tests;