Visual Studio Code, rebuilt in Rust
Rust
//! breadcrumbsPicker.ts: the tree below a selected item. A path item lists the files of its folder (the workspace's
//! folders for a root folder item) with its own file focused; a symbol item lists the outline with its symbol
//! revealed and focused. Opening a file or a symbol closes the picker; losing the focus closes it unpicked.
use std::collections::HashSet;
use std::path::PathBuf;
use gpui::{AnyElement, Bounds, ClickEvent, Context, FocusHandle, MouseButton, PathBuilder, Pixels, ScrollHandle, Subscription, Window, anchored, canvas, deferred, div, point, prelude::*, px};
use serde_json::json;
use super::{BreadcrumbElement, Workbench};
use crate::outline_model::{OutlineChildren, OutlineElement};
use crate::workbench::outline_actions::SortOrder;
use crate::workbench::outline_pane::{self, Status};
/// breadcrumbsPicker.ts `FileVirtualDelegate.getHeight`, the outline's rows too.
const ROW_HEIGHT: f32 = 22.;
/// breadcrumbsControl.ts `pickerArrowSize`.
const ARROW_SIZE: f32 = 8.;
pub(in crate::workbench) struct Picker {
pub group: u32,
pub item: usize,
pub focus: FocusHandle,
/// The window x of the click that showed the picker; the keyboard points the arrow 30% into the item.
click_x: Option<f32>,
source: Source,
/// The keys of the expanded folders or symbols.
expanded: HashSet<String>,
/// The key of the focused row.
pub(super) focused: Option<String>,
scroll: ScrollHandle,
_focus_out: Subscription,
}
enum Source {
/// `BreadcrumbsFilePicker`: the children of the folder, or the workspace's folders when `None`.
Files(Option<PathBuf>),
/// The folder of a resource of another scheme, which the port lists nothing of: debugMemory.ts `stat` makes every
/// `vscode-debug-memory` folder a file, without children.
Unlisted,
/// `BreadcrumbsOutlinePicker`: the outline of the model, whose resource opens to the side.
Outline { model_id: u32, scheme: String, path: PathBuf },
}
pub(super) struct Row<'a> {
pub(super) key: String,
depth: usize,
/// `None` for a row without children (`hideTwistiesOfChildlessElements`), else whether it is expanded.
expanded: Option<bool>,
target: Target<'a>,
}
enum Target<'a> {
/// A folder and whether it is a workspace folder (FileKind.ROOT_FOLDER).
Folder(PathBuf, bool),
File(PathBuf),
Group(&'a str),
Symbol(&'a OutlineElement),
}
impl Workbench {
/// `_onSelectEvent`'s `showContextView` and `_setInput`: the picker of `element`, its own row revealed and focused.
pub(super) fn new_breadcrumbs_picker(&mut self, group: u32, item: usize, element: BreadcrumbElement, click_x: Option<f32>, window: &mut Window, cx: &mut Context<Self>) -> Picker {
let (source, expanded, focused) = match element {
BreadcrumbElement::Folder(_, path, true) => {
let key = path.to_string_lossy().into_owned();
(Source::Files(None), HashSet::new(), Some(key))
}
BreadcrumbElement::Folder(scheme, path, false) | BreadcrumbElement::File(scheme, path) => {
let key = path.to_string_lossy().into_owned();
let source = if crate::editor::on_disk(&scheme) { Source::Files(path.parent().map(PathBuf::from)) } else { Source::Unlisted };
(source, HashSet::new(), Some(key))
}
BreadcrumbElement::Symbol(id) => {
let editor = self.active_text_editor_control().or(self.editors.active()).expect("breadcrumbs of an editor");
let (model_id, scheme, path) = (editor.model_id, editor.document().scheme.clone(), editor.document().path.clone());
// `tree.reveal(input.element)` expands the element's parents.
let expanded = match (&self.outline_pane.status, &id) {
(Status::Ready { outline, .. }, Some(id)) => outline.path_to(id).into_iter().flatten().map(|element| element.id.clone()).collect(),
_ => HashSet::new(),
};
(Source::Outline { model_id, scheme, path }, expanded, id)
}
};
let focus = cx.focus_handle();
let focus_out = cx.on_focus_out(&focus, window, |workbench, _, window, cx| workbench.hide_breadcrumbs_picker(false, window, cx));
let picker = Picker { group, item, focus, click_x, source, expanded, focused, scroll: ScrollHandle::new(), _focus_out: focus_out };
let index = self.breadcrumbs_picker_rows(&picker).iter().position(|row| Some(&row.key) == picker.focused.as_ref());
if let Some(index) = index {
picker.scroll.scroll_to_item(index);
}
picker
}
/// `hideContextView`: the item loses its focus and selection unless the focus moved on to another item.
pub(super) fn hide_breadcrumbs_picker(&mut self, keep_focus: bool, _window: &mut Window, cx: &mut Context<Self>) {
if self.breadcrumbs.picker.take().is_none() {
return;
}
if !keep_focus {
self.breadcrumbs.focused = None;
}
cx.notify();
}
pub(super) fn breadcrumbs_picker_rows<'a>(&'a self, picker: &Picker) -> Vec<Row<'a>> {
match &picker.source {
Source::Files(folder) => {
let mut rows = Vec::new();
match folder {
Some(folder) => self.push_picker_files(&mut rows, folder.clone(), 0, &picker.expanded),
None => {
for folder in self.workspace().map(|workspace| workspace.folders.as_slice()).unwrap_or_default() {
let key = folder.path.to_string_lossy().into_owned();
let expanded = picker.expanded.contains(&key);
rows.push(Row { key, depth: 0, expanded: Some(expanded), target: Target::Folder(folder.path.clone(), true) });
if expanded {
self.push_picker_files(&mut rows, folder.path.clone(), 1, &picker.expanded);
}
}
}
}
rows
}
Source::Unlisted => Vec::new(),
Source::Outline { model_id, .. } => {
let Status::Ready { model_id: shown, outline, .. } = &self.outline_pane.status else { return Vec::new() };
if shown != model_id {
return Vec::new();
}
let sort_by = match self.setting("breadcrumbs.symbolSortOrder").as_str() {
Some("name") => SortOrder::ByName,
Some("type") => SortOrder::ByKind,
_ => SortOrder::ByPosition,
};
let expanded = |id: &str| picker.expanded.contains(id);
let shown = |element: &OutlineElement| self.shows_symbol_kind("breadcrumbs", element.symbol.kind);
let mut rows = Vec::new();
match outline.children {
OutlineChildren::Elements => outline_pane::push_elements(&mut rows, &outline.groups[0].children, 0, sort_by, &expanded, &shown),
OutlineChildren::Groups => {
for group in &outline.groups {
rows.push(outline_pane::Row { depth: 0, id: &group.id, group: Some(&group.label), element: None, has_children: true });
if expanded(&group.id) {
outline_pane::push_elements(&mut rows, &group.children, 1, sort_by, &expanded, &shown);
}
}
}
}
rows.into_iter()
.map(|row| {
let target = match (row.group, row.element) {
(Some(label), _) => Target::Group(label),
(None, element) => Target::Symbol(element.expect("a row is a group or an element")),
};
Row { key: row.id.to_string(), depth: row.depth, expanded: row.has_children.then(|| expanded(row.id)), target }
})
.collect()
}
}
}
/// `FileDataSource.getChildren` in `FileSorter` order: folders first, then by name; `FileFilter` hides the
/// `files.exclude` default names.
fn push_picker_files<'a>(&self, rows: &mut Vec<Row<'a>>, folder: PathBuf, depth: usize, expanded: &HashSet<String>) {
let Ok(entries) = std::fs::read_dir(&folder) else { return };
let mut children: Vec<(String, PathBuf, bool)> = entries
.flatten()
.map(|entry| (entry.file_name().to_string_lossy().into_owned(), entry.path(), entry.path().is_dir()))
.filter(|(name, _, _)| !crate::explorer::EXCLUDED_NAMES.contains(&name.as_str()))
.collect();
children.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| crate::explorer::compare_file_names(&a.0, &b.0)));
for (_, path, is_dir) in children {
let key = path.to_string_lossy().into_owned();
if !is_dir {
rows.push(Row { key, depth, expanded: None, target: Target::File(path) });
continue;
}
let is_expanded = expanded.contains(&key);
rows.push(Row { key, depth, expanded: Some(is_expanded), target: Target::Folder(path.clone(), false) });
if is_expanded {
self.push_picker_files(rows, path, depth + 1, expanded);
}
}
}
/// listWidget.ts and abstractTree.ts `KeyboardController`: the tree takes its unmodified keys before the
/// keybindings, so Left and Right expand and collapse here where `breadcrumbs.focusPrevious` and `focusNext` would run.
pub(in crate::workbench) fn breadcrumbs_picker_key(&mut self, keystroke: &gpui::Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
let command = match keystroke.key.as_str() {
_ if keystroke.modifiers.modified() => return false,
"up" => "list.focusUp",
"down" => "list.focusDown",
"home" => "list.focusFirst",
"end" => "list.focusLast",
"left" => "list.collapse",
"right" => "list.expand",
"space" => "list.toggleExpand",
"enter" => "list.select",
_ => return false,
};
self.breadcrumbs_picker_list_command(command, window, cx)
}
/// The list commands while the picker has the focus: listWidget.ts's focus moves and abstractTree.ts's expand and
/// collapse; `list.select` opens the focused file or symbol.
pub(in crate::workbench) fn breadcrumbs_picker_list_command(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
let Some(picker) = self.breadcrumbs.picker.as_ref().filter(|picker| picker.focus.is_focused(window)) else { return false };
let rows: Vec<(String, usize, Option<bool>)> = self.breadcrumbs_picker_rows(picker).into_iter().map(|row| (row.key, row.depth, row.expanded)).collect();
if rows.is_empty() {
return true;
}
let focus = picker.focused.as_ref().and_then(|focused| rows.iter().position(|row| row.0 == *focused));
let last = rows.len() - 1;
let target = match id {
"list.focusDown" | "list.focusAnyDown" => focus.map_or(0, |index| (index + 1).min(last)),
"list.focusUp" | "list.focusAnyUp" => focus.map_or(0, |index| index.saturating_sub(1)),
"list.focusFirst" | "list.focusAnyFirst" => 0,
"list.focusLast" | "list.focusAnyLast" => last,
"list.select" => {
let Some(index) = focus else { return true };
self.open_breadcrumbs_picker_index(index, false, false, window, cx);
return true;
}
"list.expand" | "list.collapse" | "list.toggleExpand" => {
let Some(index) = focus else { return true };
let (key, depth, expanded) = rows[index].clone();
let child = rows.get(index + 1).filter(|child| child.1 > depth).map(|child| child.0.clone());
let parent = rows[..index].iter().rposition(|parent| parent.1 < depth).map(|parent| rows[parent].0.clone());
let picker = self.breadcrumbs.picker.as_mut().expect("checked above");
match (id, expanded) {
("list.toggleExpand", Some(expanded)) | ("list.expand", Some(expanded @ false)) | ("list.collapse", Some(expanded @ true)) => {
if expanded {
picker.expanded.remove(&key);
} else {
picker.expanded.insert(key);
}
}
("list.expand", Some(true)) => picker.focused = child.or(picker.focused.take()),
("list.collapse", _) => picker.focused = parent.or(picker.focused.take()),
_ => {}
}
cx.notify();
return true;
}
_ => return false,
};
let picker = self.breadcrumbs.picker.as_mut().expect("checked above");
picker.focused = Some(rows[target].0.clone());
picker.scroll.scroll_to_item(target);
cx.notify();
true
}
/// `breadcrumbs.revealFocusedFromTreeAside` and a modified click: the focused row opens, pinned, to the side.
pub(super) fn open_breadcrumbs_picker_row(&mut self, side_by_side: bool, window: &mut Window, cx: &mut Context<Self>) {
let Some(picker) = self.breadcrumbs.picker.as_ref().filter(|picker| picker.focus.is_focused(window)) else { return };
let Some(index) = self.breadcrumbs_picker_rows(picker).iter().position(|row| Some(&row.key) == picker.focused.as_ref()) else { return };
self.open_breadcrumbs_picker_index(index, side_by_side, side_by_side, window, cx);
}
/// `_revealElement`: a file or a symbol opens and closes the picker as picked; a folder does nothing.
fn open_breadcrumbs_picker_index(&mut self, index: usize, side_by_side: bool, pinned: bool, window: &mut Window, cx: &mut Context<Self>) {
let picker = self.breadcrumbs.picker.as_ref().expect("an open picker");
let group = picker.group;
let outline_resource = match &picker.source {
Source::Outline { scheme, path, .. } => Some(crate::editor::uri_value(scheme, path)),
Source::Files(_) | Source::Unlisted => None,
};
let opened = match &self.breadcrumbs_picker_rows(picker)[index].target {
Target::File(path) => Some((crate::editor::uri_value("file", path), None)),
Target::Symbol(element) => Some((outline_resource.expect("a symbol of the outline picker"), Some((element.id.clone(), element.symbol.selection_range.start)))),
Target::Folder(..) | Target::Group(_) => None,
};
let Some((resource, symbol)) = opened else { return };
self.hide_breadcrumbs_picker(false, window, cx);
self.focus_group(group, window, cx);
if side_by_side {
// documentSymbolsOutline.ts `reveal`: the selection range collapsed to its start, near the top if outside.
let mut options = json!({ "pinned": pinned, "preserveFocus": false, "position": crate::workbench::webview_panels::SIDE_GROUP });
if let Some((_, (line, column))) = symbol {
options["selection"] = json!({ "startLineNumber": line, "startColumn": column, "endLineNumber": line, "endColumn": column });
options["selectionRevealType"] = json!(3);
}
drop(self.try_show_text_document(&resource, &options, window, cx));
return;
}
match symbol {
Some((id, _)) => self.reveal_outline_symbol(&id, false, window, cx),
None => {
let Ok(("file", path)) = crate::workbench::host_requests::uri_parts(&resource) else { return };
self.open_file_in_active_group("file", path, pinned, window, cx);
}
}
}
fn breadcrumbs_picker_row_clicked(&mut self, index: usize, event: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
let Some(picker) = self.breadcrumbs.picker.as_mut() else { return };
window.focus(&picker.focus, cx);
let rows = self.breadcrumbs_picker_rows(self.breadcrumbs.picker.as_ref().expect("checked above"));
let Some(row) = rows.get(index) else { return };
let (key, expanded, is_symbol) = (row.key.clone(), row.expanded, matches!(row.target, Target::Symbol(_) | Target::Group(_)));
let picker = self.breadcrumbs.picker.as_mut().expect("checked above");
picker.focused = Some(key.clone());
cx.notify();
// The file tree expands a folder on a click on its row, the outline only on its twistie (`expandOnlyOnTwistieClick`).
if let (Some(expanded), false) = (expanded, is_symbol) {
if expanded {
picker.expanded.remove(&key);
} else {
picker.expanded.insert(key);
}
return;
}
// listService.ts `onPointer`: a middle click pins, Cmd, Ctrl or Alt opens to the side.
let modifiers = event.modifiers();
let side_by_side = modifiers.platform || modifiers.control || modifiers.alt;
let pinned = matches!(event, ClickEvent::Mouse(mouse) if mouse.down.button == MouseButton::Middle);
self.open_breadcrumbs_picker_index(index, side_by_side, pinned, window, cx);
}
fn toggle_breadcrumbs_picker_row(&mut self, key: &str, cx: &mut Context<Self>) {
let Some(picker) = self.breadcrumbs.picker.as_mut() else { return };
if !picker.expanded.remove(key) {
picker.expanded.insert(key.to_string());
}
cx.notify();
}
/// The picker below its item: breadcrumbsControl.ts `getAnchor` and breadcrumbsPicker.ts `show` and `_layout`.
pub(in crate::workbench) fn breadcrumbs_picker_widget(&self, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
let picker = self.breadcrumbs.picker.as_ref()?;
let item: Bounds<Pixels> = self.breadcrumbs.item_bounds.borrow().get(&(picker.group, picker.item)).copied()?;
let viewport = window.viewport_size();
let max_inner_width = f32::from(viewport.width) - 8.;
let width = max_inner_width.min((max_inner_width / 4.17).max(240.));
let y = f32::from(item.bottom()) + ARROW_SIZE;
// contextview.ts `layout`: a point anchor is 2px high, so the view starts 2px below `y`.
let top = y + 2.;
let mut max_height = (f32::from(viewport.height) * 0.7).min(300.);
if y + max_height >= f32::from(viewport.height) {
// Room for the shadow and the status bar.
max_height = f32::from(viewport.height) - y - 30.;
}
let mut x = f32::from(item.left());
if x + width >= max_inner_width {
x = max_inner_width - width;
}
let arrow_offset = match picker.click_x {
Some(click_x) => {
let max_arrow_offset = width - 2. * ARROW_SIZE;
let mut offset = click_x - x;
if offset > max_arrow_offset {
x = (max_inner_width - width).min(x + offset - max_arrow_offset);
offset = max_arrow_offset;
}
offset
}
None => f32::from(item.left()) + f32::from(item.size.width) * 0.3 - x,
}
.max(0.);
let rows = self.breadcrumbs_picker_rows(picker);
let tree_height = (max_height - 2. * ARROW_SIZE).min(rows.len() as f32 * ROW_HEIGHT);
let background = self.color("breadcrumbPicker.background");
let tree_focused = picker.focus.is_focused(window);
let indent = self.tree_indent();
let align_icons = self.file_icons.as_ref().is_some_and(|icons| !icons.has_folder_icons());
let foreground = self.color("foreground");
let icon_foreground = self.foreground_or("icon.foreground");
let focus_outline = self.theme.color("list.focusOutline").or(self.theme.color("focusBorder")).filter(|_| tree_focused);
let focus_background = self.theme.color("list.focusBackground").filter(|_| tree_focused);
let row_elements: Vec<AnyElement> = rows
.iter()
.enumerate()
.map(|(index, row)| {
let focused = picker.focused.as_ref() == Some(&row.key);
let toggled = row.key.clone();
let twistie = match row.expanded {
Some(expanded) => self
.icon(if expanded { "chevron-down" } else { "chevron-right" }, 16., 16., icon_foreground)
.id(("breadcrumbs-picker-twistie", index))
.on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
cx.stop_propagation();
workbench.toggle_breadcrumbs_picker_row(&toggled, cx);
})),
None => div().id(("breadcrumbs-picker-twistie", index)).size(px(16.)),
};
// views.css `align-icons-and-twisties`, which only the file picker's tree gets: a file's twistie collapses
// to its padding when the icon theme has file icons and no folder icons.
let collapsed_twistie = matches!(row.target, Target::File(_)) && align_icons;
let content = match &row.target {
Target::Folder(path, is_root) => {
let folder = crate::file_icons::FolderIcon { path, is_root: *is_root, expanded: row.expanded == Some(true) };
let icon = self.file_icons.as_ref().and_then(|icons| icons.folder_icon(folder, self.theme.kind, 13., ROW_HEIGHT, foreground));
div().flex().items_center().children(icon.map(|icon| icon.mr(px(6.)))).child(file_name(path))
}
Target::File(path) => {
let icon = self.file_icons.as_ref().and_then(|icons| icons.file_icon(path, self.languages.language_of(path, ""), self.theme.kind, 13., ROW_HEIGHT, foreground));
div().flex().items_center().children(icon.map(|icon| icon.mr(px(6.)))).child(file_name(path))
}
Target::Group(label) => div().child(label.to_string()),
// The picker's symbol icons are uncolored: symbolIcons.css colors only `.codicon-colored` ones.
Target::Symbol(element) => self.outline_element_label(element, &[], focused, Some(foreground)).flex().items_center(),
};
div()
.id(("breadcrumbs-picker-row", index))
.debug_selector(move || format!("breadcrumbs-picker-row-{index}"))
.relative()
.h(px(ROW_HEIGHT))
.flex_none()
.flex()
.items_center()
.cursor_pointer()
// roundedCorners.css: modern UI rounds list rows by `cornerRadius-small`.
.rounded(px(4.))
// abstractTree.ts `renderElement`: the twistie's padding-left, `DefaultIndent` (8) and the indent per level.
.pl(px(8. + indent * row.depth as f32))
.hover(|row| row.bg(self.color("list.hoverBackground")))
.when_some(focus_background.filter(|_| focused), |row, color| row.bg(color))
.when_some(focus_outline.filter(|_| focused), |row, color| row.child(div().absolute().inset_0().rounded(px(4.)).border_1().border_color(color)))
// tree.css: the twistie is shifted 3px right (`translateX(3px)`) inside its 6px padding-right.
.when(!collapsed_twistie, |row| row.child(twistie.flex_none().ml(px(3.)).mr(px(3.))))
.child(content.debug_selector(move || format!("breadcrumbs-picker-row-contents-{index}")).flex_1().min_w_0().overflow_hidden().whitespace_nowrap())
.on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| workbench.breadcrumbs_picker_row_clicked(index, event, window, cx)))
.into_any_element()
})
.collect();
let arrow = canvas(
|_, _, _| (),
move |bounds, _, window, _| {
// The arrow is a CSS border triangle: the 8px bottom border of a 16px box, pointing up at the item.
let (left, bottom) = (bounds.origin.x, bounds.origin.y + px(ARROW_SIZE));
let mut path = PathBuilder::fill();
path.move_to(point(left, bottom));
path.line_to(point(left + px(2. * ARROW_SIZE), bottom));
path.line_to(point(left + px(ARROW_SIZE), bounds.origin.y));
path.close();
if let Ok(path) = path.build() {
window.paint_path(path, background);
}
},
)
.ml(px(arrow_offset))
.w(px(2. * ARROW_SIZE))
.h(px(ARROW_SIZE));
let tree = div()
.id("breadcrumbs-picker-tree")
.debug_selector(|| "breadcrumbs-picker-tree".into())
.track_focus(&picker.focus)
// breadcrumbsPicker.ts `_layout` sets the content-box width; the 1px border is outside it.
.w(px(width + 2.))
.pt(px(2.))
.bg(background)
.rounded(px(3.))
.border_1()
.border_color(self.color("widget.border"))
// --vscode-shadow-lg, its 12px blur as a sigma of 6.
.shadow(vec![gpui::BoxShadow { color: gpui::rgba(0x00000024).into(), offset: point(px(0.), px(0.)), blur_radius: px(6.), spread_radius: px(0.), inset: false }])
.text_color(foreground)
.child(self.scrollable("breadcrumbs-picker-rows", Some(&picker.scroll), div().id("breadcrumbs-picker-rows").children(row_elements), cx).h(px(tree_height)));
let widget = div().occlude().flex().flex_col().child(arrow).child(tree);
Some(deferred(anchored().position(point(px(x), px(top - ARROW_SIZE))).child(widget)).with_priority(1).into_any_element())
}
}
fn file_name(path: &std::path::Path) -> String {
path.file_name().map_or_else(|| path.to_string_lossy().into_owned(), |name| name.to_string_lossy().into_owned())
}