Visual Studio Code, rebuilt in Rust
Rust
//! The Outline tree's find widget: abstractTree.ts `FindController` with `FindFilter` over the symbol names
//! (documentSymbolsTree.ts `DocumentSymbolNavigationLabelProvider`), in the mode Filter on Type picks.
use std::collections::HashSet;
use std::ops::Range;
use gpui::{Context, Div, FocusHandle, Keystroke, Window};
use serde_json::{Value, json};
use super::Workbench;
use super::explorer_find::{TreeFindLook, label_matches};
use super::find_widget::HISTORY_LIMIT;
use super::input_box_view::{InputId, InputView};
use super::outline_pane::Status;
use crate::history::HistoryNavigator;
use crate::input_box::InputBox;
use crate::outline_model::{OutlineChildren, OutlineElement};
pub(super) struct OutlineFind {
pub focus: FocusHandle,
pub view: InputView,
pub input: InputBox,
history: HistoryNavigator,
open: bool,
previous_pattern: String,
/// The Fuzzy Match toggle; unset follows `workbench.list.defaultFindMatchType`.
fuzzy: Option<bool>,
/// outlinePane.ts "expand all nodes when filtering": the expansion, focus and selection before the filter expanded all.
saved: Option<(HashSet<(u32, String)>, Option<String>, Vec<String>)>,
}
/// The find pattern the rows are matched against, while the widget is open with one.
pub(super) struct OutlineQuery {
pub pattern: String,
pub fuzzy: bool,
pub filter_mode: bool,
}
impl OutlineFind {
pub fn new(cx: &mut gpui::App) -> Self {
OutlineFind {
focus: cx.focus_handle(),
view: InputView::default(),
input: InputBox::default(),
history: HistoryNavigator::new(Vec::new(), HISTORY_LIMIT),
open: false,
previous_pattern: String::new(),
fuzzy: None,
saved: None,
}
}
pub fn is_open(&self) -> bool {
self.open
}
}
impl OutlineQuery {
/// `FindFilter.filter`'s label score: the chars to highlight, or `None` when the label does not match.
pub fn matches(&self, label: &str) -> Option<Vec<Range<usize>>> {
label_matches(&self.pattern, label, self.fuzzy)
}
/// `TreeVisibility.Recurse` in filter mode: a row shows when its label or one of its shown descendants matches.
pub fn keeps(&self, element: &OutlineElement, shown: &impl Fn(&OutlineElement) -> bool) -> bool {
self.matches(&element.symbol.name).is_some() || element.children.iter().any(|child| shown(child) && self.keeps(child, shown))
}
}
impl Workbench {
pub(super) fn outline_find_fuzzy(&self) -> bool {
self.outline_pane.find.fuzzy.unwrap_or_else(|| self.setting("workbench.list.defaultFindMatchType") != json!("contiguous"))
}
pub(super) fn outline_query(&self) -> Option<OutlineQuery> {
let find = &self.outline_pane.find;
if !find.open || find.input.value.is_empty() {
return None;
}
Some(OutlineQuery { pattern: find.input.value.clone(), fuzzy: self.outline_find_fuzzy(), filter_mode: self.outline_pane.view_state.filter_on_type })
}
/// `AbstractFindController.open`: the widget shows with the last pattern selected, or an open one takes the focus.
pub(super) fn open_outline_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !matches!(self.outline_pane.status, Status::Ready { .. }) || self.active_notebook_editor().is_some() {
return;
}
let find = &mut self.outline_pane.find;
window.focus(&find.focus.clone(), cx);
if !find.open {
find.open = true;
find.input.set_value(find.previous_pattern.clone());
self.apply_outline_find_pattern(cx);
}
let find = &mut self.outline_pane.find;
find.input.select_all();
find.history.add_to_history(&find.input.value, true);
self.blink_caret(InputId::OutlineFind, window, cx);
cx.notify();
}
/// `AbstractFindController.close`: the pattern is kept for the next open, and the tree takes the focus.
pub(super) fn close_outline_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let find = &mut self.outline_pane.find;
if !find.open {
return;
}
find.open = false;
find.previous_pattern = std::mem::take(&mut find.input.value);
find.input = InputBox::default();
find.view.reset();
self.apply_outline_find_pattern(cx);
self.focus_outline_tree(window, cx);
}
/// `FindController.mode` from the widget's Filter toggle: outlinePane.ts keeps Filter on Type in sync.
pub(super) fn toggle_outline_find_mode(&mut self, cx: &mut Context<Self>) {
self.outline_pane.view_state.filter_on_type = !self.outline_pane.view_state.filter_on_type;
self.outline_view_state_changed(cx);
}
pub(super) fn toggle_outline_find_match_type(&mut self, cx: &mut Context<Self>) {
self.outline_pane.find.fuzzy = Some(!self.outline_find_fuzzy());
cx.notify();
}
pub(super) fn edit_outline_find_input(&mut self, edit: impl FnOnce(&mut InputBox), cx: &mut Context<Self>) {
let input = &mut self.outline_pane.find.input;
let before = input.value.clone();
edit(input);
cx.notify();
if input.value != before {
self.apply_outline_find_pattern(cx);
}
}
/// `FindWidget`'s keydown: Enter returns to the tree, Up and Down walk the history, Down past its end returns
/// to the tree.
pub(super) fn outline_find_input_key(&mut self, keystroke: &Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
let modifiers = keystroke.modifiers;
if modifiers.platform || modifiers.alt || modifiers.shift || modifiers.control {
return false;
}
let find = &mut self.outline_pane.find;
match keystroke.key.as_str() {
"enter" | "down" if keystroke.key == "enter" || find.history.is_last() || find.history.is_nowhere() => {
find.history.add_to_history(&find.input.value, false);
self.focus_outline_tree(window, cx);
}
"down" => {
let value = find.history.show_next_value(&find.input.value);
self.edit_outline_find_input(|input| input.set_value(value), cx);
}
"up" => {
if let Some(value) = find.history.show_previous_value(&find.input.value) {
self.edit_outline_find_input(|input| input.set_value(value), cx);
}
}
_ => return false,
}
cx.notify();
true
}
fn focus_outline_tree(&mut self, window: &mut Window, cx: &mut Context<Self>) {
window.focus(&self.outline_pane.focus.clone(), cx);
}
/// `FindController.applyPattern` with outlinePane.ts `onDidChangeFindPattern`: a filter expands every row until
/// the pattern empties, which restores the expansion, and the focus moves to the first matching row.
fn apply_outline_find_pattern(&mut self, cx: &mut Context<Self>) {
let query = self.outline_query();
let filter_mode = self.outline_pane.view_state.filter_on_type;
let saved = self.outline_pane.find.saved.is_some();
if filter_mode && query.is_some() && !saved {
let pane = &self.outline_pane;
self.outline_pane.find.saved = Some((pane.toggled.clone(), pane.focused.clone(), pane.selected.clone()));
self.set_outline_all_expanded(true, cx);
} else if query.is_none() && saved {
let (toggled, focused, selected) = self.outline_pane.find.saved.take().expect("checked above");
self.outline_pane.toggled = toggled;
self.outline_pane.focused = focused;
self.outline_pane.selected = selected;
}
let Some(query) = query else { return cx.notify() };
let Status::Ready { model_id, outline, .. } = &self.outline_pane.status else { return };
let rows = self.outline_rows(*model_id, outline);
// `focusNext(0, true)`: from the focused row, the first one whose label matches.
let start = self.outline_pane.focused.as_deref().and_then(|focused| rows.iter().position(|row| row.id == focused)).unwrap_or(0);
let first_match = (0..rows.len()).map(|offset| (start + offset) % rows.len()).find(|&index| query.matches(rows[index].label()).is_some());
let count = rows.len();
// abstractTree.ts `FindController.applyPattern`: without a match the focus stays where it is.
if let Some(index) = first_match {
self.outline_pane.focused = Some(rows[index].id.to_string());
self.reveal_outline_index(index, count, true);
}
cx.notify();
}
/// `FindController.render`: "No results found." when no row of the tree matches.
pub(super) fn outline_find_message(&self) -> Option<String> {
let query = self.outline_query()?;
let Status::Ready { outline, .. } = &self.outline_pane.status else { return None };
let shown = |element: &OutlineElement| self.shows_symbol_kind("outline", element.symbol.kind);
let any_match = |elements: &[OutlineElement]| elements.iter().any(|element| shown(element) && query.keeps(element, &shown));
let found = match outline.children {
OutlineChildren::Elements => any_match(&outline.groups[0].children),
OutlineChildren::Groups => outline.groups.iter().any(|group| query.matches(&group.label).is_some() || any_match(&group.children)),
};
(!found).then(|| "No results found.".to_string())
}
pub(super) fn outline_find_widget(&self, window: &Window, cx: &mut Context<Self>) -> Option<Div> {
if !self.outline_pane.find.open {
return None;
}
let look = TreeFindLook { input: InputId::OutlineFind, message: self.outline_find_message(), filter_mode: self.outline_pane.view_state.filter_on_type, fuzzy: self.outline_find_fuzzy(), input_width: super::explorer_find::INPUT_WIDTH };
Some(self.tree_find_widget(look, |workbench, window, cx| workbench.close_outline_find(window, cx), window, cx))
}
/// The list keys of the focused Outline tree (listService.ts `WorkbenchListFocusContextKey`, `listSupportsFind`,
/// `treeFindOpen`); the find widget is inside the tree's element.
pub(super) fn outline_context(&self, window: &Window, context: &mut std::collections::HashMap<String, Value>) {
let find = &self.outline_pane.find;
let find_focused = find.focus.is_focused(window);
if !find_focused && !self.outline_pane.focus.is_focused(window) {
return;
}
context.insert("listFocus".into(), json!(true));
context.insert("listSupportsFind".into(), json!(true));
context.insert("treeFindOpen".into(), json!(find.open));
if find_focused {
context.insert("inputFocus".into(), json!(true));
}
// listService.ts `WorkbenchListHasSelectionOrFocus` and the `WorkbenchTreeElement*` keys of the focused row.
let pane = &self.outline_pane;
context.insert("listHasSelectionOrFocus".into(), json!(pane.focused.is_some() || !pane.selected.is_empty()));
let Status::Ready { model_id, outline, .. } = &pane.status else { return };
if self.active_notebook_editor().is_some() {
return;
}
let rows = self.outline_rows(*model_id, outline);
let Some(index) = pane.focused.as_deref().and_then(|focused| rows.iter().position(|row| row.id == focused)) else { return };
let row = &rows[index];
let expanded = self.outline_row_expanded(*model_id, row.id);
context.insert("treeElementCanCollapse".into(), json!(row.has_children && expanded));
context.insert("treeElementCanExpand".into(), json!(row.has_children && !expanded));
context.insert("treeElementHasChild".into(), json!(rows.get(index + 1).is_some_and(|child| child.depth > row.depth)));
context.insert("treeElementHasParent".into(), json!(row.depth > 0));
}
/// The list commands of the focused Outline tree, run as the keys the tree takes.
pub(super) fn outline_list_command(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
if !self.outline_pane.focus.is_focused(window) {
return false;
}
let key = match id {
"list.focusDown" | "list.focusAnyDown" => "down",
"list.focusUp" | "list.focusAnyUp" => "up",
"list.focusFirst" | "list.focusAnyFirst" => "home",
"list.focusLast" | "list.focusAnyLast" => "end",
"list.expand" => "right",
"list.collapse" => "left",
"list.select" => "enter",
"list.toggleExpand" => "space",
"list.focusPageDown" => "pagedown",
"list.focusPageUp" => "pageup",
"list.collapseAll" => {
self.set_outline_all_expanded(false, cx);
return true;
}
"list.focusParent" => {
self.focus_outline_parent(cx);
return true;
}
"list.collapseAllToFocus" => {
self.collapse_outline_focus_deep(cx);
return true;
}
// `selectElement(accessor, true)`: Space's select on a leaf, the focus kept in the tree.
"list.selectAndPreserveFocus" => {
let Some(focused) = self.outline_pane.focused.clone() else { return true };
self.outline_pane.selected = vec![focused.clone()];
self.reveal_outline_symbol(&focused, false, window, cx);
cx.notify();
return true;
}
"list.showHover" => {
self.show_outline_focus_hover(window, cx);
return true;
}
"list.clear" => {
self.outline_pane.selected.clear();
self.outline_pane.focused = None;
cx.notify();
return true;
}
"list.toggleSelection" => {
let Some(focused) = self.outline_pane.focused.clone() else { return true };
let selected = &mut self.outline_pane.selected;
match selected.iter().position(|id| *id == focused) {
Some(index) => drop(selected.remove(index)),
None => selected.push(focused),
}
cx.notify();
return true;
}
// The multi-select commands need `listSupportsMultiselect`, which the Outline tree never sets.
_ => return true,
};
self.outline_key_down(key, window, cx);
true
}
}