outline_panel.rs

   1mod outline_panel_settings;
   2
   3use anyhow::Context as _;
   4use collections::{BTreeSet, HashMap, HashSet, hash_map};
   5use db::kvp::KEY_VALUE_STORE;
   6use editor::{
   7    AnchorRangeExt, Bias, DisplayPoint, Editor, EditorEvent, ExcerptId, ExcerptRange,
   8    MultiBufferSnapshot, RangeToAnchorExt, SelectionEffects,
   9    display_map::ToDisplayPoint,
  10    items::{entry_git_aware_label_color, entry_label_color},
  11    scroll::{Autoscroll, ScrollAnchor},
  12};
  13use file_icons::FileIcons;
  14
  15use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
  16use gpui::{
  17    Action, AnyElement, App, AppContext as _, AsyncWindowContext, Bounds, ClipboardItem, Context,
  18    DismissEvent, Div, ElementId, Entity, EventEmitter, FocusHandle, Focusable, HighlightStyle,
  19    InteractiveElement, IntoElement, KeyContext, ListHorizontalSizingBehavior, ListSizingBehavior,
  20    MouseButton, MouseDownEvent, ParentElement, Pixels, Point, Render, ScrollStrategy,
  21    SharedString, Stateful, StatefulInteractiveElement as _, Styled, Subscription, Task,
  22    UniformListScrollHandle, WeakEntity, Window, actions, anchored, deferred, div, point, px, size,
  23    uniform_list,
  24};
  25use itertools::Itertools;
  26use language::language_settings::language_settings;
  27use language::{Anchor, BufferId, BufferSnapshot, OffsetRangeExt, OutlineItem};
  28use menu::{Cancel, SelectFirst, SelectLast, SelectNext, SelectPrevious};
  29use std::{
  30    cmp,
  31    collections::BTreeMap,
  32    hash::Hash,
  33    ops::Range,
  34    path::{Path, PathBuf},
  35    sync::{
  36        Arc, OnceLock,
  37        atomic::{self, AtomicBool},
  38    },
  39    time::Duration,
  40    u32,
  41};
  42
  43use outline_panel_settings::{DockSide, OutlinePanelSettings, ShowIndentGuides};
  44use project::{File, Fs, GitEntry, GitTraversal, Project, ProjectItem};
  45use search::{BufferSearchBar, ProjectSearchView};
  46use serde::{Deserialize, Serialize};
  47use settings::{Settings, SettingsStore};
  48use smol::channel;
  49use theme::{SyntaxTheme, ThemeSettings};
  50use ui::{
  51    ContextMenu, FluentBuilder, HighlightedLabel, IconButton, IconButtonShape, IndentGuideColors,
  52    IndentGuideLayout, ListItem, ScrollAxes, Scrollbars, Tab, Tooltip, WithScrollbar, prelude::*,
  53};
  54use util::{RangeExt, ResultExt, TryFutureExt, debug_panic, rel_path::RelPath};
  55use workspace::{
  56    OpenInTerminal, WeakItemHandle, Workspace,
  57    dock::{DockPosition, Panel, PanelEvent},
  58    item::ItemHandle,
  59    searchable::{SearchEvent, SearchableItem},
  60};
  61use worktree::{Entry, ProjectEntryId, WorktreeId};
  62
  63actions!(
  64    outline_panel,
  65    [
  66        /// Collapses all entries in the outline tree.
  67        CollapseAllEntries,
  68        /// Collapses the currently selected entry.
  69        CollapseSelectedEntry,
  70        /// Expands all entries in the outline tree.
  71        ExpandAllEntries,
  72        /// Expands the currently selected entry.
  73        ExpandSelectedEntry,
  74        /// Folds the selected directory.
  75        FoldDirectory,
  76        /// Opens the selected entry in the editor.
  77        OpenSelectedEntry,
  78        /// Reveals the selected item in the system file manager.
  79        RevealInFileManager,
  80        /// Scroll half a page upwards
  81        ScrollUp,
  82        /// Scroll half a page downwards
  83        ScrollDown,
  84        /// Scroll until the cursor displays at the center
  85        ScrollCursorCenter,
  86        /// Scroll until the cursor displays at the top
  87        ScrollCursorTop,
  88        /// Scroll until the cursor displays at the bottom
  89        ScrollCursorBottom,
  90        /// Selects the parent of the current entry.
  91        SelectParent,
  92        /// Toggles the pin status of the active editor.
  93        ToggleActiveEditorPin,
  94        /// Unfolds the selected directory.
  95        UnfoldDirectory,
  96        /// Toggles the outline panel.
  97        Toggle,
  98        /// Toggles focus on the outline panel.
  99        ToggleFocus,
 100    ]
 101);
 102
 103const OUTLINE_PANEL_KEY: &str = "OutlinePanel";
 104const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
 105
 106type Outline = OutlineItem<language::Anchor>;
 107type HighlightStyleData = Arc<OnceLock<Vec<(Range<usize>, HighlightStyle)>>>;
 108
 109pub struct OutlinePanel {
 110    fs: Arc<dyn Fs>,
 111    width: Option<Pixels>,
 112    project: Entity<Project>,
 113    workspace: WeakEntity<Workspace>,
 114    active: bool,
 115    pinned: bool,
 116    scroll_handle: UniformListScrollHandle,
 117    rendered_entries_len: usize,
 118    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 119    focus_handle: FocusHandle,
 120    pending_serialization: Task<Option<()>>,
 121    fs_entries_depth: HashMap<(WorktreeId, ProjectEntryId), usize>,
 122    fs_entries: Vec<FsEntry>,
 123    fs_children_count: HashMap<WorktreeId, HashMap<Arc<RelPath>, FsChildren>>,
 124    collapsed_entries: HashSet<CollapsedEntry>,
 125    unfolded_dirs: HashMap<WorktreeId, BTreeSet<ProjectEntryId>>,
 126    selected_entry: SelectedEntry,
 127    active_item: Option<ActiveItem>,
 128    _subscriptions: Vec<Subscription>,
 129    new_entries_for_fs_update: HashSet<ExcerptId>,
 130    fs_entries_update_task: Task<()>,
 131    cached_entries_update_task: Task<()>,
 132    reveal_selection_task: Task<anyhow::Result<()>>,
 133    outline_fetch_tasks: HashMap<BufferId, Task<()>>,
 134    excerpts: HashMap<BufferId, HashMap<ExcerptId, Excerpt>>,
 135    cached_entries: Vec<CachedEntry>,
 136    filter_editor: Entity<Editor>,
 137    mode: ItemsDisplayMode,
 138    max_width_item_index: Option<usize>,
 139    preserve_selection_on_buffer_fold_toggles: HashSet<BufferId>,
 140    pending_default_expansion_depth: Option<usize>,
 141    outline_children_cache: HashMap<BufferId, HashMap<(Range<Anchor>, usize), bool>>,
 142}
 143
 144#[derive(Debug)]
 145enum ItemsDisplayMode {
 146    Search(SearchState),
 147    Outline,
 148}
 149
 150#[derive(Debug)]
 151struct SearchState {
 152    kind: SearchKind,
 153    query: String,
 154    matches: Vec<(Range<editor::Anchor>, Arc<OnceLock<SearchData>>)>,
 155    highlight_search_match_tx: channel::Sender<HighlightArguments>,
 156    _search_match_highlighter: Task<()>,
 157    _search_match_notify: Task<()>,
 158}
 159
 160struct HighlightArguments {
 161    multi_buffer_snapshot: MultiBufferSnapshot,
 162    match_range: Range<editor::Anchor>,
 163    search_data: Arc<OnceLock<SearchData>>,
 164}
 165
 166impl SearchState {
 167    fn new(
 168        kind: SearchKind,
 169        query: String,
 170        previous_matches: HashMap<Range<editor::Anchor>, Arc<OnceLock<SearchData>>>,
 171        new_matches: Vec<Range<editor::Anchor>>,
 172        theme: Arc<SyntaxTheme>,
 173        window: &mut Window,
 174        cx: &mut Context<OutlinePanel>,
 175    ) -> Self {
 176        let (highlight_search_match_tx, highlight_search_match_rx) = channel::unbounded();
 177        let (notify_tx, notify_rx) = channel::unbounded::<()>();
 178        Self {
 179            kind,
 180            query,
 181            matches: new_matches
 182                .into_iter()
 183                .map(|range| {
 184                    let search_data = previous_matches
 185                        .get(&range)
 186                        .map(Arc::clone)
 187                        .unwrap_or_default();
 188                    (range, search_data)
 189                })
 190                .collect(),
 191            highlight_search_match_tx,
 192            _search_match_highlighter: cx.background_spawn(async move {
 193                while let Ok(highlight_arguments) = highlight_search_match_rx.recv().await {
 194                    let needs_init = highlight_arguments.search_data.get().is_none();
 195                    let search_data = highlight_arguments.search_data.get_or_init(|| {
 196                        SearchData::new(
 197                            &highlight_arguments.match_range,
 198                            &highlight_arguments.multi_buffer_snapshot,
 199                        )
 200                    });
 201                    if needs_init {
 202                        notify_tx.try_send(()).ok();
 203                    }
 204
 205                    let highlight_data = &search_data.highlights_data;
 206                    if highlight_data.get().is_some() {
 207                        continue;
 208                    }
 209                    let mut left_whitespaces_count = 0;
 210                    let mut non_whitespace_symbol_occurred = false;
 211                    let context_offset_range = search_data
 212                        .context_range
 213                        .to_offset(&highlight_arguments.multi_buffer_snapshot);
 214                    let mut offset = context_offset_range.start;
 215                    let mut context_text = String::new();
 216                    let mut highlight_ranges = Vec::new();
 217                    for mut chunk in highlight_arguments
 218                        .multi_buffer_snapshot
 219                        .chunks(context_offset_range.start..context_offset_range.end, true)
 220                    {
 221                        if !non_whitespace_symbol_occurred {
 222                            for c in chunk.text.chars() {
 223                                if c.is_whitespace() {
 224                                    left_whitespaces_count += c.len_utf8();
 225                                } else {
 226                                    non_whitespace_symbol_occurred = true;
 227                                    break;
 228                                }
 229                            }
 230                        }
 231
 232                        if chunk.text.len() > context_offset_range.end - offset {
 233                            chunk.text = &chunk.text[0..(context_offset_range.end - offset)];
 234                            offset = context_offset_range.end;
 235                        } else {
 236                            offset += chunk.text.len();
 237                        }
 238                        let style = chunk
 239                            .syntax_highlight_id
 240                            .and_then(|highlight| highlight.style(&theme));
 241                        if let Some(style) = style {
 242                            let start = context_text.len();
 243                            let end = start + chunk.text.len();
 244                            highlight_ranges.push((start..end, style));
 245                        }
 246                        context_text.push_str(chunk.text);
 247                        if offset >= context_offset_range.end {
 248                            break;
 249                        }
 250                    }
 251
 252                    highlight_ranges.iter_mut().for_each(|(range, _)| {
 253                        range.start = range.start.saturating_sub(left_whitespaces_count);
 254                        range.end = range.end.saturating_sub(left_whitespaces_count);
 255                    });
 256                    if highlight_data.set(highlight_ranges).ok().is_some() {
 257                        notify_tx.try_send(()).ok();
 258                    }
 259
 260                    let trimmed_text = context_text[left_whitespaces_count..].to_owned();
 261                    debug_assert_eq!(
 262                        trimmed_text, search_data.context_text,
 263                        "Highlighted text that does not match the buffer text"
 264                    );
 265                }
 266            }),
 267            _search_match_notify: cx.spawn_in(window, async move |outline_panel, cx| {
 268                loop {
 269                    match notify_rx.recv().await {
 270                        Ok(()) => {}
 271                        Err(_) => break,
 272                    };
 273                    while let Ok(()) = notify_rx.try_recv() {
 274                        //
 275                    }
 276                    let update_result = outline_panel.update(cx, |_, cx| {
 277                        cx.notify();
 278                    });
 279                    if update_result.is_err() {
 280                        break;
 281                    }
 282                }
 283            }),
 284        }
 285    }
 286}
 287
 288#[derive(Debug)]
 289enum SelectedEntry {
 290    Invalidated(Option<PanelEntry>),
 291    Valid(PanelEntry, usize),
 292    None,
 293}
 294
 295impl SelectedEntry {
 296    fn invalidate(&mut self) {
 297        match std::mem::replace(self, SelectedEntry::None) {
 298            Self::Valid(entry, _) => *self = Self::Invalidated(Some(entry)),
 299            Self::None => *self = Self::Invalidated(None),
 300            other => *self = other,
 301        }
 302    }
 303
 304    fn is_invalidated(&self) -> bool {
 305        matches!(self, Self::Invalidated(_))
 306    }
 307}
 308
 309#[derive(Debug, Clone, Copy, Default)]
 310struct FsChildren {
 311    files: usize,
 312    dirs: usize,
 313}
 314
 315impl FsChildren {
 316    fn may_be_fold_part(&self) -> bool {
 317        self.dirs == 0 || (self.dirs == 1 && self.files == 0)
 318    }
 319}
 320
 321#[derive(Clone, Debug)]
 322struct CachedEntry {
 323    depth: usize,
 324    string_match: Option<StringMatch>,
 325    entry: PanelEntry,
 326}
 327
 328#[derive(Clone, Debug, PartialEq, Eq, Hash)]
 329enum CollapsedEntry {
 330    Dir(WorktreeId, ProjectEntryId),
 331    File(WorktreeId, BufferId),
 332    ExternalFile(BufferId),
 333    Excerpt(BufferId, ExcerptId),
 334    Outline(BufferId, ExcerptId, Range<Anchor>),
 335}
 336
 337#[derive(Debug)]
 338struct Excerpt {
 339    range: ExcerptRange<language::Anchor>,
 340    outlines: ExcerptOutlines,
 341}
 342
 343impl Excerpt {
 344    fn invalidate_outlines(&mut self) {
 345        if let ExcerptOutlines::Outlines(valid_outlines) = &mut self.outlines {
 346            self.outlines = ExcerptOutlines::Invalidated(std::mem::take(valid_outlines));
 347        }
 348    }
 349
 350    fn iter_outlines(&self) -> impl Iterator<Item = &Outline> {
 351        match &self.outlines {
 352            ExcerptOutlines::Outlines(outlines) => outlines.iter(),
 353            ExcerptOutlines::Invalidated(outlines) => outlines.iter(),
 354            ExcerptOutlines::NotFetched => [].iter(),
 355        }
 356    }
 357
 358    fn should_fetch_outlines(&self) -> bool {
 359        match &self.outlines {
 360            ExcerptOutlines::Outlines(_) => false,
 361            ExcerptOutlines::Invalidated(_) => true,
 362            ExcerptOutlines::NotFetched => true,
 363        }
 364    }
 365}
 366
 367#[derive(Debug)]
 368enum ExcerptOutlines {
 369    Outlines(Vec<Outline>),
 370    Invalidated(Vec<Outline>),
 371    NotFetched,
 372}
 373
 374#[derive(Clone, Debug, PartialEq, Eq)]
 375struct FoldedDirsEntry {
 376    worktree_id: WorktreeId,
 377    entries: Vec<GitEntry>,
 378}
 379
 380// TODO: collapse the inner enums into panel entry
 381#[derive(Clone, Debug)]
 382enum PanelEntry {
 383    Fs(FsEntry),
 384    FoldedDirs(FoldedDirsEntry),
 385    Outline(OutlineEntry),
 386    Search(SearchEntry),
 387}
 388
 389#[derive(Clone, Debug)]
 390struct SearchEntry {
 391    match_range: Range<editor::Anchor>,
 392    kind: SearchKind,
 393    render_data: Arc<OnceLock<SearchData>>,
 394}
 395
 396#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 397enum SearchKind {
 398    Project,
 399    Buffer,
 400}
 401
 402#[derive(Clone, Debug)]
 403struct SearchData {
 404    context_range: Range<editor::Anchor>,
 405    context_text: String,
 406    truncated_left: bool,
 407    truncated_right: bool,
 408    search_match_indices: Vec<Range<usize>>,
 409    highlights_data: HighlightStyleData,
 410}
 411
 412impl PartialEq for PanelEntry {
 413    fn eq(&self, other: &Self) -> bool {
 414        match (self, other) {
 415            (Self::Fs(a), Self::Fs(b)) => a == b,
 416            (
 417                Self::FoldedDirs(FoldedDirsEntry {
 418                    worktree_id: worktree_id_a,
 419                    entries: entries_a,
 420                }),
 421                Self::FoldedDirs(FoldedDirsEntry {
 422                    worktree_id: worktree_id_b,
 423                    entries: entries_b,
 424                }),
 425            ) => worktree_id_a == worktree_id_b && entries_a == entries_b,
 426            (Self::Outline(a), Self::Outline(b)) => a == b,
 427            (
 428                Self::Search(SearchEntry {
 429                    match_range: match_range_a,
 430                    kind: kind_a,
 431                    ..
 432                }),
 433                Self::Search(SearchEntry {
 434                    match_range: match_range_b,
 435                    kind: kind_b,
 436                    ..
 437                }),
 438            ) => match_range_a == match_range_b && kind_a == kind_b,
 439            _ => false,
 440        }
 441    }
 442}
 443
 444impl Eq for PanelEntry {}
 445
 446const SEARCH_MATCH_CONTEXT_SIZE: u32 = 40;
 447const TRUNCATED_CONTEXT_MARK: &str = "";
 448
 449impl SearchData {
 450    fn new(
 451        match_range: &Range<editor::Anchor>,
 452        multi_buffer_snapshot: &MultiBufferSnapshot,
 453    ) -> Self {
 454        let match_point_range = match_range.to_point(multi_buffer_snapshot);
 455        let context_left_border = multi_buffer_snapshot.clip_point(
 456            language::Point::new(
 457                match_point_range.start.row,
 458                match_point_range
 459                    .start
 460                    .column
 461                    .saturating_sub(SEARCH_MATCH_CONTEXT_SIZE),
 462            ),
 463            Bias::Left,
 464        );
 465        let context_right_border = multi_buffer_snapshot.clip_point(
 466            language::Point::new(
 467                match_point_range.end.row,
 468                match_point_range.end.column + SEARCH_MATCH_CONTEXT_SIZE,
 469            ),
 470            Bias::Right,
 471        );
 472
 473        let context_anchor_range =
 474            (context_left_border..context_right_border).to_anchors(multi_buffer_snapshot);
 475        let context_offset_range = context_anchor_range.to_offset(multi_buffer_snapshot);
 476        let match_offset_range = match_range.to_offset(multi_buffer_snapshot);
 477
 478        let mut search_match_indices = vec![
 479            match_offset_range.start - context_offset_range.start
 480                ..match_offset_range.end - context_offset_range.start,
 481        ];
 482
 483        let entire_context_text = multi_buffer_snapshot
 484            .text_for_range(context_offset_range.clone())
 485            .collect::<String>();
 486        let left_whitespaces_offset = entire_context_text
 487            .chars()
 488            .take_while(|c| c.is_whitespace())
 489            .map(|c| c.len_utf8())
 490            .sum::<usize>();
 491
 492        let mut extended_context_left_border = context_left_border;
 493        extended_context_left_border.column = extended_context_left_border.column.saturating_sub(1);
 494        let extended_context_left_border =
 495            multi_buffer_snapshot.clip_point(extended_context_left_border, Bias::Left);
 496        let mut extended_context_right_border = context_right_border;
 497        extended_context_right_border.column += 1;
 498        let extended_context_right_border =
 499            multi_buffer_snapshot.clip_point(extended_context_right_border, Bias::Right);
 500
 501        let truncated_left = left_whitespaces_offset == 0
 502            && extended_context_left_border < context_left_border
 503            && multi_buffer_snapshot
 504                .chars_at(extended_context_left_border)
 505                .last()
 506                .is_some_and(|c| !c.is_whitespace());
 507        let truncated_right = entire_context_text
 508            .chars()
 509            .last()
 510            .is_none_or(|c| !c.is_whitespace())
 511            && extended_context_right_border > context_right_border
 512            && multi_buffer_snapshot
 513                .chars_at(extended_context_right_border)
 514                .next()
 515                .is_some_and(|c| !c.is_whitespace());
 516        search_match_indices.iter_mut().for_each(|range| {
 517            range.start = range.start.saturating_sub(left_whitespaces_offset);
 518            range.end = range.end.saturating_sub(left_whitespaces_offset);
 519        });
 520
 521        let trimmed_row_offset_range =
 522            context_offset_range.start + left_whitespaces_offset..context_offset_range.end;
 523        let trimmed_text = entire_context_text[left_whitespaces_offset..].to_owned();
 524        Self {
 525            highlights_data: Arc::default(),
 526            search_match_indices,
 527            context_range: trimmed_row_offset_range.to_anchors(multi_buffer_snapshot),
 528            context_text: trimmed_text,
 529            truncated_left,
 530            truncated_right,
 531        }
 532    }
 533}
 534
 535#[derive(Clone, Debug, PartialEq, Eq, Hash)]
 536struct OutlineEntryExcerpt {
 537    id: ExcerptId,
 538    buffer_id: BufferId,
 539    range: ExcerptRange<language::Anchor>,
 540}
 541
 542#[derive(Clone, Debug, Eq)]
 543struct OutlineEntryOutline {
 544    buffer_id: BufferId,
 545    excerpt_id: ExcerptId,
 546    outline: Outline,
 547}
 548
 549impl PartialEq for OutlineEntryOutline {
 550    fn eq(&self, other: &Self) -> bool {
 551        self.buffer_id == other.buffer_id
 552            && self.excerpt_id == other.excerpt_id
 553            && self.outline.depth == other.outline.depth
 554            && self.outline.range == other.outline.range
 555            && self.outline.text == other.outline.text
 556    }
 557}
 558
 559impl Hash for OutlineEntryOutline {
 560    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 561        (
 562            self.buffer_id,
 563            self.excerpt_id,
 564            self.outline.depth,
 565            &self.outline.range,
 566            &self.outline.text,
 567        )
 568            .hash(state);
 569    }
 570}
 571
 572#[derive(Clone, Debug, PartialEq, Eq)]
 573enum OutlineEntry {
 574    Excerpt(OutlineEntryExcerpt),
 575    Outline(OutlineEntryOutline),
 576}
 577
 578impl OutlineEntry {
 579    fn ids(&self) -> (BufferId, ExcerptId) {
 580        match self {
 581            OutlineEntry::Excerpt(excerpt) => (excerpt.buffer_id, excerpt.id),
 582            OutlineEntry::Outline(outline) => (outline.buffer_id, outline.excerpt_id),
 583        }
 584    }
 585}
 586
 587#[derive(Debug, Clone, Eq)]
 588struct FsEntryFile {
 589    worktree_id: WorktreeId,
 590    entry: GitEntry,
 591    buffer_id: BufferId,
 592    excerpts: Vec<ExcerptId>,
 593}
 594
 595impl PartialEq for FsEntryFile {
 596    fn eq(&self, other: &Self) -> bool {
 597        self.worktree_id == other.worktree_id
 598            && self.entry.id == other.entry.id
 599            && self.buffer_id == other.buffer_id
 600    }
 601}
 602
 603impl Hash for FsEntryFile {
 604    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 605        (self.buffer_id, self.entry.id, self.worktree_id).hash(state);
 606    }
 607}
 608
 609#[derive(Debug, Clone, Eq)]
 610struct FsEntryDirectory {
 611    worktree_id: WorktreeId,
 612    entry: GitEntry,
 613}
 614
 615impl PartialEq for FsEntryDirectory {
 616    fn eq(&self, other: &Self) -> bool {
 617        self.worktree_id == other.worktree_id && self.entry.id == other.entry.id
 618    }
 619}
 620
 621impl Hash for FsEntryDirectory {
 622    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 623        (self.worktree_id, self.entry.id).hash(state);
 624    }
 625}
 626
 627#[derive(Debug, Clone, Eq)]
 628struct FsEntryExternalFile {
 629    buffer_id: BufferId,
 630    excerpts: Vec<ExcerptId>,
 631}
 632
 633impl PartialEq for FsEntryExternalFile {
 634    fn eq(&self, other: &Self) -> bool {
 635        self.buffer_id == other.buffer_id
 636    }
 637}
 638
 639impl Hash for FsEntryExternalFile {
 640    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 641        self.buffer_id.hash(state);
 642    }
 643}
 644
 645#[derive(Clone, Debug, Eq, PartialEq)]
 646enum FsEntry {
 647    ExternalFile(FsEntryExternalFile),
 648    Directory(FsEntryDirectory),
 649    File(FsEntryFile),
 650}
 651
 652struct ActiveItem {
 653    item_handle: Box<dyn WeakItemHandle>,
 654    active_editor: WeakEntity<Editor>,
 655    _buffer_search_subscription: Subscription,
 656    _editor_subscription: Subscription,
 657}
 658
 659#[derive(Debug)]
 660pub enum Event {
 661    Focus,
 662}
 663
 664#[derive(Serialize, Deserialize)]
 665struct SerializedOutlinePanel {
 666    width: Option<Pixels>,
 667    active: Option<bool>,
 668}
 669
 670pub fn init(cx: &mut App) {
 671    cx.observe_new(|workspace: &mut Workspace, _, _| {
 672        workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
 673            workspace.toggle_panel_focus::<OutlinePanel>(window, cx);
 674        });
 675        workspace.register_action(|workspace, _: &Toggle, window, cx| {
 676            if !workspace.toggle_panel_focus::<OutlinePanel>(window, cx) {
 677                workspace.close_panel::<OutlinePanel>(window, cx);
 678            }
 679        });
 680    })
 681    .detach();
 682}
 683
 684impl OutlinePanel {
 685    pub async fn load(
 686        workspace: WeakEntity<Workspace>,
 687        mut cx: AsyncWindowContext,
 688    ) -> anyhow::Result<Entity<Self>> {
 689        let serialized_panel = match workspace
 690            .read_with(&cx, |workspace, _| {
 691                OutlinePanel::serialization_key(workspace)
 692            })
 693            .ok()
 694            .flatten()
 695        {
 696            Some(serialization_key) => cx
 697                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
 698                .await
 699                .context("loading outline panel")
 700                .log_err()
 701                .flatten()
 702                .map(|panel| serde_json::from_str::<SerializedOutlinePanel>(&panel))
 703                .transpose()
 704                .log_err()
 705                .flatten(),
 706            None => None,
 707        };
 708
 709        workspace.update_in(&mut cx, |workspace, window, cx| {
 710            let panel = Self::new(workspace, serialized_panel.as_ref(), window, cx);
 711            if let Some(serialized_panel) = serialized_panel {
 712                panel.update(cx, |panel, cx| {
 713                    panel.width = serialized_panel.width.map(|px| px.round());
 714                    cx.notify();
 715                });
 716            }
 717            panel
 718        })
 719    }
 720
 721    fn new(
 722        workspace: &mut Workspace,
 723        serialized: Option<&SerializedOutlinePanel>,
 724        window: &mut Window,
 725        cx: &mut Context<Workspace>,
 726    ) -> Entity<Self> {
 727        let project = workspace.project().clone();
 728        let workspace_handle = cx.entity().downgrade();
 729
 730        cx.new(|cx| {
 731            let filter_editor = cx.new(|cx| {
 732                let mut editor = Editor::single_line(window, cx);
 733                editor.set_placeholder_text("Search buffer symbols…", window, cx);
 734                editor
 735            });
 736            let filter_update_subscription = cx.subscribe_in(
 737                &filter_editor,
 738                window,
 739                |outline_panel: &mut Self, _, event, window, cx| {
 740                    if let editor::EditorEvent::BufferEdited = event {
 741                        outline_panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
 742                    }
 743                },
 744            );
 745
 746            let focus_handle = cx.focus_handle();
 747            let focus_subscription = cx.on_focus(&focus_handle, window, Self::focus_in);
 748            let workspace_subscription = cx.subscribe_in(
 749                &workspace
 750                    .weak_handle()
 751                    .upgrade()
 752                    .expect("have a &mut Workspace"),
 753                window,
 754                move |outline_panel, workspace, event, window, cx| {
 755                    if let workspace::Event::ActiveItemChanged = event {
 756                        if let Some((new_active_item, new_active_editor)) =
 757                            workspace_active_editor(workspace.read(cx), cx)
 758                        {
 759                            if outline_panel.should_replace_active_item(new_active_item.as_ref()) {
 760                                outline_panel.replace_active_editor(
 761                                    new_active_item,
 762                                    new_active_editor,
 763                                    window,
 764                                    cx,
 765                                );
 766                            }
 767                        } else {
 768                            outline_panel.clear_previous(window, cx);
 769                            cx.notify();
 770                        }
 771                    }
 772                },
 773            );
 774
 775            let icons_subscription = cx.observe_global::<FileIcons>(|_, cx| {
 776                cx.notify();
 777            });
 778
 779            let mut outline_panel_settings = *OutlinePanelSettings::get_global(cx);
 780            let mut current_theme = ThemeSettings::get_global(cx).clone();
 781            let mut document_symbols_by_buffer = HashMap::default();
 782            let settings_subscription =
 783                cx.observe_global_in::<SettingsStore>(window, move |outline_panel, window, cx| {
 784                    let new_settings = OutlinePanelSettings::get_global(cx);
 785                    let new_theme = ThemeSettings::get_global(cx);
 786                    let mut outlines_invalidated = false;
 787                    if &current_theme != new_theme {
 788                        outline_panel_settings = *new_settings;
 789                        current_theme = new_theme.clone();
 790                        for excerpts in outline_panel.excerpts.values_mut() {
 791                            for excerpt in excerpts.values_mut() {
 792                                excerpt.invalidate_outlines();
 793                            }
 794                        }
 795                        outlines_invalidated = true;
 796                        let update_cached_items = outline_panel.update_non_fs_items(window, cx);
 797                        if update_cached_items {
 798                            outline_panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
 799                        }
 800                    } else if &outline_panel_settings != new_settings {
 801                        let old_expansion_depth = outline_panel_settings.expand_outlines_with_depth;
 802                        outline_panel_settings = *new_settings;
 803
 804                        if old_expansion_depth != new_settings.expand_outlines_with_depth {
 805                            let old_collapsed_entries = outline_panel.collapsed_entries.clone();
 806                            outline_panel
 807                                .collapsed_entries
 808                                .retain(|entry| !matches!(entry, CollapsedEntry::Outline(..)));
 809
 810                            let new_depth = new_settings.expand_outlines_with_depth;
 811
 812                            for (buffer_id, excerpts) in &outline_panel.excerpts {
 813                                for (excerpt_id, excerpt) in excerpts {
 814                                    if let ExcerptOutlines::Outlines(outlines) = &excerpt.outlines {
 815                                        for outline in outlines {
 816                                            if outline_panel
 817                                                .outline_children_cache
 818                                                .get(buffer_id)
 819                                                .and_then(|children_map| {
 820                                                    let key =
 821                                                        (outline.range.clone(), outline.depth);
 822                                                    children_map.get(&key)
 823                                                })
 824                                                .copied()
 825                                                .unwrap_or(false)
 826                                                && (new_depth == 0 || outline.depth >= new_depth)
 827                                            {
 828                                                outline_panel.collapsed_entries.insert(
 829                                                    CollapsedEntry::Outline(
 830                                                        *buffer_id,
 831                                                        *excerpt_id,
 832                                                        outline.range.clone(),
 833                                                    ),
 834                                                );
 835                                            }
 836                                        }
 837                                    }
 838                                }
 839                            }
 840
 841                            if old_collapsed_entries != outline_panel.collapsed_entries {
 842                                outline_panel.update_cached_entries(
 843                                    Some(UPDATE_DEBOUNCE),
 844                                    window,
 845                                    cx,
 846                                );
 847                            }
 848                        } else {
 849                            cx.notify();
 850                        }
 851                    }
 852
 853                    if !outlines_invalidated {
 854                        let new_document_symbols = outline_panel
 855                            .excerpts
 856                            .keys()
 857                            .filter_map(|buffer_id| {
 858                                let buffer = outline_panel
 859                                    .project
 860                                    .read(cx)
 861                                    .buffer_for_id(*buffer_id, cx)?;
 862                                let buffer = buffer.read(cx);
 863                                let doc_symbols = language_settings(
 864                                    buffer.language().map(|l| l.name()),
 865                                    buffer.file(),
 866                                    cx,
 867                                )
 868                                .document_symbols;
 869                                Some((*buffer_id, doc_symbols))
 870                            })
 871                            .collect();
 872                        if new_document_symbols != document_symbols_by_buffer {
 873                            document_symbols_by_buffer = new_document_symbols;
 874                            for excerpts in outline_panel.excerpts.values_mut() {
 875                                for excerpt in excerpts.values_mut() {
 876                                    excerpt.invalidate_outlines();
 877                                }
 878                            }
 879                            let update_cached_items = outline_panel.update_non_fs_items(window, cx);
 880                            if update_cached_items {
 881                                outline_panel.update_cached_entries(
 882                                    Some(UPDATE_DEBOUNCE),
 883                                    window,
 884                                    cx,
 885                                );
 886                            }
 887                        }
 888                    }
 889                });
 890
 891            let scroll_handle = UniformListScrollHandle::new();
 892
 893            let mut outline_panel = Self {
 894                mode: ItemsDisplayMode::Outline,
 895                active: serialized.and_then(|s| s.active).unwrap_or(false),
 896                pinned: false,
 897                workspace: workspace_handle,
 898                project,
 899                fs: workspace.app_state().fs.clone(),
 900                max_width_item_index: None,
 901                scroll_handle,
 902                rendered_entries_len: 0,
 903                focus_handle,
 904                filter_editor,
 905                fs_entries: Vec::new(),
 906                fs_entries_depth: HashMap::default(),
 907                fs_children_count: HashMap::default(),
 908                collapsed_entries: HashSet::default(),
 909                unfolded_dirs: HashMap::default(),
 910                selected_entry: SelectedEntry::None,
 911                context_menu: None,
 912                width: None,
 913                active_item: None,
 914                pending_serialization: Task::ready(None),
 915                new_entries_for_fs_update: HashSet::default(),
 916                preserve_selection_on_buffer_fold_toggles: HashSet::default(),
 917                pending_default_expansion_depth: None,
 918                fs_entries_update_task: Task::ready(()),
 919                cached_entries_update_task: Task::ready(()),
 920                reveal_selection_task: Task::ready(Ok(())),
 921                outline_fetch_tasks: HashMap::default(),
 922                excerpts: HashMap::default(),
 923                cached_entries: Vec::new(),
 924                _subscriptions: vec![
 925                    settings_subscription,
 926                    icons_subscription,
 927                    focus_subscription,
 928                    workspace_subscription,
 929                    filter_update_subscription,
 930                ],
 931                outline_children_cache: HashMap::default(),
 932            };
 933            if let Some((item, editor)) = workspace_active_editor(workspace, cx) {
 934                outline_panel.replace_active_editor(item, editor, window, cx);
 935            }
 936            outline_panel
 937        })
 938    }
 939
 940    fn serialization_key(workspace: &Workspace) -> Option<String> {
 941        workspace
 942            .database_id()
 943            .map(|id| i64::from(id).to_string())
 944            .or(workspace.session_id())
 945            .map(|id| format!("{}-{:?}", OUTLINE_PANEL_KEY, id))
 946    }
 947
 948    fn serialize(&mut self, cx: &mut Context<Self>) {
 949        let Some(serialization_key) = self
 950            .workspace
 951            .read_with(cx, |workspace, _| {
 952                OutlinePanel::serialization_key(workspace)
 953            })
 954            .ok()
 955            .flatten()
 956        else {
 957            return;
 958        };
 959        let width = self.width;
 960        let active = Some(self.active);
 961        self.pending_serialization = cx.background_spawn(
 962            async move {
 963                KEY_VALUE_STORE
 964                    .write_kvp(
 965                        serialization_key,
 966                        serde_json::to_string(&SerializedOutlinePanel { width, active })?,
 967                    )
 968                    .await?;
 969                anyhow::Ok(())
 970            }
 971            .log_err(),
 972        );
 973    }
 974
 975    fn dispatch_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 976        let mut dispatch_context = KeyContext::new_with_defaults();
 977        dispatch_context.add("OutlinePanel");
 978        dispatch_context.add("menu");
 979        let identifier = if self.filter_editor.focus_handle(cx).is_focused(window) {
 980            "editing"
 981        } else {
 982            "not_editing"
 983        };
 984        dispatch_context.add(identifier);
 985        dispatch_context
 986    }
 987
 988    fn unfold_directory(
 989        &mut self,
 990        _: &UnfoldDirectory,
 991        window: &mut Window,
 992        cx: &mut Context<Self>,
 993    ) {
 994        if let Some(PanelEntry::FoldedDirs(FoldedDirsEntry {
 995            worktree_id,
 996            entries,
 997            ..
 998        })) = self.selected_entry().cloned()
 999        {
1000            self.unfolded_dirs
1001                .entry(worktree_id)
1002                .or_default()
1003                .extend(entries.iter().map(|entry| entry.id));
1004            self.update_cached_entries(None, window, cx);
1005        }
1006    }
1007
1008    fn fold_directory(&mut self, _: &FoldDirectory, window: &mut Window, cx: &mut Context<Self>) {
1009        let (worktree_id, entry) = match self.selected_entry().cloned() {
1010            Some(PanelEntry::Fs(FsEntry::Directory(directory))) => {
1011                (directory.worktree_id, Some(directory.entry))
1012            }
1013            Some(PanelEntry::FoldedDirs(folded_dirs)) => {
1014                (folded_dirs.worktree_id, folded_dirs.entries.last().cloned())
1015            }
1016            _ => return,
1017        };
1018        let Some(entry) = entry else {
1019            return;
1020        };
1021        let unfolded_dirs = self.unfolded_dirs.get_mut(&worktree_id);
1022        let worktree = self
1023            .project
1024            .read(cx)
1025            .worktree_for_id(worktree_id, cx)
1026            .map(|w| w.read(cx).snapshot());
1027        let Some((_, unfolded_dirs)) = worktree.zip(unfolded_dirs) else {
1028            return;
1029        };
1030
1031        unfolded_dirs.remove(&entry.id);
1032        self.update_cached_entries(None, window, cx);
1033    }
1034
1035    fn open_selected_entry(
1036        &mut self,
1037        _: &OpenSelectedEntry,
1038        window: &mut Window,
1039        cx: &mut Context<Self>,
1040    ) {
1041        if self.filter_editor.focus_handle(cx).is_focused(window) {
1042            cx.propagate()
1043        } else if let Some(selected_entry) = self.selected_entry().cloned() {
1044            self.scroll_editor_to_entry(&selected_entry, true, true, window, cx);
1045        }
1046    }
1047
1048    fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
1049        if self.filter_editor.focus_handle(cx).is_focused(window) {
1050            self.focus_handle.focus(window, cx);
1051        } else {
1052            self.filter_editor.focus_handle(cx).focus(window, cx);
1053        }
1054
1055        if self.context_menu.is_some() {
1056            self.context_menu.take();
1057            cx.notify();
1058        }
1059    }
1060
1061    fn open_excerpts(
1062        &mut self,
1063        action: &editor::actions::OpenExcerpts,
1064        window: &mut Window,
1065        cx: &mut Context<Self>,
1066    ) {
1067        if self.filter_editor.focus_handle(cx).is_focused(window) {
1068            cx.propagate()
1069        } else if let Some((active_editor, selected_entry)) =
1070            self.active_editor().zip(self.selected_entry().cloned())
1071        {
1072            self.scroll_editor_to_entry(&selected_entry, true, true, window, cx);
1073            active_editor.update(cx, |editor, cx| editor.open_excerpts(action, window, cx));
1074        }
1075    }
1076
1077    fn open_excerpts_split(
1078        &mut self,
1079        action: &editor::actions::OpenExcerptsSplit,
1080        window: &mut Window,
1081        cx: &mut Context<Self>,
1082    ) {
1083        if self.filter_editor.focus_handle(cx).is_focused(window) {
1084            cx.propagate()
1085        } else if let Some((active_editor, selected_entry)) =
1086            self.active_editor().zip(self.selected_entry().cloned())
1087        {
1088            self.scroll_editor_to_entry(&selected_entry, true, true, window, cx);
1089            active_editor.update(cx, |editor, cx| {
1090                editor.open_excerpts_in_split(action, window, cx)
1091            });
1092        }
1093    }
1094
1095    fn scroll_editor_to_entry(
1096        &mut self,
1097        entry: &PanelEntry,
1098        prefer_selection_change: bool,
1099        prefer_focus_change: bool,
1100        window: &mut Window,
1101        cx: &mut Context<OutlinePanel>,
1102    ) {
1103        let Some(active_editor) = self.active_editor() else {
1104            return;
1105        };
1106        let active_multi_buffer = active_editor.read(cx).buffer().clone();
1107        let multi_buffer_snapshot = active_multi_buffer.read(cx).snapshot(cx);
1108        let mut change_selection = prefer_selection_change;
1109        let mut change_focus = prefer_focus_change;
1110        let mut scroll_to_buffer = None;
1111        let scroll_target = match entry {
1112            PanelEntry::FoldedDirs(..) | PanelEntry::Fs(FsEntry::Directory(..)) => {
1113                change_focus = false;
1114                None
1115            }
1116            PanelEntry::Fs(FsEntry::ExternalFile(file)) => {
1117                change_selection = false;
1118                scroll_to_buffer = Some(file.buffer_id);
1119                multi_buffer_snapshot.excerpts().find_map(
1120                    |(excerpt_id, buffer_snapshot, excerpt_range)| {
1121                        if buffer_snapshot.remote_id() == file.buffer_id {
1122                            multi_buffer_snapshot
1123                                .anchor_in_buffer(excerpt_id, excerpt_range.context.start)
1124                        } else {
1125                            None
1126                        }
1127                    },
1128                )
1129            }
1130
1131            PanelEntry::Fs(FsEntry::File(file)) => {
1132                change_selection = false;
1133                scroll_to_buffer = Some(file.buffer_id);
1134                self.project
1135                    .update(cx, |project, cx| {
1136                        project
1137                            .path_for_entry(file.entry.id, cx)
1138                            .and_then(|path| project.get_open_buffer(&path, cx))
1139                    })
1140                    .map(|buffer| {
1141                        active_multi_buffer
1142                            .read(cx)
1143                            .excerpts_for_buffer(buffer.read(cx).remote_id(), cx)
1144                    })
1145                    .and_then(|excerpts| {
1146                        let (excerpt_id, excerpt_range) = excerpts.first()?;
1147                        multi_buffer_snapshot
1148                            .anchor_in_buffer(*excerpt_id, excerpt_range.context.start)
1149                    })
1150            }
1151            PanelEntry::Outline(OutlineEntry::Outline(outline)) => multi_buffer_snapshot
1152                .anchor_in_buffer(outline.excerpt_id, outline.outline.range.start)
1153                .or_else(|| {
1154                    multi_buffer_snapshot
1155                        .anchor_in_buffer(outline.excerpt_id, outline.outline.range.end)
1156                }),
1157            PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => {
1158                change_selection = false;
1159                change_focus = false;
1160                multi_buffer_snapshot.anchor_in_buffer(excerpt.id, excerpt.range.context.start)
1161            }
1162            PanelEntry::Search(search_entry) => Some(search_entry.match_range.start),
1163        };
1164
1165        if let Some(anchor) = scroll_target {
1166            let activate = self
1167                .workspace
1168                .update(cx, |workspace, cx| match self.active_item() {
1169                    Some(active_item) => workspace.activate_item(
1170                        active_item.as_ref(),
1171                        true,
1172                        change_focus,
1173                        window,
1174                        cx,
1175                    ),
1176                    None => workspace.activate_item(&active_editor, true, change_focus, window, cx),
1177                });
1178
1179            if activate.is_ok() {
1180                self.select_entry(entry.clone(), true, window, cx);
1181                if change_selection {
1182                    active_editor.update(cx, |editor, cx| {
1183                        editor.change_selections(
1184                            SelectionEffects::scroll(Autoscroll::center()),
1185                            window,
1186                            cx,
1187                            |s| s.select_ranges(Some(anchor..anchor)),
1188                        );
1189                    });
1190                } else {
1191                    let mut offset = Point::default();
1192                    if let Some(buffer_id) = scroll_to_buffer
1193                        && multi_buffer_snapshot.as_singleton().is_none()
1194                        && !active_editor.read(cx).is_buffer_folded(buffer_id, cx)
1195                    {
1196                        offset.y = -(active_editor.read(cx).file_header_size() as f64);
1197                    }
1198
1199                    active_editor.update(cx, |editor, cx| {
1200                        editor.set_scroll_anchor(ScrollAnchor { offset, anchor }, window, cx);
1201                    });
1202                }
1203
1204                if change_focus {
1205                    active_editor.focus_handle(cx).focus(window, cx);
1206                } else {
1207                    self.focus_handle.focus(window, cx);
1208                }
1209            }
1210        }
1211    }
1212
1213    fn scroll_up(&mut self, _: &ScrollUp, window: &mut Window, cx: &mut Context<Self>) {
1214        for _ in 0..self.rendered_entries_len / 2 {
1215            window.dispatch_action(SelectPrevious.boxed_clone(), cx);
1216        }
1217    }
1218
1219    fn scroll_down(&mut self, _: &ScrollDown, window: &mut Window, cx: &mut Context<Self>) {
1220        for _ in 0..self.rendered_entries_len / 2 {
1221            window.dispatch_action(SelectNext.boxed_clone(), cx);
1222        }
1223    }
1224
1225    fn scroll_cursor_center(
1226        &mut self,
1227        _: &ScrollCursorCenter,
1228        _: &mut Window,
1229        cx: &mut Context<Self>,
1230    ) {
1231        if let Some(selected_entry) = self.selected_entry() {
1232            let index = self
1233                .cached_entries
1234                .iter()
1235                .position(|cached_entry| &cached_entry.entry == selected_entry);
1236            if let Some(index) = index {
1237                self.scroll_handle
1238                    .scroll_to_item_strict(index, ScrollStrategy::Center);
1239                cx.notify();
1240            }
1241        }
1242    }
1243
1244    fn scroll_cursor_top(&mut self, _: &ScrollCursorTop, _: &mut Window, cx: &mut Context<Self>) {
1245        if let Some(selected_entry) = self.selected_entry() {
1246            let index = self
1247                .cached_entries
1248                .iter()
1249                .position(|cached_entry| &cached_entry.entry == selected_entry);
1250            if let Some(index) = index {
1251                self.scroll_handle
1252                    .scroll_to_item_strict(index, ScrollStrategy::Top);
1253                cx.notify();
1254            }
1255        }
1256    }
1257
1258    fn scroll_cursor_bottom(
1259        &mut self,
1260        _: &ScrollCursorBottom,
1261        _: &mut Window,
1262        cx: &mut Context<Self>,
1263    ) {
1264        if let Some(selected_entry) = self.selected_entry() {
1265            let index = self
1266                .cached_entries
1267                .iter()
1268                .position(|cached_entry| &cached_entry.entry == selected_entry);
1269            if let Some(index) = index {
1270                self.scroll_handle
1271                    .scroll_to_item_strict(index, ScrollStrategy::Bottom);
1272                cx.notify();
1273            }
1274        }
1275    }
1276
1277    fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
1278        if let Some(entry_to_select) = self.selected_entry().and_then(|selected_entry| {
1279            self.cached_entries
1280                .iter()
1281                .map(|cached_entry| &cached_entry.entry)
1282                .skip_while(|entry| entry != &selected_entry)
1283                .nth(1)
1284                .cloned()
1285        }) {
1286            self.select_entry(entry_to_select, true, window, cx);
1287        } else {
1288            self.select_first(&SelectFirst {}, window, cx)
1289        }
1290        if let Some(selected_entry) = self.selected_entry().cloned() {
1291            self.scroll_editor_to_entry(&selected_entry, true, false, window, cx);
1292        }
1293    }
1294
1295    fn select_previous(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
1296        if let Some(entry_to_select) = self.selected_entry().and_then(|selected_entry| {
1297            self.cached_entries
1298                .iter()
1299                .rev()
1300                .map(|cached_entry| &cached_entry.entry)
1301                .skip_while(|entry| entry != &selected_entry)
1302                .nth(1)
1303                .cloned()
1304        }) {
1305            self.select_entry(entry_to_select, true, window, cx);
1306        } else {
1307            self.select_last(&SelectLast, window, cx)
1308        }
1309        if let Some(selected_entry) = self.selected_entry().cloned() {
1310            self.scroll_editor_to_entry(&selected_entry, true, false, window, cx);
1311        }
1312    }
1313
1314    fn select_parent(&mut self, _: &SelectParent, window: &mut Window, cx: &mut Context<Self>) {
1315        if let Some(entry_to_select) = self.selected_entry().and_then(|selected_entry| {
1316            let mut previous_entries = self
1317                .cached_entries
1318                .iter()
1319                .rev()
1320                .map(|cached_entry| &cached_entry.entry)
1321                .skip_while(|entry| entry != &selected_entry)
1322                .skip(1);
1323            match &selected_entry {
1324                PanelEntry::Fs(fs_entry) => match fs_entry {
1325                    FsEntry::ExternalFile(..) => None,
1326                    FsEntry::File(FsEntryFile {
1327                        worktree_id, entry, ..
1328                    })
1329                    | FsEntry::Directory(FsEntryDirectory {
1330                        worktree_id, entry, ..
1331                    }) => entry.path.parent().and_then(|parent_path| {
1332                        previous_entries.find(|entry| match entry {
1333                            PanelEntry::Fs(FsEntry::Directory(directory)) => {
1334                                directory.worktree_id == *worktree_id
1335                                    && directory.entry.path.as_ref() == parent_path
1336                            }
1337                            PanelEntry::FoldedDirs(FoldedDirsEntry {
1338                                worktree_id: dirs_worktree_id,
1339                                entries: dirs,
1340                                ..
1341                            }) => {
1342                                dirs_worktree_id == worktree_id
1343                                    && dirs
1344                                        .last()
1345                                        .is_some_and(|dir| dir.path.as_ref() == parent_path)
1346                            }
1347                            _ => false,
1348                        })
1349                    }),
1350                },
1351                PanelEntry::FoldedDirs(folded_dirs) => folded_dirs
1352                    .entries
1353                    .first()
1354                    .and_then(|entry| entry.path.parent())
1355                    .and_then(|parent_path| {
1356                        previous_entries.find(|entry| {
1357                            if let PanelEntry::Fs(FsEntry::Directory(directory)) = entry {
1358                                directory.worktree_id == folded_dirs.worktree_id
1359                                    && directory.entry.path.as_ref() == parent_path
1360                            } else {
1361                                false
1362                            }
1363                        })
1364                    }),
1365                PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => {
1366                    previous_entries.find(|entry| match entry {
1367                        PanelEntry::Fs(FsEntry::File(file)) => {
1368                            file.buffer_id == excerpt.buffer_id
1369                                && file.excerpts.contains(&excerpt.id)
1370                        }
1371                        PanelEntry::Fs(FsEntry::ExternalFile(external_file)) => {
1372                            external_file.buffer_id == excerpt.buffer_id
1373                                && external_file.excerpts.contains(&excerpt.id)
1374                        }
1375                        _ => false,
1376                    })
1377                }
1378                PanelEntry::Outline(OutlineEntry::Outline(outline)) => {
1379                    previous_entries.find(|entry| {
1380                        if let PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) = entry {
1381                            outline.buffer_id == excerpt.buffer_id
1382                                && outline.excerpt_id == excerpt.id
1383                        } else {
1384                            false
1385                        }
1386                    })
1387                }
1388                PanelEntry::Search(_) => {
1389                    previous_entries.find(|entry| !matches!(entry, PanelEntry::Search(_)))
1390                }
1391            }
1392        }) {
1393            self.select_entry(entry_to_select.clone(), true, window, cx);
1394        } else {
1395            self.select_first(&SelectFirst {}, window, cx);
1396        }
1397    }
1398
1399    fn select_first(&mut self, _: &SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
1400        if let Some(first_entry) = self.cached_entries.first() {
1401            self.select_entry(first_entry.entry.clone(), true, window, cx);
1402        }
1403    }
1404
1405    fn select_last(&mut self, _: &SelectLast, window: &mut Window, cx: &mut Context<Self>) {
1406        if let Some(new_selection) = self
1407            .cached_entries
1408            .iter()
1409            .rev()
1410            .map(|cached_entry| &cached_entry.entry)
1411            .next()
1412        {
1413            self.select_entry(new_selection.clone(), true, window, cx);
1414        }
1415    }
1416
1417    fn autoscroll(&mut self, cx: &mut Context<Self>) {
1418        if let Some(selected_entry) = self.selected_entry() {
1419            let index = self
1420                .cached_entries
1421                .iter()
1422                .position(|cached_entry| &cached_entry.entry == selected_entry);
1423            if let Some(index) = index {
1424                self.scroll_handle
1425                    .scroll_to_item(index, ScrollStrategy::Center);
1426                cx.notify();
1427            }
1428        }
1429    }
1430
1431    fn focus_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1432        if !self.focus_handle.contains_focused(window, cx) {
1433            cx.emit(Event::Focus);
1434        }
1435    }
1436
1437    fn deploy_context_menu(
1438        &mut self,
1439        position: Point<Pixels>,
1440        entry: PanelEntry,
1441        window: &mut Window,
1442        cx: &mut Context<Self>,
1443    ) {
1444        self.select_entry(entry.clone(), true, window, cx);
1445        let is_root = match &entry {
1446            PanelEntry::Fs(FsEntry::File(FsEntryFile {
1447                worktree_id, entry, ..
1448            }))
1449            | PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory {
1450                worktree_id, entry, ..
1451            })) => self
1452                .project
1453                .read(cx)
1454                .worktree_for_id(*worktree_id, cx)
1455                .map(|worktree| {
1456                    worktree.read(cx).root_entry().map(|entry| entry.id) == Some(entry.id)
1457                })
1458                .unwrap_or(false),
1459            PanelEntry::FoldedDirs(FoldedDirsEntry {
1460                worktree_id,
1461                entries,
1462                ..
1463            }) => entries
1464                .first()
1465                .and_then(|entry| {
1466                    self.project
1467                        .read(cx)
1468                        .worktree_for_id(*worktree_id, cx)
1469                        .map(|worktree| {
1470                            worktree.read(cx).root_entry().map(|entry| entry.id) == Some(entry.id)
1471                        })
1472                })
1473                .unwrap_or(false),
1474            PanelEntry::Fs(FsEntry::ExternalFile(..)) => false,
1475            PanelEntry::Outline(..) => {
1476                cx.notify();
1477                return;
1478            }
1479            PanelEntry::Search(_) => {
1480                cx.notify();
1481                return;
1482            }
1483        };
1484        let auto_fold_dirs = OutlinePanelSettings::get_global(cx).auto_fold_dirs;
1485        let is_foldable = auto_fold_dirs && !is_root && self.is_foldable(&entry);
1486        let is_unfoldable = auto_fold_dirs && !is_root && self.is_unfoldable(&entry);
1487
1488        let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
1489            menu.context(self.focus_handle.clone())
1490                .action(
1491                    if cfg!(target_os = "macos") {
1492                        "Reveal in Finder"
1493                    } else if cfg!(target_os = "windows") {
1494                        "Reveal in File Explorer"
1495                    } else {
1496                        "Reveal in File Manager"
1497                    },
1498                    Box::new(RevealInFileManager),
1499                )
1500                .action("Open in Terminal", Box::new(OpenInTerminal))
1501                .when(is_unfoldable, |menu| {
1502                    menu.action("Unfold Directory", Box::new(UnfoldDirectory))
1503                })
1504                .when(is_foldable, |menu| {
1505                    menu.action("Fold Directory", Box::new(FoldDirectory))
1506                })
1507                .separator()
1508                .action("Copy Path", Box::new(zed_actions::workspace::CopyPath))
1509                .action(
1510                    "Copy Relative Path",
1511                    Box::new(zed_actions::workspace::CopyRelativePath),
1512                )
1513        });
1514        window.focus(&context_menu.focus_handle(cx), cx);
1515        let subscription = cx.subscribe(&context_menu, |outline_panel, _, _: &DismissEvent, cx| {
1516            outline_panel.context_menu.take();
1517            cx.notify();
1518        });
1519        self.context_menu = Some((context_menu, position, subscription));
1520        cx.notify();
1521    }
1522
1523    fn is_unfoldable(&self, entry: &PanelEntry) -> bool {
1524        matches!(entry, PanelEntry::FoldedDirs(..))
1525    }
1526
1527    fn is_foldable(&self, entry: &PanelEntry) -> bool {
1528        let (directory_worktree, directory_entry) = match entry {
1529            PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory {
1530                worktree_id,
1531                entry: directory_entry,
1532                ..
1533            })) => (*worktree_id, Some(directory_entry)),
1534            _ => return false,
1535        };
1536        let Some(directory_entry) = directory_entry else {
1537            return false;
1538        };
1539
1540        if self
1541            .unfolded_dirs
1542            .get(&directory_worktree)
1543            .is_none_or(|unfolded_dirs| !unfolded_dirs.contains(&directory_entry.id))
1544        {
1545            return false;
1546        }
1547
1548        let children = self
1549            .fs_children_count
1550            .get(&directory_worktree)
1551            .and_then(|entries| entries.get(&directory_entry.path))
1552            .copied()
1553            .unwrap_or_default();
1554
1555        children.may_be_fold_part() && children.dirs > 0
1556    }
1557
1558    fn expand_selected_entry(
1559        &mut self,
1560        _: &ExpandSelectedEntry,
1561        window: &mut Window,
1562        cx: &mut Context<Self>,
1563    ) {
1564        let Some(active_editor) = self.active_editor() else {
1565            return;
1566        };
1567        let Some(selected_entry) = self.selected_entry().cloned() else {
1568            return;
1569        };
1570        let mut buffers_to_unfold = HashSet::default();
1571        let entry_to_expand = match &selected_entry {
1572            PanelEntry::FoldedDirs(FoldedDirsEntry {
1573                entries: dir_entries,
1574                worktree_id,
1575                ..
1576            }) => dir_entries.last().map(|entry| {
1577                buffers_to_unfold.extend(self.buffers_inside_directory(*worktree_id, entry));
1578                CollapsedEntry::Dir(*worktree_id, entry.id)
1579            }),
1580            PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory {
1581                worktree_id, entry, ..
1582            })) => {
1583                buffers_to_unfold.extend(self.buffers_inside_directory(*worktree_id, entry));
1584                Some(CollapsedEntry::Dir(*worktree_id, entry.id))
1585            }
1586            PanelEntry::Fs(FsEntry::File(FsEntryFile {
1587                worktree_id,
1588                buffer_id,
1589                ..
1590            })) => {
1591                buffers_to_unfold.insert(*buffer_id);
1592                Some(CollapsedEntry::File(*worktree_id, *buffer_id))
1593            }
1594            PanelEntry::Fs(FsEntry::ExternalFile(external_file)) => {
1595                buffers_to_unfold.insert(external_file.buffer_id);
1596                Some(CollapsedEntry::ExternalFile(external_file.buffer_id))
1597            }
1598            PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => {
1599                Some(CollapsedEntry::Excerpt(excerpt.buffer_id, excerpt.id))
1600            }
1601            PanelEntry::Outline(OutlineEntry::Outline(outline)) => Some(CollapsedEntry::Outline(
1602                outline.buffer_id,
1603                outline.excerpt_id,
1604                outline.outline.range.clone(),
1605            )),
1606            PanelEntry::Search(_) => return,
1607        };
1608        let Some(collapsed_entry) = entry_to_expand else {
1609            return;
1610        };
1611        let expanded = self.collapsed_entries.remove(&collapsed_entry);
1612        if expanded {
1613            if let CollapsedEntry::Dir(worktree_id, dir_entry_id) = collapsed_entry {
1614                let task = self.project.update(cx, |project, cx| {
1615                    project.expand_entry(worktree_id, dir_entry_id, cx)
1616                });
1617                if let Some(task) = task {
1618                    task.detach_and_log_err(cx);
1619                }
1620            };
1621
1622            active_editor.update(cx, |editor, cx| {
1623                buffers_to_unfold.retain(|buffer_id| editor.is_buffer_folded(*buffer_id, cx));
1624            });
1625            self.select_entry(selected_entry, true, window, cx);
1626            if buffers_to_unfold.is_empty() {
1627                self.update_cached_entries(None, window, cx);
1628            } else {
1629                self.toggle_buffers_fold(buffers_to_unfold, false, window, cx)
1630                    .detach();
1631            }
1632        } else {
1633            self.select_next(&SelectNext, window, cx)
1634        }
1635    }
1636
1637    fn collapse_selected_entry(
1638        &mut self,
1639        _: &CollapseSelectedEntry,
1640        window: &mut Window,
1641        cx: &mut Context<Self>,
1642    ) {
1643        let Some(active_editor) = self.active_editor() else {
1644            return;
1645        };
1646        let Some(selected_entry) = self.selected_entry().cloned() else {
1647            return;
1648        };
1649
1650        let mut buffers_to_fold = HashSet::default();
1651        let collapsed = match &selected_entry {
1652            PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory {
1653                worktree_id, entry, ..
1654            })) => {
1655                if self
1656                    .collapsed_entries
1657                    .insert(CollapsedEntry::Dir(*worktree_id, entry.id))
1658                {
1659                    buffers_to_fold.extend(self.buffers_inside_directory(*worktree_id, entry));
1660                    true
1661                } else {
1662                    false
1663                }
1664            }
1665            PanelEntry::Fs(FsEntry::File(FsEntryFile {
1666                worktree_id,
1667                buffer_id,
1668                ..
1669            })) => {
1670                if self
1671                    .collapsed_entries
1672                    .insert(CollapsedEntry::File(*worktree_id, *buffer_id))
1673                {
1674                    buffers_to_fold.insert(*buffer_id);
1675                    true
1676                } else {
1677                    false
1678                }
1679            }
1680            PanelEntry::Fs(FsEntry::ExternalFile(external_file)) => {
1681                if self
1682                    .collapsed_entries
1683                    .insert(CollapsedEntry::ExternalFile(external_file.buffer_id))
1684                {
1685                    buffers_to_fold.insert(external_file.buffer_id);
1686                    true
1687                } else {
1688                    false
1689                }
1690            }
1691            PanelEntry::FoldedDirs(folded_dirs) => {
1692                let mut folded = false;
1693                if let Some(dir_entry) = folded_dirs.entries.last()
1694                    && self
1695                        .collapsed_entries
1696                        .insert(CollapsedEntry::Dir(folded_dirs.worktree_id, dir_entry.id))
1697                {
1698                    folded = true;
1699                    buffers_to_fold
1700                        .extend(self.buffers_inside_directory(folded_dirs.worktree_id, dir_entry));
1701                }
1702                folded
1703            }
1704            PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => self
1705                .collapsed_entries
1706                .insert(CollapsedEntry::Excerpt(excerpt.buffer_id, excerpt.id)),
1707            PanelEntry::Outline(OutlineEntry::Outline(outline)) => {
1708                self.collapsed_entries.insert(CollapsedEntry::Outline(
1709                    outline.buffer_id,
1710                    outline.excerpt_id,
1711                    outline.outline.range.clone(),
1712                ))
1713            }
1714            PanelEntry::Search(_) => false,
1715        };
1716
1717        if collapsed {
1718            active_editor.update(cx, |editor, cx| {
1719                buffers_to_fold.retain(|buffer_id| !editor.is_buffer_folded(*buffer_id, cx));
1720            });
1721            self.select_entry(selected_entry, true, window, cx);
1722            if buffers_to_fold.is_empty() {
1723                self.update_cached_entries(None, window, cx);
1724            } else {
1725                self.toggle_buffers_fold(buffers_to_fold, true, window, cx)
1726                    .detach();
1727            }
1728        } else {
1729            self.select_parent(&SelectParent, window, cx);
1730        }
1731    }
1732
1733    pub fn expand_all_entries(
1734        &mut self,
1735        _: &ExpandAllEntries,
1736        window: &mut Window,
1737        cx: &mut Context<Self>,
1738    ) {
1739        let Some(active_editor) = self.active_editor() else {
1740            return;
1741        };
1742
1743        let mut to_uncollapse: HashSet<CollapsedEntry> = HashSet::default();
1744        let mut buffers_to_unfold: HashSet<BufferId> = HashSet::default();
1745
1746        for fs_entry in &self.fs_entries {
1747            match fs_entry {
1748                FsEntry::File(FsEntryFile {
1749                    worktree_id,
1750                    buffer_id,
1751                    ..
1752                }) => {
1753                    to_uncollapse.insert(CollapsedEntry::File(*worktree_id, *buffer_id));
1754                    buffers_to_unfold.insert(*buffer_id);
1755                }
1756                FsEntry::ExternalFile(FsEntryExternalFile { buffer_id, .. }) => {
1757                    to_uncollapse.insert(CollapsedEntry::ExternalFile(*buffer_id));
1758                    buffers_to_unfold.insert(*buffer_id);
1759                }
1760                FsEntry::Directory(FsEntryDirectory {
1761                    worktree_id, entry, ..
1762                }) => {
1763                    to_uncollapse.insert(CollapsedEntry::Dir(*worktree_id, entry.id));
1764                }
1765            }
1766        }
1767
1768        for (&buffer_id, excerpts) in &self.excerpts {
1769            for (&excerpt_id, excerpt) in excerpts {
1770                match &excerpt.outlines {
1771                    ExcerptOutlines::Outlines(outlines) => {
1772                        for outline in outlines {
1773                            to_uncollapse.insert(CollapsedEntry::Outline(
1774                                buffer_id,
1775                                excerpt_id,
1776                                outline.range.clone(),
1777                            ));
1778                        }
1779                    }
1780                    ExcerptOutlines::Invalidated(outlines) => {
1781                        for outline in outlines {
1782                            to_uncollapse.insert(CollapsedEntry::Outline(
1783                                buffer_id,
1784                                excerpt_id,
1785                                outline.range.clone(),
1786                            ));
1787                        }
1788                    }
1789                    ExcerptOutlines::NotFetched => {}
1790                }
1791                to_uncollapse.insert(CollapsedEntry::Excerpt(buffer_id, excerpt_id));
1792            }
1793        }
1794
1795        for cached in &self.cached_entries {
1796            if let PanelEntry::FoldedDirs(FoldedDirsEntry {
1797                worktree_id,
1798                entries,
1799                ..
1800            }) = &cached.entry
1801            {
1802                if let Some(last) = entries.last() {
1803                    to_uncollapse.insert(CollapsedEntry::Dir(*worktree_id, last.id));
1804                }
1805            }
1806        }
1807
1808        self.collapsed_entries
1809            .retain(|entry| !to_uncollapse.contains(entry));
1810
1811        active_editor.update(cx, |editor, cx| {
1812            buffers_to_unfold.retain(|buffer_id| editor.is_buffer_folded(*buffer_id, cx));
1813        });
1814
1815        if buffers_to_unfold.is_empty() {
1816            self.update_cached_entries(None, window, cx);
1817        } else {
1818            self.toggle_buffers_fold(buffers_to_unfold, false, window, cx)
1819                .detach();
1820        }
1821    }
1822
1823    pub fn collapse_all_entries(
1824        &mut self,
1825        _: &CollapseAllEntries,
1826        window: &mut Window,
1827        cx: &mut Context<Self>,
1828    ) {
1829        let Some(active_editor) = self.active_editor() else {
1830            return;
1831        };
1832        let mut buffers_to_fold = HashSet::default();
1833        self.collapsed_entries
1834            .extend(self.cached_entries.iter().filter_map(
1835                |cached_entry| match &cached_entry.entry {
1836                    PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory {
1837                        worktree_id,
1838                        entry,
1839                        ..
1840                    })) => Some(CollapsedEntry::Dir(*worktree_id, entry.id)),
1841                    PanelEntry::Fs(FsEntry::File(FsEntryFile {
1842                        worktree_id,
1843                        buffer_id,
1844                        ..
1845                    })) => {
1846                        buffers_to_fold.insert(*buffer_id);
1847                        Some(CollapsedEntry::File(*worktree_id, *buffer_id))
1848                    }
1849                    PanelEntry::Fs(FsEntry::ExternalFile(external_file)) => {
1850                        buffers_to_fold.insert(external_file.buffer_id);
1851                        Some(CollapsedEntry::ExternalFile(external_file.buffer_id))
1852                    }
1853                    PanelEntry::FoldedDirs(FoldedDirsEntry {
1854                        worktree_id,
1855                        entries,
1856                        ..
1857                    }) => Some(CollapsedEntry::Dir(*worktree_id, entries.last()?.id)),
1858                    PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => {
1859                        Some(CollapsedEntry::Excerpt(excerpt.buffer_id, excerpt.id))
1860                    }
1861                    PanelEntry::Outline(OutlineEntry::Outline(outline)) => {
1862                        Some(CollapsedEntry::Outline(
1863                            outline.buffer_id,
1864                            outline.excerpt_id,
1865                            outline.outline.range.clone(),
1866                        ))
1867                    }
1868                    PanelEntry::Search(_) => None,
1869                },
1870            ));
1871
1872        active_editor.update(cx, |editor, cx| {
1873            buffers_to_fold.retain(|buffer_id| !editor.is_buffer_folded(*buffer_id, cx));
1874        });
1875        if buffers_to_fold.is_empty() {
1876            self.update_cached_entries(None, window, cx);
1877        } else {
1878            self.toggle_buffers_fold(buffers_to_fold, true, window, cx)
1879                .detach();
1880        }
1881    }
1882
1883    fn toggle_expanded(&mut self, entry: &PanelEntry, window: &mut Window, cx: &mut Context<Self>) {
1884        let Some(active_editor) = self.active_editor() else {
1885            return;
1886        };
1887        let mut fold = false;
1888        let mut buffers_to_toggle = HashSet::default();
1889        match entry {
1890            PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory {
1891                worktree_id,
1892                entry: dir_entry,
1893                ..
1894            })) => {
1895                let entry_id = dir_entry.id;
1896                let collapsed_entry = CollapsedEntry::Dir(*worktree_id, entry_id);
1897                buffers_to_toggle.extend(self.buffers_inside_directory(*worktree_id, dir_entry));
1898                if self.collapsed_entries.remove(&collapsed_entry) {
1899                    self.project
1900                        .update(cx, |project, cx| {
1901                            project.expand_entry(*worktree_id, entry_id, cx)
1902                        })
1903                        .unwrap_or_else(|| Task::ready(Ok(())))
1904                        .detach_and_log_err(cx);
1905                } else {
1906                    self.collapsed_entries.insert(collapsed_entry);
1907                    fold = true;
1908                }
1909            }
1910            PanelEntry::Fs(FsEntry::File(FsEntryFile {
1911                worktree_id,
1912                buffer_id,
1913                ..
1914            })) => {
1915                let collapsed_entry = CollapsedEntry::File(*worktree_id, *buffer_id);
1916                buffers_to_toggle.insert(*buffer_id);
1917                if !self.collapsed_entries.remove(&collapsed_entry) {
1918                    self.collapsed_entries.insert(collapsed_entry);
1919                    fold = true;
1920                }
1921            }
1922            PanelEntry::Fs(FsEntry::ExternalFile(external_file)) => {
1923                let collapsed_entry = CollapsedEntry::ExternalFile(external_file.buffer_id);
1924                buffers_to_toggle.insert(external_file.buffer_id);
1925                if !self.collapsed_entries.remove(&collapsed_entry) {
1926                    self.collapsed_entries.insert(collapsed_entry);
1927                    fold = true;
1928                }
1929            }
1930            PanelEntry::FoldedDirs(FoldedDirsEntry {
1931                worktree_id,
1932                entries: dir_entries,
1933                ..
1934            }) => {
1935                if let Some(dir_entry) = dir_entries.first() {
1936                    let entry_id = dir_entry.id;
1937                    let collapsed_entry = CollapsedEntry::Dir(*worktree_id, entry_id);
1938                    buffers_to_toggle
1939                        .extend(self.buffers_inside_directory(*worktree_id, dir_entry));
1940                    if self.collapsed_entries.remove(&collapsed_entry) {
1941                        self.project
1942                            .update(cx, |project, cx| {
1943                                project.expand_entry(*worktree_id, entry_id, cx)
1944                            })
1945                            .unwrap_or_else(|| Task::ready(Ok(())))
1946                            .detach_and_log_err(cx);
1947                    } else {
1948                        self.collapsed_entries.insert(collapsed_entry);
1949                        fold = true;
1950                    }
1951                }
1952            }
1953            PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => {
1954                let collapsed_entry = CollapsedEntry::Excerpt(excerpt.buffer_id, excerpt.id);
1955                if !self.collapsed_entries.remove(&collapsed_entry) {
1956                    self.collapsed_entries.insert(collapsed_entry);
1957                }
1958            }
1959            PanelEntry::Outline(OutlineEntry::Outline(outline)) => {
1960                let collapsed_entry = CollapsedEntry::Outline(
1961                    outline.buffer_id,
1962                    outline.excerpt_id,
1963                    outline.outline.range.clone(),
1964                );
1965                if !self.collapsed_entries.remove(&collapsed_entry) {
1966                    self.collapsed_entries.insert(collapsed_entry);
1967                }
1968            }
1969            _ => {}
1970        }
1971
1972        active_editor.update(cx, |editor, cx| {
1973            buffers_to_toggle.retain(|buffer_id| {
1974                let folded = editor.is_buffer_folded(*buffer_id, cx);
1975                if fold { !folded } else { folded }
1976            });
1977        });
1978
1979        self.select_entry(entry.clone(), true, window, cx);
1980        if buffers_to_toggle.is_empty() {
1981            self.update_cached_entries(None, window, cx);
1982        } else {
1983            self.toggle_buffers_fold(buffers_to_toggle, fold, window, cx)
1984                .detach();
1985        }
1986    }
1987
1988    fn toggle_buffers_fold(
1989        &self,
1990        buffers: HashSet<BufferId>,
1991        fold: bool,
1992        window: &mut Window,
1993        cx: &mut Context<Self>,
1994    ) -> Task<()> {
1995        let Some(active_editor) = self.active_editor() else {
1996            return Task::ready(());
1997        };
1998        cx.spawn_in(window, async move |outline_panel, cx| {
1999            outline_panel
2000                .update_in(cx, |outline_panel, window, cx| {
2001                    active_editor.update(cx, |editor, cx| {
2002                        for buffer_id in buffers {
2003                            outline_panel
2004                                .preserve_selection_on_buffer_fold_toggles
2005                                .insert(buffer_id);
2006                            if fold {
2007                                editor.fold_buffer(buffer_id, cx);
2008                            } else {
2009                                editor.unfold_buffer(buffer_id, cx);
2010                            }
2011                        }
2012                    });
2013                    if let Some(selection) = outline_panel.selected_entry().cloned() {
2014                        outline_panel.scroll_editor_to_entry(&selection, false, false, window, cx);
2015                    }
2016                })
2017                .ok();
2018        })
2019    }
2020
2021    fn copy_path(
2022        &mut self,
2023        _: &zed_actions::workspace::CopyPath,
2024        _: &mut Window,
2025        cx: &mut Context<Self>,
2026    ) {
2027        if let Some(clipboard_text) = self
2028            .selected_entry()
2029            .and_then(|entry| self.abs_path(entry, cx))
2030            .map(|p| p.to_string_lossy().into_owned())
2031        {
2032            cx.write_to_clipboard(ClipboardItem::new_string(clipboard_text));
2033        }
2034    }
2035
2036    fn copy_relative_path(
2037        &mut self,
2038        _: &zed_actions::workspace::CopyRelativePath,
2039        _: &mut Window,
2040        cx: &mut Context<Self>,
2041    ) {
2042        let path_style = self.project.read(cx).path_style(cx);
2043        if let Some(clipboard_text) = self
2044            .selected_entry()
2045            .and_then(|entry| match entry {
2046                PanelEntry::Fs(entry) => self.relative_path(entry, cx),
2047                PanelEntry::FoldedDirs(folded_dirs) => {
2048                    folded_dirs.entries.last().map(|entry| entry.path.clone())
2049                }
2050                PanelEntry::Search(_) | PanelEntry::Outline(..) => None,
2051            })
2052            .map(|p| p.display(path_style).to_string())
2053        {
2054            cx.write_to_clipboard(ClipboardItem::new_string(clipboard_text));
2055        }
2056    }
2057
2058    fn reveal_in_finder(
2059        &mut self,
2060        _: &RevealInFileManager,
2061        _: &mut Window,
2062        cx: &mut Context<Self>,
2063    ) {
2064        if let Some(abs_path) = self
2065            .selected_entry()
2066            .and_then(|entry| self.abs_path(entry, cx))
2067        {
2068            self.project
2069                .update(cx, |project, cx| project.reveal_path(&abs_path, cx));
2070        }
2071    }
2072
2073    fn open_in_terminal(
2074        &mut self,
2075        _: &OpenInTerminal,
2076        window: &mut Window,
2077        cx: &mut Context<Self>,
2078    ) {
2079        let selected_entry = self.selected_entry();
2080        let abs_path = selected_entry.and_then(|entry| self.abs_path(entry, cx));
2081        let working_directory = if let (
2082            Some(abs_path),
2083            Some(PanelEntry::Fs(FsEntry::File(..) | FsEntry::ExternalFile(..))),
2084        ) = (&abs_path, selected_entry)
2085        {
2086            abs_path.parent().map(|p| p.to_owned())
2087        } else {
2088            abs_path
2089        };
2090
2091        if let Some(working_directory) = working_directory {
2092            window.dispatch_action(
2093                workspace::OpenTerminal {
2094                    working_directory,
2095                    local: false,
2096                }
2097                .boxed_clone(),
2098                cx,
2099            )
2100        }
2101    }
2102
2103    fn reveal_entry_for_selection(
2104        &mut self,
2105        editor: Entity<Editor>,
2106        window: &mut Window,
2107        cx: &mut Context<Self>,
2108    ) {
2109        if !self.active
2110            || !OutlinePanelSettings::get_global(cx).auto_reveal_entries
2111            || self.focus_handle.contains_focused(window, cx)
2112        {
2113            return;
2114        }
2115        let project = self.project.clone();
2116        self.reveal_selection_task = cx.spawn_in(window, async move |outline_panel, cx| {
2117            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
2118            let entry_with_selection =
2119                outline_panel.update_in(cx, |outline_panel, window, cx| {
2120                    outline_panel.location_for_editor_selection(&editor, window, cx)
2121                })?;
2122            let Some(entry_with_selection) = entry_with_selection else {
2123                outline_panel.update(cx, |outline_panel, cx| {
2124                    outline_panel.selected_entry = SelectedEntry::None;
2125                    cx.notify();
2126                })?;
2127                return Ok(());
2128            };
2129            let related_buffer_entry = match &entry_with_selection {
2130                PanelEntry::Fs(FsEntry::File(FsEntryFile {
2131                    worktree_id,
2132                    buffer_id,
2133                    ..
2134                })) => project.update(cx, |project, cx| {
2135                    let entry_id = project
2136                        .buffer_for_id(*buffer_id, cx)
2137                        .and_then(|buffer| buffer.read(cx).entry_id(cx));
2138                    project
2139                        .worktree_for_id(*worktree_id, cx)
2140                        .zip(entry_id)
2141                        .and_then(|(worktree, entry_id)| {
2142                            let entry = worktree.read(cx).entry_for_id(entry_id)?.clone();
2143                            Some((worktree, entry))
2144                        })
2145                }),
2146                PanelEntry::Outline(outline_entry) => {
2147                    let (buffer_id, excerpt_id) = outline_entry.ids();
2148                    outline_panel.update(cx, |outline_panel, cx| {
2149                        outline_panel
2150                            .collapsed_entries
2151                            .remove(&CollapsedEntry::ExternalFile(buffer_id));
2152                        outline_panel
2153                            .collapsed_entries
2154                            .remove(&CollapsedEntry::Excerpt(buffer_id, excerpt_id));
2155                        let project = outline_panel.project.read(cx);
2156                        let entry_id = project
2157                            .buffer_for_id(buffer_id, cx)
2158                            .and_then(|buffer| buffer.read(cx).entry_id(cx));
2159
2160                        entry_id.and_then(|entry_id| {
2161                            project
2162                                .worktree_for_entry(entry_id, cx)
2163                                .and_then(|worktree| {
2164                                    let worktree_id = worktree.read(cx).id();
2165                                    outline_panel
2166                                        .collapsed_entries
2167                                        .remove(&CollapsedEntry::File(worktree_id, buffer_id));
2168                                    let entry = worktree.read(cx).entry_for_id(entry_id)?.clone();
2169                                    Some((worktree, entry))
2170                                })
2171                        })
2172                    })?
2173                }
2174                PanelEntry::Fs(FsEntry::ExternalFile(..)) => None,
2175                PanelEntry::Search(SearchEntry { match_range, .. }) => match_range
2176                    .start
2177                    .text_anchor
2178                    .buffer_id
2179                    .or(match_range.end.text_anchor.buffer_id)
2180                    .map(|buffer_id| {
2181                        outline_panel.update(cx, |outline_panel, cx| {
2182                            outline_panel
2183                                .collapsed_entries
2184                                .remove(&CollapsedEntry::ExternalFile(buffer_id));
2185                            let project = project.read(cx);
2186                            let entry_id = project
2187                                .buffer_for_id(buffer_id, cx)
2188                                .and_then(|buffer| buffer.read(cx).entry_id(cx));
2189
2190                            entry_id.and_then(|entry_id| {
2191                                project
2192                                    .worktree_for_entry(entry_id, cx)
2193                                    .and_then(|worktree| {
2194                                        let worktree_id = worktree.read(cx).id();
2195                                        outline_panel
2196                                            .collapsed_entries
2197                                            .remove(&CollapsedEntry::File(worktree_id, buffer_id));
2198                                        let entry =
2199                                            worktree.read(cx).entry_for_id(entry_id)?.clone();
2200                                        Some((worktree, entry))
2201                                    })
2202                            })
2203                        })
2204                    })
2205                    .transpose()?
2206                    .flatten(),
2207                _ => return anyhow::Ok(()),
2208            };
2209            if let Some((worktree, buffer_entry)) = related_buffer_entry {
2210                outline_panel.update(cx, |outline_panel, cx| {
2211                    let worktree_id = worktree.read(cx).id();
2212                    let mut dirs_to_expand = Vec::new();
2213                    {
2214                        let mut traversal = worktree.read(cx).traverse_from_path(
2215                            true,
2216                            true,
2217                            true,
2218                            buffer_entry.path.as_ref(),
2219                        );
2220                        let mut current_entry = buffer_entry;
2221                        loop {
2222                            if current_entry.is_dir()
2223                                && outline_panel
2224                                    .collapsed_entries
2225                                    .remove(&CollapsedEntry::Dir(worktree_id, current_entry.id))
2226                            {
2227                                dirs_to_expand.push(current_entry.id);
2228                            }
2229
2230                            if traversal.back_to_parent()
2231                                && let Some(parent_entry) = traversal.entry()
2232                            {
2233                                current_entry = parent_entry.clone();
2234                                continue;
2235                            }
2236                            break;
2237                        }
2238                    }
2239                    for dir_to_expand in dirs_to_expand {
2240                        project
2241                            .update(cx, |project, cx| {
2242                                project.expand_entry(worktree_id, dir_to_expand, cx)
2243                            })
2244                            .unwrap_or_else(|| Task::ready(Ok(())))
2245                            .detach_and_log_err(cx)
2246                    }
2247                })?
2248            }
2249
2250            outline_panel.update_in(cx, |outline_panel, window, cx| {
2251                outline_panel.select_entry(entry_with_selection, false, window, cx);
2252                outline_panel.update_cached_entries(None, window, cx);
2253            })?;
2254
2255            anyhow::Ok(())
2256        });
2257    }
2258
2259    fn render_excerpt(
2260        &self,
2261        excerpt: &OutlineEntryExcerpt,
2262        depth: usize,
2263        window: &mut Window,
2264        cx: &mut Context<OutlinePanel>,
2265    ) -> Option<Stateful<Div>> {
2266        let item_id = ElementId::from(excerpt.id.to_proto() as usize);
2267        let is_active = match self.selected_entry() {
2268            Some(PanelEntry::Outline(OutlineEntry::Excerpt(selected_excerpt))) => {
2269                selected_excerpt.buffer_id == excerpt.buffer_id && selected_excerpt.id == excerpt.id
2270            }
2271            _ => false,
2272        };
2273        let has_outlines = self
2274            .excerpts
2275            .get(&excerpt.buffer_id)
2276            .and_then(|excerpts| match &excerpts.get(&excerpt.id)?.outlines {
2277                ExcerptOutlines::Outlines(outlines) => Some(outlines),
2278                ExcerptOutlines::Invalidated(outlines) => Some(outlines),
2279                ExcerptOutlines::NotFetched => None,
2280            })
2281            .is_some_and(|outlines| !outlines.is_empty());
2282        let is_expanded = !self
2283            .collapsed_entries
2284            .contains(&CollapsedEntry::Excerpt(excerpt.buffer_id, excerpt.id));
2285        let color = entry_label_color(is_active);
2286        let icon = if has_outlines {
2287            FileIcons::get_chevron_icon(is_expanded, cx)
2288                .map(|icon_path| Icon::from_path(icon_path).color(color).into_any_element())
2289        } else {
2290            None
2291        }
2292        .unwrap_or_else(empty_icon);
2293
2294        let label = self.excerpt_label(excerpt.buffer_id, &excerpt.range, cx)?;
2295        let label_element = Label::new(label)
2296            .single_line()
2297            .color(color)
2298            .into_any_element();
2299
2300        Some(self.entry_element(
2301            PanelEntry::Outline(OutlineEntry::Excerpt(excerpt.clone())),
2302            item_id,
2303            depth,
2304            icon,
2305            is_active,
2306            label_element,
2307            window,
2308            cx,
2309        ))
2310    }
2311
2312    fn excerpt_label(
2313        &self,
2314        buffer_id: BufferId,
2315        range: &ExcerptRange<language::Anchor>,
2316        cx: &App,
2317    ) -> Option<String> {
2318        let buffer_snapshot = self.buffer_snapshot_for_id(buffer_id, cx)?;
2319        let excerpt_range = range.context.to_point(&buffer_snapshot);
2320        Some(format!(
2321            "Lines {}- {}",
2322            excerpt_range.start.row + 1,
2323            excerpt_range.end.row + 1,
2324        ))
2325    }
2326
2327    fn render_outline(
2328        &self,
2329        outline: &OutlineEntryOutline,
2330        depth: usize,
2331        string_match: Option<&StringMatch>,
2332        window: &mut Window,
2333        cx: &mut Context<Self>,
2334    ) -> Stateful<Div> {
2335        let item_id = ElementId::from(SharedString::from(format!(
2336            "{:?}|{:?}{:?}|{:?}",
2337            outline.buffer_id, outline.excerpt_id, outline.outline.range, &outline.outline.text,
2338        )));
2339
2340        let label_element = outline::render_item(
2341            &outline.outline,
2342            string_match
2343                .map(|string_match| string_match.ranges().collect::<Vec<_>>())
2344                .unwrap_or_default(),
2345            cx,
2346        )
2347        .into_any_element();
2348
2349        let is_active = match self.selected_entry() {
2350            Some(PanelEntry::Outline(OutlineEntry::Outline(selected))) => {
2351                outline == selected && outline.outline == selected.outline
2352            }
2353            _ => false,
2354        };
2355
2356        let has_children = self
2357            .outline_children_cache
2358            .get(&outline.buffer_id)
2359            .and_then(|children_map| {
2360                let key = (outline.outline.range.clone(), outline.outline.depth);
2361                children_map.get(&key)
2362            })
2363            .copied()
2364            .unwrap_or(false);
2365        let is_expanded = !self.collapsed_entries.contains(&CollapsedEntry::Outline(
2366            outline.buffer_id,
2367            outline.excerpt_id,
2368            outline.outline.range.clone(),
2369        ));
2370
2371        let icon = if has_children {
2372            FileIcons::get_chevron_icon(is_expanded, cx)
2373                .map(|icon_path| {
2374                    Icon::from_path(icon_path)
2375                        .color(entry_label_color(is_active))
2376                        .into_any_element()
2377                })
2378                .unwrap_or_else(empty_icon)
2379        } else {
2380            empty_icon()
2381        };
2382
2383        self.entry_element(
2384            PanelEntry::Outline(OutlineEntry::Outline(outline.clone())),
2385            item_id,
2386            depth,
2387            icon,
2388            is_active,
2389            label_element,
2390            window,
2391            cx,
2392        )
2393    }
2394
2395    fn render_entry(
2396        &self,
2397        rendered_entry: &FsEntry,
2398        depth: usize,
2399        string_match: Option<&StringMatch>,
2400        window: &mut Window,
2401        cx: &mut Context<Self>,
2402    ) -> Stateful<Div> {
2403        let settings = OutlinePanelSettings::get_global(cx);
2404        let is_active = match self.selected_entry() {
2405            Some(PanelEntry::Fs(selected_entry)) => selected_entry == rendered_entry,
2406            _ => false,
2407        };
2408        let (item_id, label_element, icon) = match rendered_entry {
2409            FsEntry::File(FsEntryFile {
2410                worktree_id, entry, ..
2411            }) => {
2412                let name = self.entry_name(worktree_id, entry, cx);
2413                let color =
2414                    entry_git_aware_label_color(entry.git_summary, entry.is_ignored, is_active);
2415                let icon = if settings.file_icons {
2416                    FileIcons::get_icon(entry.path.as_std_path(), cx)
2417                        .map(|icon_path| Icon::from_path(icon_path).color(color).into_any_element())
2418                } else {
2419                    None
2420                };
2421                (
2422                    ElementId::from(entry.id.to_proto() as usize),
2423                    HighlightedLabel::new(
2424                        name,
2425                        string_match
2426                            .map(|string_match| string_match.positions.clone())
2427                            .unwrap_or_default(),
2428                    )
2429                    .color(color)
2430                    .into_any_element(),
2431                    icon.unwrap_or_else(empty_icon),
2432                )
2433            }
2434            FsEntry::Directory(directory) => {
2435                let name = self.entry_name(&directory.worktree_id, &directory.entry, cx);
2436
2437                let is_expanded = !self.collapsed_entries.contains(&CollapsedEntry::Dir(
2438                    directory.worktree_id,
2439                    directory.entry.id,
2440                ));
2441                let color = entry_git_aware_label_color(
2442                    directory.entry.git_summary,
2443                    directory.entry.is_ignored,
2444                    is_active,
2445                );
2446                let icon = if settings.folder_icons {
2447                    FileIcons::get_folder_icon(is_expanded, directory.entry.path.as_std_path(), cx)
2448                } else {
2449                    FileIcons::get_chevron_icon(is_expanded, cx)
2450                }
2451                .map(Icon::from_path)
2452                .map(|icon| icon.color(color).into_any_element());
2453                (
2454                    ElementId::from(directory.entry.id.to_proto() as usize),
2455                    HighlightedLabel::new(
2456                        name,
2457                        string_match
2458                            .map(|string_match| string_match.positions.clone())
2459                            .unwrap_or_default(),
2460                    )
2461                    .color(color)
2462                    .into_any_element(),
2463                    icon.unwrap_or_else(empty_icon),
2464                )
2465            }
2466            FsEntry::ExternalFile(external_file) => {
2467                let color = entry_label_color(is_active);
2468                let (icon, name) = match self.buffer_snapshot_for_id(external_file.buffer_id, cx) {
2469                    Some(buffer_snapshot) => match buffer_snapshot.file() {
2470                        Some(file) => {
2471                            let path = file.path();
2472                            let icon = if settings.file_icons {
2473                                FileIcons::get_icon(path.as_std_path(), cx)
2474                            } else {
2475                                None
2476                            }
2477                            .map(Icon::from_path)
2478                            .map(|icon| icon.color(color).into_any_element());
2479                            (icon, file_name(path.as_std_path()))
2480                        }
2481                        None => (None, "Untitled".to_string()),
2482                    },
2483                    None => (None, "Unknown buffer".to_string()),
2484                };
2485                (
2486                    ElementId::from(external_file.buffer_id.to_proto() as usize),
2487                    HighlightedLabel::new(
2488                        name,
2489                        string_match
2490                            .map(|string_match| string_match.positions.clone())
2491                            .unwrap_or_default(),
2492                    )
2493                    .color(color)
2494                    .into_any_element(),
2495                    icon.unwrap_or_else(empty_icon),
2496                )
2497            }
2498        };
2499
2500        self.entry_element(
2501            PanelEntry::Fs(rendered_entry.clone()),
2502            item_id,
2503            depth,
2504            icon,
2505            is_active,
2506            label_element,
2507            window,
2508            cx,
2509        )
2510    }
2511
2512    fn render_folded_dirs(
2513        &self,
2514        folded_dir: &FoldedDirsEntry,
2515        depth: usize,
2516        string_match: Option<&StringMatch>,
2517        window: &mut Window,
2518        cx: &mut Context<OutlinePanel>,
2519    ) -> Stateful<Div> {
2520        let settings = OutlinePanelSettings::get_global(cx);
2521        let is_active = match self.selected_entry() {
2522            Some(PanelEntry::FoldedDirs(selected_dirs)) => {
2523                selected_dirs.worktree_id == folded_dir.worktree_id
2524                    && selected_dirs.entries == folded_dir.entries
2525            }
2526            _ => false,
2527        };
2528        let (item_id, label_element, icon) = {
2529            let name = self.dir_names_string(&folded_dir.entries, folded_dir.worktree_id, cx);
2530
2531            let is_expanded = folded_dir.entries.iter().all(|dir| {
2532                !self
2533                    .collapsed_entries
2534                    .contains(&CollapsedEntry::Dir(folded_dir.worktree_id, dir.id))
2535            });
2536            let is_ignored = folded_dir.entries.iter().any(|entry| entry.is_ignored);
2537            let git_status = folded_dir
2538                .entries
2539                .first()
2540                .map(|entry| entry.git_summary)
2541                .unwrap_or_default();
2542            let color = entry_git_aware_label_color(git_status, is_ignored, is_active);
2543            let icon = if settings.folder_icons {
2544                FileIcons::get_folder_icon(is_expanded, &Path::new(&name), cx)
2545            } else {
2546                FileIcons::get_chevron_icon(is_expanded, cx)
2547            }
2548            .map(Icon::from_path)
2549            .map(|icon| icon.color(color).into_any_element());
2550            (
2551                ElementId::from(
2552                    folded_dir
2553                        .entries
2554                        .last()
2555                        .map(|entry| entry.id.to_proto())
2556                        .unwrap_or_else(|| folded_dir.worktree_id.to_proto())
2557                        as usize,
2558                ),
2559                HighlightedLabel::new(
2560                    name,
2561                    string_match
2562                        .map(|string_match| string_match.positions.clone())
2563                        .unwrap_or_default(),
2564                )
2565                .color(color)
2566                .into_any_element(),
2567                icon.unwrap_or_else(empty_icon),
2568            )
2569        };
2570
2571        self.entry_element(
2572            PanelEntry::FoldedDirs(folded_dir.clone()),
2573            item_id,
2574            depth,
2575            icon,
2576            is_active,
2577            label_element,
2578            window,
2579            cx,
2580        )
2581    }
2582
2583    fn render_search_match(
2584        &mut self,
2585        multi_buffer_snapshot: Option<&MultiBufferSnapshot>,
2586        match_range: &Range<editor::Anchor>,
2587        render_data: &Arc<OnceLock<SearchData>>,
2588        kind: SearchKind,
2589        depth: usize,
2590        string_match: Option<&StringMatch>,
2591        window: &mut Window,
2592        cx: &mut Context<Self>,
2593    ) -> Option<Stateful<Div>> {
2594        let search_data = match render_data.get() {
2595            Some(search_data) => search_data,
2596            None => {
2597                if let ItemsDisplayMode::Search(search_state) = &mut self.mode
2598                    && let Some(multi_buffer_snapshot) = multi_buffer_snapshot
2599                {
2600                    search_state
2601                        .highlight_search_match_tx
2602                        .try_send(HighlightArguments {
2603                            multi_buffer_snapshot: multi_buffer_snapshot.clone(),
2604                            match_range: match_range.clone(),
2605                            search_data: Arc::clone(render_data),
2606                        })
2607                        .ok();
2608                }
2609                return None;
2610            }
2611        };
2612        let search_matches = string_match
2613            .iter()
2614            .flat_map(|string_match| string_match.ranges())
2615            .collect::<Vec<_>>();
2616        let match_ranges = if search_matches.is_empty() {
2617            &search_data.search_match_indices
2618        } else {
2619            &search_matches
2620        };
2621        let outline_item = OutlineItem {
2622            depth,
2623            annotation_range: None,
2624            range: search_data.context_range.clone(),
2625            text: search_data.context_text.clone(),
2626            source_range_for_text: search_data.context_range.clone(),
2627            highlight_ranges: search_data
2628                .highlights_data
2629                .get()
2630                .cloned()
2631                .unwrap_or_default(),
2632            name_ranges: search_data.search_match_indices.clone(),
2633            body_range: Some(search_data.context_range.clone()),
2634        };
2635        let label_element = outline::render_item(&outline_item, match_ranges.iter().cloned(), cx);
2636        let truncated_contents_label = || Label::new(TRUNCATED_CONTEXT_MARK);
2637        let entire_label = h_flex()
2638            .justify_center()
2639            .p_0()
2640            .when(search_data.truncated_left, |parent| {
2641                parent.child(truncated_contents_label())
2642            })
2643            .child(label_element)
2644            .when(search_data.truncated_right, |parent| {
2645                parent.child(truncated_contents_label())
2646            })
2647            .into_any_element();
2648
2649        let is_active = match self.selected_entry() {
2650            Some(PanelEntry::Search(SearchEntry {
2651                match_range: selected_match_range,
2652                ..
2653            })) => match_range == selected_match_range,
2654            _ => false,
2655        };
2656        Some(self.entry_element(
2657            PanelEntry::Search(SearchEntry {
2658                kind,
2659                match_range: match_range.clone(),
2660                render_data: render_data.clone(),
2661            }),
2662            ElementId::from(SharedString::from(format!("search-{match_range:?}"))),
2663            depth,
2664            empty_icon(),
2665            is_active,
2666            entire_label,
2667            window,
2668            cx,
2669        ))
2670    }
2671
2672    fn entry_element(
2673        &self,
2674        rendered_entry: PanelEntry,
2675        item_id: ElementId,
2676        depth: usize,
2677        icon_element: AnyElement,
2678        is_active: bool,
2679        label_element: gpui::AnyElement,
2680        window: &mut Window,
2681        cx: &mut Context<OutlinePanel>,
2682    ) -> Stateful<Div> {
2683        let settings = OutlinePanelSettings::get_global(cx);
2684        div()
2685            .text_ui(cx)
2686            .id(item_id.clone())
2687            .on_click({
2688                let clicked_entry = rendered_entry.clone();
2689                cx.listener(move |outline_panel, event: &gpui::ClickEvent, window, cx| {
2690                    if event.is_right_click() || event.first_focus() {
2691                        return;
2692                    }
2693
2694                    let change_focus = event.click_count() > 1;
2695                    outline_panel.toggle_expanded(&clicked_entry, window, cx);
2696
2697                    outline_panel.scroll_editor_to_entry(
2698                        &clicked_entry,
2699                        true,
2700                        change_focus,
2701                        window,
2702                        cx,
2703                    );
2704                })
2705            })
2706            .cursor_pointer()
2707            .child(
2708                ListItem::new(item_id)
2709                    .indent_level(depth)
2710                    .indent_step_size(px(settings.indent_size))
2711                    .toggle_state(is_active)
2712                    .child(
2713                        h_flex()
2714                            .child(h_flex().w(px(16.)).justify_center().child(icon_element))
2715                            .child(h_flex().h_6().child(label_element).ml_1()),
2716                    )
2717                    .on_secondary_mouse_down(cx.listener(
2718                        move |outline_panel, event: &MouseDownEvent, window, cx| {
2719                            // Stop propagation to prevent the catch-all context menu for the project
2720                            // panel from being deployed.
2721                            cx.stop_propagation();
2722                            outline_panel.deploy_context_menu(
2723                                event.position,
2724                                rendered_entry.clone(),
2725                                window,
2726                                cx,
2727                            )
2728                        },
2729                    )),
2730            )
2731            .border_1()
2732            .border_r_2()
2733            .rounded_none()
2734            .hover(|style| {
2735                if is_active {
2736                    style
2737                } else {
2738                    let hover_color = cx.theme().colors().ghost_element_hover;
2739                    style.bg(hover_color).border_color(hover_color)
2740                }
2741            })
2742            .when(
2743                is_active && self.focus_handle.contains_focused(window, cx),
2744                |div| div.border_color(cx.theme().colors().panel_focused_border),
2745            )
2746    }
2747
2748    fn entry_name(&self, worktree_id: &WorktreeId, entry: &Entry, cx: &App) -> String {
2749        match self.project.read(cx).worktree_for_id(*worktree_id, cx) {
2750            Some(worktree) => {
2751                let worktree = worktree.read(cx);
2752                match worktree.snapshot().root_entry() {
2753                    Some(root_entry) => {
2754                        if root_entry.id == entry.id {
2755                            file_name(worktree.abs_path().as_ref())
2756                        } else {
2757                            let path = worktree.absolutize(entry.path.as_ref());
2758                            file_name(&path)
2759                        }
2760                    }
2761                    None => {
2762                        let path = worktree.absolutize(entry.path.as_ref());
2763                        file_name(&path)
2764                    }
2765                }
2766            }
2767            None => file_name(entry.path.as_std_path()),
2768        }
2769    }
2770
2771    fn update_fs_entries(
2772        &mut self,
2773        active_editor: Entity<Editor>,
2774        debounce: Option<Duration>,
2775        window: &mut Window,
2776        cx: &mut Context<Self>,
2777    ) {
2778        if !self.active {
2779            return;
2780        }
2781
2782        let auto_fold_dirs = OutlinePanelSettings::get_global(cx).auto_fold_dirs;
2783        let active_multi_buffer = active_editor.read(cx).buffer().clone();
2784        let new_entries = self.new_entries_for_fs_update.clone();
2785        let repo_snapshots = self.project.update(cx, |project, cx| {
2786            project.git_store().read(cx).repo_snapshots(cx)
2787        });
2788        self.fs_entries_update_task = cx.spawn_in(window, async move |outline_panel, cx| {
2789            if let Some(debounce) = debounce {
2790                cx.background_executor().timer(debounce).await;
2791            }
2792
2793            let mut new_collapsed_entries = HashSet::default();
2794            let mut new_unfolded_dirs = HashMap::default();
2795            let mut root_entries = HashSet::default();
2796            let mut new_excerpts = HashMap::<BufferId, HashMap<ExcerptId, Excerpt>>::default();
2797            let Ok(buffer_excerpts) = outline_panel.update(cx, |outline_panel, cx| {
2798                let git_store = outline_panel.project.read(cx).git_store().clone();
2799                new_collapsed_entries = outline_panel.collapsed_entries.clone();
2800                new_unfolded_dirs = outline_panel.unfolded_dirs.clone();
2801                let multi_buffer_snapshot = active_multi_buffer.read(cx).snapshot(cx);
2802
2803                multi_buffer_snapshot.excerpts().fold(
2804                    HashMap::default(),
2805                    |mut buffer_excerpts, (excerpt_id, buffer_snapshot, excerpt_range)| {
2806                        let buffer_id = buffer_snapshot.remote_id();
2807                        let file = File::from_dyn(buffer_snapshot.file());
2808                        let entry_id = file.and_then(|file| file.project_entry_id());
2809                        let worktree = file.map(|file| file.worktree.read(cx).snapshot());
2810                        let is_new = new_entries.contains(&excerpt_id)
2811                            || !outline_panel.excerpts.contains_key(&buffer_id);
2812                        let is_folded = active_editor.read(cx).is_buffer_folded(buffer_id, cx);
2813                        let status = git_store
2814                            .read(cx)
2815                            .repository_and_path_for_buffer_id(buffer_id, cx)
2816                            .and_then(|(repo, path)| {
2817                                Some(repo.read(cx).status_for_path(&path)?.status)
2818                            });
2819                        buffer_excerpts
2820                            .entry(buffer_id)
2821                            .or_insert_with(|| {
2822                                (is_new, is_folded, Vec::new(), entry_id, worktree, status)
2823                            })
2824                            .2
2825                            .push(excerpt_id);
2826
2827                        let outlines = match outline_panel
2828                            .excerpts
2829                            .get(&buffer_id)
2830                            .and_then(|excerpts| excerpts.get(&excerpt_id))
2831                        {
2832                            Some(old_excerpt) => match &old_excerpt.outlines {
2833                                ExcerptOutlines::Outlines(outlines) => {
2834                                    ExcerptOutlines::Outlines(outlines.clone())
2835                                }
2836                                ExcerptOutlines::Invalidated(_) => ExcerptOutlines::NotFetched,
2837                                ExcerptOutlines::NotFetched => ExcerptOutlines::NotFetched,
2838                            },
2839                            None => ExcerptOutlines::NotFetched,
2840                        };
2841                        new_excerpts.entry(buffer_id).or_default().insert(
2842                            excerpt_id,
2843                            Excerpt {
2844                                range: excerpt_range,
2845                                outlines,
2846                            },
2847                        );
2848                        buffer_excerpts
2849                    },
2850                )
2851            }) else {
2852                return;
2853            };
2854
2855            let Some((
2856                new_collapsed_entries,
2857                new_unfolded_dirs,
2858                new_fs_entries,
2859                new_depth_map,
2860                new_children_count,
2861            )) = cx
2862                .background_spawn(async move {
2863                    let mut processed_external_buffers = HashSet::default();
2864                    let mut new_worktree_entries =
2865                        BTreeMap::<WorktreeId, HashMap<ProjectEntryId, GitEntry>>::default();
2866                    let mut worktree_excerpts = HashMap::<
2867                        WorktreeId,
2868                        HashMap<ProjectEntryId, (BufferId, Vec<ExcerptId>)>,
2869                    >::default();
2870                    let mut external_excerpts = HashMap::default();
2871
2872                    for (buffer_id, (is_new, is_folded, excerpts, entry_id, worktree, status)) in
2873                        buffer_excerpts
2874                    {
2875                        if is_folded {
2876                            match &worktree {
2877                                Some(worktree) => {
2878                                    new_collapsed_entries
2879                                        .insert(CollapsedEntry::File(worktree.id(), buffer_id));
2880                                }
2881                                None => {
2882                                    new_collapsed_entries
2883                                        .insert(CollapsedEntry::ExternalFile(buffer_id));
2884                                }
2885                            }
2886                        } else if is_new {
2887                            match &worktree {
2888                                Some(worktree) => {
2889                                    new_collapsed_entries
2890                                        .remove(&CollapsedEntry::File(worktree.id(), buffer_id));
2891                                }
2892                                None => {
2893                                    new_collapsed_entries
2894                                        .remove(&CollapsedEntry::ExternalFile(buffer_id));
2895                                }
2896                            }
2897                        }
2898
2899                        if let Some(worktree) = worktree {
2900                            let worktree_id = worktree.id();
2901                            let unfolded_dirs = new_unfolded_dirs.entry(worktree_id).or_default();
2902
2903                            match entry_id.and_then(|id| worktree.entry_for_id(id)).cloned() {
2904                                Some(entry) => {
2905                                    let entry = GitEntry {
2906                                        git_summary: status
2907                                            .map(|status| status.summary())
2908                                            .unwrap_or_default(),
2909                                        entry,
2910                                    };
2911                                    let mut traversal = GitTraversal::new(
2912                                        &repo_snapshots,
2913                                        worktree.traverse_from_path(
2914                                            true,
2915                                            true,
2916                                            true,
2917                                            entry.path.as_ref(),
2918                                        ),
2919                                    );
2920
2921                                    let mut entries_to_add = HashMap::default();
2922                                    worktree_excerpts
2923                                        .entry(worktree_id)
2924                                        .or_default()
2925                                        .insert(entry.id, (buffer_id, excerpts));
2926                                    let mut current_entry = entry;
2927                                    loop {
2928                                        if current_entry.is_dir() {
2929                                            let is_root =
2930                                                worktree.root_entry().map(|entry| entry.id)
2931                                                    == Some(current_entry.id);
2932                                            if is_root {
2933                                                root_entries.insert(current_entry.id);
2934                                                if auto_fold_dirs {
2935                                                    unfolded_dirs.insert(current_entry.id);
2936                                                }
2937                                            }
2938                                            if is_new {
2939                                                new_collapsed_entries.remove(&CollapsedEntry::Dir(
2940                                                    worktree_id,
2941                                                    current_entry.id,
2942                                                ));
2943                                            }
2944                                        }
2945
2946                                        let new_entry_added = entries_to_add
2947                                            .insert(current_entry.id, current_entry)
2948                                            .is_none();
2949                                        if new_entry_added
2950                                            && traversal.back_to_parent()
2951                                            && let Some(parent_entry) = traversal.entry()
2952                                        {
2953                                            current_entry = parent_entry.to_owned();
2954                                            continue;
2955                                        }
2956                                        break;
2957                                    }
2958                                    new_worktree_entries
2959                                        .entry(worktree_id)
2960                                        .or_insert_with(HashMap::default)
2961                                        .extend(entries_to_add);
2962                                }
2963                                None => {
2964                                    if processed_external_buffers.insert(buffer_id) {
2965                                        external_excerpts
2966                                            .entry(buffer_id)
2967                                            .or_insert_with(Vec::new)
2968                                            .extend(excerpts);
2969                                    }
2970                                }
2971                            }
2972                        } else if processed_external_buffers.insert(buffer_id) {
2973                            external_excerpts
2974                                .entry(buffer_id)
2975                                .or_insert_with(Vec::new)
2976                                .extend(excerpts);
2977                        }
2978                    }
2979
2980                    let mut new_children_count =
2981                        HashMap::<WorktreeId, HashMap<Arc<RelPath>, FsChildren>>::default();
2982
2983                    let worktree_entries = new_worktree_entries
2984                        .into_iter()
2985                        .map(|(worktree_id, entries)| {
2986                            let mut entries = entries.into_values().collect::<Vec<_>>();
2987                            entries.sort_by(|a, b| a.path.as_ref().cmp(b.path.as_ref()));
2988                            (worktree_id, entries)
2989                        })
2990                        .flat_map(|(worktree_id, entries)| {
2991                            {
2992                                entries
2993                                    .into_iter()
2994                                    .filter_map(|entry| {
2995                                        if auto_fold_dirs && let Some(parent) = entry.path.parent()
2996                                        {
2997                                            let children = new_children_count
2998                                                .entry(worktree_id)
2999                                                .or_default()
3000                                                .entry(Arc::from(parent))
3001                                                .or_default();
3002                                            if entry.is_dir() {
3003                                                children.dirs += 1;
3004                                            } else {
3005                                                children.files += 1;
3006                                            }
3007                                        }
3008
3009                                        if entry.is_dir() {
3010                                            Some(FsEntry::Directory(FsEntryDirectory {
3011                                                worktree_id,
3012                                                entry,
3013                                            }))
3014                                        } else {
3015                                            let (buffer_id, excerpts) = worktree_excerpts
3016                                                .get_mut(&worktree_id)
3017                                                .and_then(|worktree_excerpts| {
3018                                                    worktree_excerpts.remove(&entry.id)
3019                                                })?;
3020                                            Some(FsEntry::File(FsEntryFile {
3021                                                worktree_id,
3022                                                buffer_id,
3023                                                entry,
3024                                                excerpts,
3025                                            }))
3026                                        }
3027                                    })
3028                                    .collect::<Vec<_>>()
3029                            }
3030                        })
3031                        .collect::<Vec<_>>();
3032
3033                    let mut visited_dirs = Vec::new();
3034                    let mut new_depth_map = HashMap::default();
3035                    let new_visible_entries = external_excerpts
3036                        .into_iter()
3037                        .sorted_by_key(|(id, _)| *id)
3038                        .map(|(buffer_id, excerpts)| {
3039                            FsEntry::ExternalFile(FsEntryExternalFile {
3040                                buffer_id,
3041                                excerpts,
3042                            })
3043                        })
3044                        .chain(worktree_entries)
3045                        .filter(|visible_item| {
3046                            match visible_item {
3047                                FsEntry::Directory(directory) => {
3048                                    let parent_id = back_to_common_visited_parent(
3049                                        &mut visited_dirs,
3050                                        &directory.worktree_id,
3051                                        &directory.entry,
3052                                    );
3053
3054                                    let mut depth = 0;
3055                                    if !root_entries.contains(&directory.entry.id) {
3056                                        if auto_fold_dirs {
3057                                            let children = new_children_count
3058                                                .get(&directory.worktree_id)
3059                                                .and_then(|children_count| {
3060                                                    children_count.get(&directory.entry.path)
3061                                                })
3062                                                .copied()
3063                                                .unwrap_or_default();
3064
3065                                            if !children.may_be_fold_part()
3066                                                || (children.dirs == 0
3067                                                    && visited_dirs
3068                                                        .last()
3069                                                        .map(|(parent_dir_id, _)| {
3070                                                            new_unfolded_dirs
3071                                                                .get(&directory.worktree_id)
3072                                                                .is_none_or(|unfolded_dirs| {
3073                                                                    unfolded_dirs
3074                                                                        .contains(parent_dir_id)
3075                                                                })
3076                                                        })
3077                                                        .unwrap_or(true))
3078                                            {
3079                                                new_unfolded_dirs
3080                                                    .entry(directory.worktree_id)
3081                                                    .or_default()
3082                                                    .insert(directory.entry.id);
3083                                            }
3084                                        }
3085
3086                                        depth = parent_id
3087                                            .and_then(|(worktree_id, id)| {
3088                                                new_depth_map.get(&(worktree_id, id)).copied()
3089                                            })
3090                                            .unwrap_or(0)
3091                                            + 1;
3092                                    };
3093                                    visited_dirs
3094                                        .push((directory.entry.id, directory.entry.path.clone()));
3095                                    new_depth_map
3096                                        .insert((directory.worktree_id, directory.entry.id), depth);
3097                                }
3098                                FsEntry::File(FsEntryFile {
3099                                    worktree_id,
3100                                    entry: file_entry,
3101                                    ..
3102                                }) => {
3103                                    let parent_id = back_to_common_visited_parent(
3104                                        &mut visited_dirs,
3105                                        worktree_id,
3106                                        file_entry,
3107                                    );
3108                                    let depth = if root_entries.contains(&file_entry.id) {
3109                                        0
3110                                    } else {
3111                                        parent_id
3112                                            .and_then(|(worktree_id, id)| {
3113                                                new_depth_map.get(&(worktree_id, id)).copied()
3114                                            })
3115                                            .unwrap_or(0)
3116                                            + 1
3117                                    };
3118                                    new_depth_map.insert((*worktree_id, file_entry.id), depth);
3119                                }
3120                                FsEntry::ExternalFile(..) => {
3121                                    visited_dirs.clear();
3122                                }
3123                            }
3124
3125                            true
3126                        })
3127                        .collect::<Vec<_>>();
3128
3129                    anyhow::Ok((
3130                        new_collapsed_entries,
3131                        new_unfolded_dirs,
3132                        new_visible_entries,
3133                        new_depth_map,
3134                        new_children_count,
3135                    ))
3136                })
3137                .await
3138                .log_err()
3139            else {
3140                return;
3141            };
3142
3143            outline_panel
3144                .update_in(cx, |outline_panel, window, cx| {
3145                    outline_panel.new_entries_for_fs_update.clear();
3146                    outline_panel.excerpts = new_excerpts;
3147                    outline_panel.collapsed_entries = new_collapsed_entries;
3148                    outline_panel.unfolded_dirs = new_unfolded_dirs;
3149                    outline_panel.fs_entries = new_fs_entries;
3150                    outline_panel.fs_entries_depth = new_depth_map;
3151                    outline_panel.fs_children_count = new_children_count;
3152                    outline_panel.update_non_fs_items(window, cx);
3153
3154                    // Only update cached entries if we don't have outlines to fetch
3155                    // If we do have outlines to fetch, let fetch_outdated_outlines handle the update
3156                    if outline_panel.excerpt_fetch_ranges(cx).is_empty() {
3157                        outline_panel.update_cached_entries(debounce, window, cx);
3158                    }
3159
3160                    cx.notify();
3161                })
3162                .ok();
3163        });
3164    }
3165
3166    fn replace_active_editor(
3167        &mut self,
3168        new_active_item: Box<dyn ItemHandle>,
3169        new_active_editor: Entity<Editor>,
3170        window: &mut Window,
3171        cx: &mut Context<Self>,
3172    ) {
3173        self.clear_previous(window, cx);
3174
3175        let default_expansion_depth =
3176            OutlinePanelSettings::get_global(cx).expand_outlines_with_depth;
3177        // We'll apply the expansion depth after outlines are loaded
3178        self.pending_default_expansion_depth = Some(default_expansion_depth);
3179
3180        let buffer_search_subscription = cx.subscribe_in(
3181            &new_active_editor,
3182            window,
3183            |outline_panel: &mut Self,
3184             _,
3185             e: &SearchEvent,
3186             window: &mut Window,
3187             cx: &mut Context<Self>| {
3188                if matches!(e, SearchEvent::MatchesInvalidated) {
3189                    let update_cached_items = outline_panel.update_search_matches(window, cx);
3190                    if update_cached_items {
3191                        outline_panel.selected_entry.invalidate();
3192                        outline_panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
3193                    }
3194                };
3195                outline_panel.autoscroll(cx);
3196            },
3197        );
3198        self.active_item = Some(ActiveItem {
3199            _buffer_search_subscription: buffer_search_subscription,
3200            _editor_subscription: subscribe_for_editor_events(&new_active_editor, window, cx),
3201            item_handle: new_active_item.downgrade_item(),
3202            active_editor: new_active_editor.downgrade(),
3203        });
3204        self.new_entries_for_fs_update
3205            .extend(new_active_editor.read(cx).buffer().read(cx).excerpt_ids());
3206        self.selected_entry.invalidate();
3207        self.update_fs_entries(new_active_editor, None, window, cx);
3208    }
3209
3210    fn clear_previous(&mut self, window: &mut Window, cx: &mut App) {
3211        self.fs_entries_update_task = Task::ready(());
3212        self.outline_fetch_tasks.clear();
3213        self.cached_entries_update_task = Task::ready(());
3214        self.reveal_selection_task = Task::ready(Ok(()));
3215        self.filter_editor
3216            .update(cx, |editor, cx| editor.clear(window, cx));
3217        self.collapsed_entries.clear();
3218        self.unfolded_dirs.clear();
3219        self.active_item = None;
3220        self.fs_entries.clear();
3221        self.fs_entries_depth.clear();
3222        self.fs_children_count.clear();
3223        self.excerpts.clear();
3224        self.cached_entries = Vec::new();
3225        self.selected_entry = SelectedEntry::None;
3226        self.pinned = false;
3227        self.mode = ItemsDisplayMode::Outline;
3228        self.pending_default_expansion_depth = None;
3229    }
3230
3231    fn location_for_editor_selection(
3232        &self,
3233        editor: &Entity<Editor>,
3234        window: &mut Window,
3235        cx: &mut Context<Self>,
3236    ) -> Option<PanelEntry> {
3237        let selection = editor.update(cx, |editor, cx| {
3238            editor
3239                .selections
3240                .newest::<language::Point>(&editor.display_snapshot(cx))
3241                .head()
3242        });
3243        let editor_snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
3244        let multi_buffer = editor.read(cx).buffer();
3245        let multi_buffer_snapshot = multi_buffer.read(cx).snapshot(cx);
3246        let (excerpt_id, buffer, _) = editor
3247            .read(cx)
3248            .buffer()
3249            .read(cx)
3250            .excerpt_containing(selection, cx)?;
3251        let buffer_id = buffer.read(cx).remote_id();
3252
3253        if editor.read(cx).is_buffer_folded(buffer_id, cx) {
3254            return self
3255                .fs_entries
3256                .iter()
3257                .find(|fs_entry| match fs_entry {
3258                    FsEntry::Directory(..) => false,
3259                    FsEntry::File(FsEntryFile {
3260                        buffer_id: other_buffer_id,
3261                        ..
3262                    })
3263                    | FsEntry::ExternalFile(FsEntryExternalFile {
3264                        buffer_id: other_buffer_id,
3265                        ..
3266                    }) => buffer_id == *other_buffer_id,
3267                })
3268                .cloned()
3269                .map(PanelEntry::Fs);
3270        }
3271
3272        let selection_display_point = selection.to_display_point(&editor_snapshot);
3273
3274        match &self.mode {
3275            ItemsDisplayMode::Search(search_state) => search_state
3276                .matches
3277                .iter()
3278                .rev()
3279                .min_by_key(|&(match_range, _)| {
3280                    let match_display_range =
3281                        match_range.clone().to_display_points(&editor_snapshot);
3282                    let start_distance = if selection_display_point < match_display_range.start {
3283                        match_display_range.start - selection_display_point
3284                    } else {
3285                        selection_display_point - match_display_range.start
3286                    };
3287                    let end_distance = if selection_display_point < match_display_range.end {
3288                        match_display_range.end - selection_display_point
3289                    } else {
3290                        selection_display_point - match_display_range.end
3291                    };
3292                    start_distance + end_distance
3293                })
3294                .and_then(|(closest_range, _)| {
3295                    self.cached_entries.iter().find_map(|cached_entry| {
3296                        if let PanelEntry::Search(SearchEntry { match_range, .. }) =
3297                            &cached_entry.entry
3298                        {
3299                            if match_range == closest_range {
3300                                Some(cached_entry.entry.clone())
3301                            } else {
3302                                None
3303                            }
3304                        } else {
3305                            None
3306                        }
3307                    })
3308                }),
3309            ItemsDisplayMode::Outline => self.outline_location(
3310                buffer_id,
3311                excerpt_id,
3312                multi_buffer_snapshot,
3313                editor_snapshot,
3314                selection_display_point,
3315            ),
3316        }
3317    }
3318
3319    fn outline_location(
3320        &self,
3321        buffer_id: BufferId,
3322        excerpt_id: ExcerptId,
3323        multi_buffer_snapshot: editor::MultiBufferSnapshot,
3324        editor_snapshot: editor::EditorSnapshot,
3325        selection_display_point: DisplayPoint,
3326    ) -> Option<PanelEntry> {
3327        let excerpt_outlines = self
3328            .excerpts
3329            .get(&buffer_id)
3330            .and_then(|excerpts| excerpts.get(&excerpt_id))
3331            .into_iter()
3332            .flat_map(|excerpt| excerpt.iter_outlines())
3333            .flat_map(|outline| {
3334                let range = multi_buffer_snapshot
3335                    .anchor_range_in_buffer(excerpt_id, outline.range.clone())?;
3336                Some((
3337                    range.start.to_display_point(&editor_snapshot)
3338                        ..range.end.to_display_point(&editor_snapshot),
3339                    outline,
3340                ))
3341            })
3342            .collect::<Vec<_>>();
3343
3344        let mut matching_outline_indices = Vec::new();
3345        let mut children = HashMap::default();
3346        let mut parents_stack = Vec::<(&Range<DisplayPoint>, &&Outline, usize)>::new();
3347
3348        for (i, (outline_range, outline)) in excerpt_outlines.iter().enumerate() {
3349            if outline_range
3350                .to_inclusive()
3351                .contains(&selection_display_point)
3352            {
3353                matching_outline_indices.push(i);
3354            } else if (outline_range.start.row()..outline_range.end.row())
3355                .to_inclusive()
3356                .contains(&selection_display_point.row())
3357            {
3358                matching_outline_indices.push(i);
3359            }
3360
3361            while let Some((parent_range, parent_outline, _)) = parents_stack.last() {
3362                if parent_outline.depth >= outline.depth
3363                    || !parent_range.contains(&outline_range.start)
3364                {
3365                    parents_stack.pop();
3366                } else {
3367                    break;
3368                }
3369            }
3370            if let Some((_, _, parent_index)) = parents_stack.last_mut() {
3371                children
3372                    .entry(*parent_index)
3373                    .or_insert_with(Vec::new)
3374                    .push(i);
3375            }
3376            parents_stack.push((outline_range, outline, i));
3377        }
3378
3379        let outline_item = matching_outline_indices
3380            .into_iter()
3381            .flat_map(|i| Some((i, excerpt_outlines.get(i)?)))
3382            .filter(|(i, _)| {
3383                children
3384                    .get(i)
3385                    .map(|children| {
3386                        children.iter().all(|child_index| {
3387                            excerpt_outlines
3388                                .get(*child_index)
3389                                .map(|(child_range, _)| child_range.start > selection_display_point)
3390                                .unwrap_or(false)
3391                        })
3392                    })
3393                    .unwrap_or(true)
3394            })
3395            .min_by_key(|(_, (outline_range, outline))| {
3396                let distance_from_start = if outline_range.start > selection_display_point {
3397                    outline_range.start - selection_display_point
3398                } else {
3399                    selection_display_point - outline_range.start
3400                };
3401                let distance_from_end = if outline_range.end > selection_display_point {
3402                    outline_range.end - selection_display_point
3403                } else {
3404                    selection_display_point - outline_range.end
3405                };
3406
3407                (
3408                    cmp::Reverse(outline.depth),
3409                    distance_from_start + distance_from_end,
3410                )
3411            })
3412            .map(|(_, (_, outline))| *outline)
3413            .cloned();
3414
3415        let closest_container = match outline_item {
3416            Some(outline) => PanelEntry::Outline(OutlineEntry::Outline(OutlineEntryOutline {
3417                buffer_id,
3418                excerpt_id,
3419                outline,
3420            })),
3421            None => {
3422                self.cached_entries.iter().rev().find_map(|cached_entry| {
3423                    match &cached_entry.entry {
3424                        PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => {
3425                            if excerpt.buffer_id == buffer_id && excerpt.id == excerpt_id {
3426                                Some(cached_entry.entry.clone())
3427                            } else {
3428                                None
3429                            }
3430                        }
3431                        PanelEntry::Fs(
3432                            FsEntry::ExternalFile(FsEntryExternalFile {
3433                                buffer_id: file_buffer_id,
3434                                excerpts: file_excerpts,
3435                            })
3436                            | FsEntry::File(FsEntryFile {
3437                                buffer_id: file_buffer_id,
3438                                excerpts: file_excerpts,
3439                                ..
3440                            }),
3441                        ) => {
3442                            if file_buffer_id == &buffer_id && file_excerpts.contains(&excerpt_id) {
3443                                Some(cached_entry.entry.clone())
3444                            } else {
3445                                None
3446                            }
3447                        }
3448                        _ => None,
3449                    }
3450                })?
3451            }
3452        };
3453        Some(closest_container)
3454    }
3455
3456    fn fetch_outdated_outlines(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3457        let excerpt_fetch_ranges = self.excerpt_fetch_ranges(cx);
3458        if excerpt_fetch_ranges.is_empty() {
3459            return;
3460        }
3461
3462        let first_update = Arc::new(AtomicBool::new(true));
3463        for (buffer_id, (_buffer_snapshot, excerpt_ranges)) in excerpt_fetch_ranges {
3464            let outline_task = self.active_editor().map(|editor| {
3465                editor.update(cx, |editor, cx| editor.buffer_outline_items(buffer_id, cx))
3466            });
3467
3468            let excerpt_ids = excerpt_ranges.keys().copied().collect::<Vec<_>>();
3469            let first_update = first_update.clone();
3470
3471            self.outline_fetch_tasks.insert(
3472                buffer_id,
3473                cx.spawn_in(window, async move |outline_panel, cx| {
3474                    let Some(outline_task) = outline_task else {
3475                        return;
3476                    };
3477                    let fetched_outlines = outline_task.await;
3478                    let outlines_with_children = fetched_outlines
3479                        .windows(2)
3480                        .filter_map(|window| {
3481                            let current = &window[0];
3482                            let next = &window[1];
3483                            if next.depth > current.depth {
3484                                Some((current.range.clone(), current.depth))
3485                            } else {
3486                                None
3487                            }
3488                        })
3489                        .collect::<HashSet<_>>();
3490
3491                    outline_panel
3492                        .update_in(cx, |outline_panel, window, cx| {
3493                            let pending_default_depth =
3494                                outline_panel.pending_default_expansion_depth.take();
3495
3496                            let debounce =
3497                                if first_update.fetch_and(false, atomic::Ordering::AcqRel) {
3498                                    None
3499                                } else {
3500                                    Some(UPDATE_DEBOUNCE)
3501                                };
3502
3503                            for excerpt_id in &excerpt_ids {
3504                                if let Some(excerpt) = outline_panel
3505                                    .excerpts
3506                                    .entry(buffer_id)
3507                                    .or_default()
3508                                    .get_mut(excerpt_id)
3509                                {
3510                                    excerpt.outlines =
3511                                        ExcerptOutlines::Outlines(fetched_outlines.clone());
3512
3513                                    if let Some(default_depth) = pending_default_depth
3514                                        && let ExcerptOutlines::Outlines(outlines) =
3515                                            &excerpt.outlines
3516                                    {
3517                                        outlines
3518                                            .iter()
3519                                            .filter(|outline| {
3520                                                (default_depth == 0
3521                                                    || outline.depth >= default_depth)
3522                                                    && outlines_with_children.contains(&(
3523                                                        outline.range.clone(),
3524                                                        outline.depth,
3525                                                    ))
3526                                            })
3527                                            .for_each(|outline| {
3528                                                outline_panel.collapsed_entries.insert(
3529                                                    CollapsedEntry::Outline(
3530                                                        buffer_id,
3531                                                        *excerpt_id,
3532                                                        outline.range.clone(),
3533                                                    ),
3534                                                );
3535                                            });
3536                                    }
3537                                }
3538                            }
3539
3540                            outline_panel.update_cached_entries(debounce, window, cx);
3541                        })
3542                        .ok();
3543                }),
3544            );
3545        }
3546    }
3547
3548    fn is_singleton_active(&self, cx: &App) -> bool {
3549        self.active_editor()
3550            .is_some_and(|active_editor| active_editor.read(cx).buffer().read(cx).is_singleton())
3551    }
3552
3553    fn invalidate_outlines(&mut self, ids: &[ExcerptId]) {
3554        self.outline_fetch_tasks.clear();
3555        let mut ids = ids.iter().collect::<HashSet<_>>();
3556        for excerpts in self.excerpts.values_mut() {
3557            ids.retain(|id| {
3558                if let Some(excerpt) = excerpts.get_mut(id) {
3559                    excerpt.invalidate_outlines();
3560                    false
3561                } else {
3562                    true
3563                }
3564            });
3565            if ids.is_empty() {
3566                break;
3567            }
3568        }
3569    }
3570
3571    fn excerpt_fetch_ranges(
3572        &self,
3573        cx: &App,
3574    ) -> HashMap<
3575        BufferId,
3576        (
3577            BufferSnapshot,
3578            HashMap<ExcerptId, ExcerptRange<language::Anchor>>,
3579        ),
3580    > {
3581        self.fs_entries
3582            .iter()
3583            .fold(HashMap::default(), |mut excerpts_to_fetch, fs_entry| {
3584                match fs_entry {
3585                    FsEntry::File(FsEntryFile {
3586                        buffer_id,
3587                        excerpts: file_excerpts,
3588                        ..
3589                    })
3590                    | FsEntry::ExternalFile(FsEntryExternalFile {
3591                        buffer_id,
3592                        excerpts: file_excerpts,
3593                    }) => {
3594                        let excerpts = self.excerpts.get(buffer_id);
3595                        for &file_excerpt in file_excerpts {
3596                            if let Some(excerpt) = excerpts
3597                                .and_then(|excerpts| excerpts.get(&file_excerpt))
3598                                .filter(|excerpt| excerpt.should_fetch_outlines())
3599                            {
3600                                match excerpts_to_fetch.entry(*buffer_id) {
3601                                    hash_map::Entry::Occupied(mut o) => {
3602                                        o.get_mut().1.insert(file_excerpt, excerpt.range.clone());
3603                                    }
3604                                    hash_map::Entry::Vacant(v) => {
3605                                        if let Some(buffer_snapshot) =
3606                                            self.buffer_snapshot_for_id(*buffer_id, cx)
3607                                        {
3608                                            v.insert((buffer_snapshot, HashMap::default()))
3609                                                .1
3610                                                .insert(file_excerpt, excerpt.range.clone());
3611                                        }
3612                                    }
3613                                }
3614                            }
3615                        }
3616                    }
3617                    FsEntry::Directory(..) => {}
3618                }
3619                excerpts_to_fetch
3620            })
3621    }
3622
3623    fn buffer_snapshot_for_id(&self, buffer_id: BufferId, cx: &App) -> Option<BufferSnapshot> {
3624        let editor = self.active_editor()?;
3625        Some(
3626            editor
3627                .read(cx)
3628                .buffer()
3629                .read(cx)
3630                .buffer(buffer_id)?
3631                .read(cx)
3632                .snapshot(),
3633        )
3634    }
3635
3636    fn abs_path(&self, entry: &PanelEntry, cx: &App) -> Option<PathBuf> {
3637        match entry {
3638            PanelEntry::Fs(
3639                FsEntry::File(FsEntryFile { buffer_id, .. })
3640                | FsEntry::ExternalFile(FsEntryExternalFile { buffer_id, .. }),
3641            ) => self
3642                .buffer_snapshot_for_id(*buffer_id, cx)
3643                .and_then(|buffer_snapshot| {
3644                    let file = File::from_dyn(buffer_snapshot.file())?;
3645                    Some(file.worktree.read(cx).absolutize(&file.path))
3646                }),
3647            PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory {
3648                worktree_id, entry, ..
3649            })) => Some(
3650                self.project
3651                    .read(cx)
3652                    .worktree_for_id(*worktree_id, cx)?
3653                    .read(cx)
3654                    .absolutize(&entry.path),
3655            ),
3656            PanelEntry::FoldedDirs(FoldedDirsEntry {
3657                worktree_id,
3658                entries: dirs,
3659                ..
3660            }) => dirs.last().and_then(|entry| {
3661                self.project
3662                    .read(cx)
3663                    .worktree_for_id(*worktree_id, cx)
3664                    .map(|worktree| worktree.read(cx).absolutize(&entry.path))
3665            }),
3666            PanelEntry::Search(_) | PanelEntry::Outline(..) => None,
3667        }
3668    }
3669
3670    fn relative_path(&self, entry: &FsEntry, cx: &App) -> Option<Arc<RelPath>> {
3671        match entry {
3672            FsEntry::ExternalFile(FsEntryExternalFile { buffer_id, .. }) => {
3673                let buffer_snapshot = self.buffer_snapshot_for_id(*buffer_id, cx)?;
3674                Some(buffer_snapshot.file()?.path().clone())
3675            }
3676            FsEntry::Directory(FsEntryDirectory { entry, .. }) => Some(entry.path.clone()),
3677            FsEntry::File(FsEntryFile { entry, .. }) => Some(entry.path.clone()),
3678        }
3679    }
3680
3681    fn update_cached_entries(
3682        &mut self,
3683        debounce: Option<Duration>,
3684        window: &mut Window,
3685        cx: &mut Context<OutlinePanel>,
3686    ) {
3687        if !self.active {
3688            return;
3689        }
3690
3691        let is_singleton = self.is_singleton_active(cx);
3692        let query = self.query(cx);
3693        self.cached_entries_update_task = cx.spawn_in(window, async move |outline_panel, cx| {
3694            if let Some(debounce) = debounce {
3695                cx.background_executor().timer(debounce).await;
3696            }
3697            let Some(new_cached_entries) = outline_panel
3698                .update_in(cx, |outline_panel, window, cx| {
3699                    outline_panel.generate_cached_entries(is_singleton, query, window, cx)
3700                })
3701                .ok()
3702            else {
3703                return;
3704            };
3705            let (new_cached_entries, max_width_item_index) = new_cached_entries.await;
3706            outline_panel
3707                .update_in(cx, |outline_panel, window, cx| {
3708                    outline_panel.cached_entries = new_cached_entries;
3709                    outline_panel.max_width_item_index = max_width_item_index;
3710                    if (outline_panel.selected_entry.is_invalidated()
3711                        || matches!(outline_panel.selected_entry, SelectedEntry::None))
3712                        && let Some(new_selected_entry) =
3713                            outline_panel.active_editor().and_then(|active_editor| {
3714                                outline_panel.location_for_editor_selection(
3715                                    &active_editor,
3716                                    window,
3717                                    cx,
3718                                )
3719                            })
3720                    {
3721                        outline_panel.select_entry(new_selected_entry, false, window, cx);
3722                    }
3723
3724                    outline_panel.autoscroll(cx);
3725                    cx.notify();
3726                })
3727                .ok();
3728        });
3729    }
3730
3731    fn generate_cached_entries(
3732        &self,
3733        is_singleton: bool,
3734        query: Option<String>,
3735        window: &mut Window,
3736        cx: &mut Context<Self>,
3737    ) -> Task<(Vec<CachedEntry>, Option<usize>)> {
3738        let project = self.project.clone();
3739        let Some(active_editor) = self.active_editor() else {
3740            return Task::ready((Vec::new(), None));
3741        };
3742        cx.spawn_in(window, async move |outline_panel, cx| {
3743            let mut generation_state = GenerationState::default();
3744
3745            let Ok(()) = outline_panel.update(cx, |outline_panel, cx| {
3746                let auto_fold_dirs = OutlinePanelSettings::get_global(cx).auto_fold_dirs;
3747                let mut folded_dirs_entry = None::<(usize, FoldedDirsEntry)>;
3748                let track_matches = query.is_some();
3749
3750                #[derive(Debug)]
3751                struct ParentStats {
3752                    path: Arc<RelPath>,
3753                    folded: bool,
3754                    expanded: bool,
3755                    depth: usize,
3756                }
3757                let mut parent_dirs = Vec::<ParentStats>::new();
3758                for entry in outline_panel.fs_entries.clone() {
3759                    let is_expanded = outline_panel.is_expanded(&entry);
3760                    let (depth, should_add) = match &entry {
3761                        FsEntry::Directory(directory_entry) => {
3762                            let mut should_add = true;
3763                            let is_root = project
3764                                .read(cx)
3765                                .worktree_for_id(directory_entry.worktree_id, cx)
3766                                .is_some_and(|worktree| {
3767                                    worktree.read(cx).root_entry() == Some(&directory_entry.entry)
3768                                });
3769                            let folded = auto_fold_dirs
3770                                && !is_root
3771                                && outline_panel
3772                                    .unfolded_dirs
3773                                    .get(&directory_entry.worktree_id)
3774                                    .is_none_or(|unfolded_dirs| {
3775                                        !unfolded_dirs.contains(&directory_entry.entry.id)
3776                                    });
3777                            let fs_depth = outline_panel
3778                                .fs_entries_depth
3779                                .get(&(directory_entry.worktree_id, directory_entry.entry.id))
3780                                .copied()
3781                                .unwrap_or(0);
3782                            while let Some(parent) = parent_dirs.last() {
3783                                if !is_root && directory_entry.entry.path.starts_with(&parent.path)
3784                                {
3785                                    break;
3786                                }
3787                                parent_dirs.pop();
3788                            }
3789                            let auto_fold = match parent_dirs.last() {
3790                                Some(parent) => {
3791                                    parent.folded
3792                                        && Some(parent.path.as_ref())
3793                                            == directory_entry.entry.path.parent()
3794                                        && outline_panel
3795                                            .fs_children_count
3796                                            .get(&directory_entry.worktree_id)
3797                                            .and_then(|entries| {
3798                                                entries.get(&directory_entry.entry.path)
3799                                            })
3800                                            .copied()
3801                                            .unwrap_or_default()
3802                                            .may_be_fold_part()
3803                                }
3804                                None => false,
3805                            };
3806                            let folded = folded || auto_fold;
3807                            let (depth, parent_expanded, parent_folded) = match parent_dirs.last() {
3808                                Some(parent) => {
3809                                    let parent_folded = parent.folded;
3810                                    let parent_expanded = parent.expanded;
3811                                    let new_depth = if parent_folded {
3812                                        parent.depth
3813                                    } else {
3814                                        parent.depth + 1
3815                                    };
3816                                    parent_dirs.push(ParentStats {
3817                                        path: directory_entry.entry.path.clone(),
3818                                        folded,
3819                                        expanded: parent_expanded && is_expanded,
3820                                        depth: new_depth,
3821                                    });
3822                                    (new_depth, parent_expanded, parent_folded)
3823                                }
3824                                None => {
3825                                    parent_dirs.push(ParentStats {
3826                                        path: directory_entry.entry.path.clone(),
3827                                        folded,
3828                                        expanded: is_expanded,
3829                                        depth: fs_depth,
3830                                    });
3831                                    (fs_depth, true, false)
3832                                }
3833                            };
3834
3835                            if let Some((folded_depth, mut folded_dirs)) = folded_dirs_entry.take()
3836                            {
3837                                if folded
3838                                    && directory_entry.worktree_id == folded_dirs.worktree_id
3839                                    && directory_entry.entry.path.parent()
3840                                        == folded_dirs
3841                                            .entries
3842                                            .last()
3843                                            .map(|entry| entry.path.as_ref())
3844                                {
3845                                    folded_dirs.entries.push(directory_entry.entry.clone());
3846                                    folded_dirs_entry = Some((folded_depth, folded_dirs))
3847                                } else {
3848                                    if !is_singleton {
3849                                        let start_of_collapsed_dir_sequence = !parent_expanded
3850                                            && parent_dirs
3851                                                .iter()
3852                                                .rev()
3853                                                .nth(folded_dirs.entries.len() + 1)
3854                                                .is_none_or(|parent| parent.expanded);
3855                                        if start_of_collapsed_dir_sequence
3856                                            || parent_expanded
3857                                            || query.is_some()
3858                                        {
3859                                            if parent_folded {
3860                                                folded_dirs
3861                                                    .entries
3862                                                    .push(directory_entry.entry.clone());
3863                                                should_add = false;
3864                                            }
3865                                            let new_folded_dirs =
3866                                                PanelEntry::FoldedDirs(folded_dirs.clone());
3867                                            outline_panel.push_entry(
3868                                                &mut generation_state,
3869                                                track_matches,
3870                                                new_folded_dirs,
3871                                                folded_depth,
3872                                                cx,
3873                                            );
3874                                        }
3875                                    }
3876
3877                                    folded_dirs_entry = if parent_folded {
3878                                        None
3879                                    } else {
3880                                        Some((
3881                                            depth,
3882                                            FoldedDirsEntry {
3883                                                worktree_id: directory_entry.worktree_id,
3884                                                entries: vec![directory_entry.entry.clone()],
3885                                            },
3886                                        ))
3887                                    };
3888                                }
3889                            } else if folded {
3890                                folded_dirs_entry = Some((
3891                                    depth,
3892                                    FoldedDirsEntry {
3893                                        worktree_id: directory_entry.worktree_id,
3894                                        entries: vec![directory_entry.entry.clone()],
3895                                    },
3896                                ));
3897                            }
3898
3899                            let should_add =
3900                                should_add && parent_expanded && folded_dirs_entry.is_none();
3901                            (depth, should_add)
3902                        }
3903                        FsEntry::ExternalFile(..) => {
3904                            if let Some((folded_depth, folded_dir)) = folded_dirs_entry.take() {
3905                                let parent_expanded = parent_dirs
3906                                    .iter()
3907                                    .rev()
3908                                    .find(|parent| {
3909                                        folded_dir
3910                                            .entries
3911                                            .iter()
3912                                            .all(|entry| entry.path != parent.path)
3913                                    })
3914                                    .is_none_or(|parent| parent.expanded);
3915                                if !is_singleton && (parent_expanded || query.is_some()) {
3916                                    outline_panel.push_entry(
3917                                        &mut generation_state,
3918                                        track_matches,
3919                                        PanelEntry::FoldedDirs(folded_dir),
3920                                        folded_depth,
3921                                        cx,
3922                                    );
3923                                }
3924                            }
3925                            parent_dirs.clear();
3926                            (0, true)
3927                        }
3928                        FsEntry::File(file) => {
3929                            if let Some((folded_depth, folded_dirs)) = folded_dirs_entry.take() {
3930                                let parent_expanded = parent_dirs
3931                                    .iter()
3932                                    .rev()
3933                                    .find(|parent| {
3934                                        folded_dirs
3935                                            .entries
3936                                            .iter()
3937                                            .all(|entry| entry.path != parent.path)
3938                                    })
3939                                    .is_none_or(|parent| parent.expanded);
3940                                if !is_singleton && (parent_expanded || query.is_some()) {
3941                                    outline_panel.push_entry(
3942                                        &mut generation_state,
3943                                        track_matches,
3944                                        PanelEntry::FoldedDirs(folded_dirs),
3945                                        folded_depth,
3946                                        cx,
3947                                    );
3948                                }
3949                            }
3950
3951                            let fs_depth = outline_panel
3952                                .fs_entries_depth
3953                                .get(&(file.worktree_id, file.entry.id))
3954                                .copied()
3955                                .unwrap_or(0);
3956                            while let Some(parent) = parent_dirs.last() {
3957                                if file.entry.path.starts_with(&parent.path) {
3958                                    break;
3959                                }
3960                                parent_dirs.pop();
3961                            }
3962                            match parent_dirs.last() {
3963                                Some(parent) => {
3964                                    let new_depth = parent.depth + 1;
3965                                    (new_depth, parent.expanded)
3966                                }
3967                                None => (fs_depth, true),
3968                            }
3969                        }
3970                    };
3971
3972                    if !is_singleton
3973                        && (should_add || (query.is_some() && folded_dirs_entry.is_none()))
3974                    {
3975                        outline_panel.push_entry(
3976                            &mut generation_state,
3977                            track_matches,
3978                            PanelEntry::Fs(entry.clone()),
3979                            depth,
3980                            cx,
3981                        );
3982                    }
3983
3984                    match outline_panel.mode {
3985                        ItemsDisplayMode::Search(_) => {
3986                            if is_singleton || query.is_some() || (should_add && is_expanded) {
3987                                outline_panel.add_search_entries(
3988                                    &mut generation_state,
3989                                    &active_editor,
3990                                    entry.clone(),
3991                                    depth,
3992                                    query.clone(),
3993                                    is_singleton,
3994                                    cx,
3995                                );
3996                            }
3997                        }
3998                        ItemsDisplayMode::Outline => {
3999                            let excerpts_to_consider =
4000                                if is_singleton || query.is_some() || (should_add && is_expanded) {
4001                                    match &entry {
4002                                        FsEntry::File(FsEntryFile {
4003                                            buffer_id,
4004                                            excerpts,
4005                                            ..
4006                                        })
4007                                        | FsEntry::ExternalFile(FsEntryExternalFile {
4008                                            buffer_id,
4009                                            excerpts,
4010                                            ..
4011                                        }) => Some((*buffer_id, excerpts)),
4012                                        _ => None,
4013                                    }
4014                                } else {
4015                                    None
4016                                };
4017                            if let Some((buffer_id, entry_excerpts)) = excerpts_to_consider
4018                                && !active_editor.read(cx).is_buffer_folded(buffer_id, cx)
4019                            {
4020                                outline_panel.add_excerpt_entries(
4021                                    &mut generation_state,
4022                                    buffer_id,
4023                                    entry_excerpts,
4024                                    depth,
4025                                    track_matches,
4026                                    is_singleton,
4027                                    query.as_deref(),
4028                                    cx,
4029                                );
4030                            }
4031                        }
4032                    }
4033
4034                    if is_singleton
4035                        && matches!(entry, FsEntry::File(..) | FsEntry::ExternalFile(..))
4036                        && !generation_state.entries.iter().any(|item| {
4037                            matches!(item.entry, PanelEntry::Outline(..) | PanelEntry::Search(_))
4038                        })
4039                    {
4040                        outline_panel.push_entry(
4041                            &mut generation_state,
4042                            track_matches,
4043                            PanelEntry::Fs(entry.clone()),
4044                            0,
4045                            cx,
4046                        );
4047                    }
4048                }
4049
4050                if let Some((folded_depth, folded_dirs)) = folded_dirs_entry.take() {
4051                    let parent_expanded = parent_dirs
4052                        .iter()
4053                        .rev()
4054                        .find(|parent| {
4055                            folded_dirs
4056                                .entries
4057                                .iter()
4058                                .all(|entry| entry.path != parent.path)
4059                        })
4060                        .is_none_or(|parent| parent.expanded);
4061                    if parent_expanded || query.is_some() {
4062                        outline_panel.push_entry(
4063                            &mut generation_state,
4064                            track_matches,
4065                            PanelEntry::FoldedDirs(folded_dirs),
4066                            folded_depth,
4067                            cx,
4068                        );
4069                    }
4070                }
4071            }) else {
4072                return (Vec::new(), None);
4073            };
4074
4075            let Some(query) = query else {
4076                return (
4077                    generation_state.entries,
4078                    generation_state
4079                        .max_width_estimate_and_index
4080                        .map(|(_, index)| index),
4081                );
4082            };
4083
4084            let mut matched_ids = match_strings(
4085                &generation_state.match_candidates,
4086                &query,
4087                true,
4088                true,
4089                usize::MAX,
4090                &AtomicBool::default(),
4091                cx.background_executor().clone(),
4092            )
4093            .await
4094            .into_iter()
4095            .map(|string_match| (string_match.candidate_id, string_match))
4096            .collect::<HashMap<_, _>>();
4097
4098            let mut id = 0;
4099            generation_state.entries.retain_mut(|cached_entry| {
4100                let retain = match matched_ids.remove(&id) {
4101                    Some(string_match) => {
4102                        cached_entry.string_match = Some(string_match);
4103                        true
4104                    }
4105                    None => false,
4106                };
4107                id += 1;
4108                retain
4109            });
4110
4111            (
4112                generation_state.entries,
4113                generation_state
4114                    .max_width_estimate_and_index
4115                    .map(|(_, index)| index),
4116            )
4117        })
4118    }
4119
4120    fn push_entry(
4121        &self,
4122        state: &mut GenerationState,
4123        track_matches: bool,
4124        entry: PanelEntry,
4125        depth: usize,
4126        cx: &mut App,
4127    ) {
4128        let entry = if let PanelEntry::FoldedDirs(folded_dirs_entry) = &entry {
4129            match folded_dirs_entry.entries.len() {
4130                0 => {
4131                    debug_panic!("Empty folded dirs receiver");
4132                    return;
4133                }
4134                1 => PanelEntry::Fs(FsEntry::Directory(FsEntryDirectory {
4135                    worktree_id: folded_dirs_entry.worktree_id,
4136                    entry: folded_dirs_entry.entries[0].clone(),
4137                })),
4138                _ => entry,
4139            }
4140        } else {
4141            entry
4142        };
4143
4144        if track_matches {
4145            let id = state.entries.len();
4146            match &entry {
4147                PanelEntry::Fs(fs_entry) => {
4148                    if let Some(file_name) = self
4149                        .relative_path(fs_entry, cx)
4150                        .and_then(|path| Some(path.file_name()?.to_string()))
4151                    {
4152                        state
4153                            .match_candidates
4154                            .push(StringMatchCandidate::new(id, &file_name));
4155                    }
4156                }
4157                PanelEntry::FoldedDirs(folded_dir_entry) => {
4158                    let dir_names = self.dir_names_string(
4159                        &folded_dir_entry.entries,
4160                        folded_dir_entry.worktree_id,
4161                        cx,
4162                    );
4163                    {
4164                        state
4165                            .match_candidates
4166                            .push(StringMatchCandidate::new(id, &dir_names));
4167                    }
4168                }
4169                PanelEntry::Outline(OutlineEntry::Outline(outline_entry)) => state
4170                    .match_candidates
4171                    .push(StringMatchCandidate::new(id, &outline_entry.outline.text)),
4172                PanelEntry::Outline(OutlineEntry::Excerpt(_)) => {}
4173                PanelEntry::Search(new_search_entry) => {
4174                    if let Some(search_data) = new_search_entry.render_data.get() {
4175                        state
4176                            .match_candidates
4177                            .push(StringMatchCandidate::new(id, &search_data.context_text));
4178                    }
4179                }
4180            }
4181        }
4182
4183        let width_estimate = self.width_estimate(depth, &entry, cx);
4184        if Some(width_estimate)
4185            > state
4186                .max_width_estimate_and_index
4187                .map(|(estimate, _)| estimate)
4188        {
4189            state.max_width_estimate_and_index = Some((width_estimate, state.entries.len()));
4190        }
4191        state.entries.push(CachedEntry {
4192            depth,
4193            entry,
4194            string_match: None,
4195        });
4196    }
4197
4198    fn dir_names_string(&self, entries: &[GitEntry], worktree_id: WorktreeId, cx: &App) -> String {
4199        let dir_names_segment = entries
4200            .iter()
4201            .map(|entry| self.entry_name(&worktree_id, entry, cx))
4202            .collect::<PathBuf>();
4203        dir_names_segment.to_string_lossy().into_owned()
4204    }
4205
4206    fn query(&self, cx: &App) -> Option<String> {
4207        let query = self.filter_editor.read(cx).text(cx);
4208        if query.trim().is_empty() {
4209            None
4210        } else {
4211            Some(query)
4212        }
4213    }
4214
4215    fn is_expanded(&self, entry: &FsEntry) -> bool {
4216        let entry_to_check = match entry {
4217            FsEntry::ExternalFile(FsEntryExternalFile { buffer_id, .. }) => {
4218                CollapsedEntry::ExternalFile(*buffer_id)
4219            }
4220            FsEntry::File(FsEntryFile {
4221                worktree_id,
4222                buffer_id,
4223                ..
4224            }) => CollapsedEntry::File(*worktree_id, *buffer_id),
4225            FsEntry::Directory(FsEntryDirectory {
4226                worktree_id, entry, ..
4227            }) => CollapsedEntry::Dir(*worktree_id, entry.id),
4228        };
4229        !self.collapsed_entries.contains(&entry_to_check)
4230    }
4231
4232    fn update_non_fs_items(&mut self, window: &mut Window, cx: &mut Context<OutlinePanel>) -> bool {
4233        if !self.active {
4234            return false;
4235        }
4236
4237        let mut update_cached_items = false;
4238        update_cached_items |= self.update_search_matches(window, cx);
4239        self.fetch_outdated_outlines(window, cx);
4240        if update_cached_items {
4241            self.selected_entry.invalidate();
4242        }
4243        update_cached_items
4244    }
4245
4246    fn update_search_matches(
4247        &mut self,
4248        window: &mut Window,
4249        cx: &mut Context<OutlinePanel>,
4250    ) -> bool {
4251        if !self.active {
4252            return false;
4253        }
4254
4255        let project_search = self
4256            .active_item()
4257            .and_then(|item| item.downcast::<ProjectSearchView>());
4258        let project_search_matches = project_search
4259            .as_ref()
4260            .map(|project_search| project_search.read(cx).get_matches(cx))
4261            .unwrap_or_default();
4262
4263        let buffer_search = self
4264            .active_item()
4265            .as_deref()
4266            .and_then(|active_item| {
4267                self.workspace
4268                    .upgrade()
4269                    .and_then(|workspace| workspace.read(cx).pane_for(active_item))
4270            })
4271            .and_then(|pane| {
4272                pane.read(cx)
4273                    .toolbar()
4274                    .read(cx)
4275                    .item_of_type::<BufferSearchBar>()
4276            });
4277        let buffer_search_matches = self
4278            .active_editor()
4279            .map(|active_editor| {
4280                active_editor.update(cx, |editor, cx| editor.get_matches(window, cx).0)
4281            })
4282            .unwrap_or_default();
4283
4284        let mut update_cached_entries = false;
4285        if buffer_search_matches.is_empty() && project_search_matches.is_empty() {
4286            if matches!(self.mode, ItemsDisplayMode::Search(_)) {
4287                self.mode = ItemsDisplayMode::Outline;
4288                update_cached_entries = true;
4289            }
4290        } else {
4291            let (kind, new_search_matches, new_search_query) = if buffer_search_matches.is_empty() {
4292                (
4293                    SearchKind::Project,
4294                    project_search_matches,
4295                    project_search
4296                        .map(|project_search| project_search.read(cx).search_query_text(cx))
4297                        .unwrap_or_default(),
4298                )
4299            } else {
4300                (
4301                    SearchKind::Buffer,
4302                    buffer_search_matches,
4303                    buffer_search
4304                        .map(|buffer_search| buffer_search.read(cx).query(cx))
4305                        .unwrap_or_default(),
4306                )
4307            };
4308
4309            let mut previous_matches = HashMap::default();
4310            update_cached_entries = match &mut self.mode {
4311                ItemsDisplayMode::Search(current_search_state) => {
4312                    let update = current_search_state.query != new_search_query
4313                        || current_search_state.kind != kind
4314                        || current_search_state.matches.is_empty()
4315                        || current_search_state.matches.iter().enumerate().any(
4316                            |(i, (match_range, _))| new_search_matches.get(i) != Some(match_range),
4317                        );
4318                    if current_search_state.kind == kind {
4319                        previous_matches.extend(current_search_state.matches.drain(..));
4320                    }
4321                    update
4322                }
4323                ItemsDisplayMode::Outline => true,
4324            };
4325            self.mode = ItemsDisplayMode::Search(SearchState::new(
4326                kind,
4327                new_search_query,
4328                previous_matches,
4329                new_search_matches,
4330                cx.theme().syntax().clone(),
4331                window,
4332                cx,
4333            ));
4334        }
4335        update_cached_entries
4336    }
4337
4338    fn add_excerpt_entries(
4339        &mut self,
4340        state: &mut GenerationState,
4341        buffer_id: BufferId,
4342        entries_to_add: &[ExcerptId],
4343        parent_depth: usize,
4344        track_matches: bool,
4345        is_singleton: bool,
4346        query: Option<&str>,
4347        cx: &mut Context<Self>,
4348    ) {
4349        if let Some(excerpts) = self.excerpts.get(&buffer_id) {
4350            let buffer_snapshot = self.buffer_snapshot_for_id(buffer_id, cx);
4351
4352            for &excerpt_id in entries_to_add {
4353                let Some(excerpt) = excerpts.get(&excerpt_id) else {
4354                    continue;
4355                };
4356                let excerpt_depth = parent_depth + 1;
4357                self.push_entry(
4358                    state,
4359                    track_matches,
4360                    PanelEntry::Outline(OutlineEntry::Excerpt(OutlineEntryExcerpt {
4361                        buffer_id,
4362                        id: excerpt_id,
4363                        range: excerpt.range.clone(),
4364                    })),
4365                    excerpt_depth,
4366                    cx,
4367                );
4368
4369                let mut outline_base_depth = excerpt_depth + 1;
4370                if is_singleton {
4371                    outline_base_depth = 0;
4372                    state.clear();
4373                } else if query.is_none()
4374                    && self
4375                        .collapsed_entries
4376                        .contains(&CollapsedEntry::Excerpt(buffer_id, excerpt_id))
4377                {
4378                    continue;
4379                }
4380
4381                let mut last_depth_at_level: Vec<Option<Range<Anchor>>> = vec![None; 10];
4382
4383                let all_outlines: Vec<_> = excerpt.iter_outlines().collect();
4384
4385                let mut outline_has_children = HashMap::default();
4386                let mut visible_outlines = Vec::new();
4387                let mut collapsed_state: Option<(usize, Range<Anchor>)> = None;
4388
4389                for (i, &outline) in all_outlines.iter().enumerate() {
4390                    let has_children = all_outlines
4391                        .get(i + 1)
4392                        .map(|next| next.depth > outline.depth)
4393                        .unwrap_or(false);
4394
4395                    outline_has_children
4396                        .insert((outline.range.clone(), outline.depth), has_children);
4397
4398                    let mut should_include = true;
4399
4400                    if let Some((collapsed_depth, collapsed_range)) = &collapsed_state {
4401                        if outline.depth <= *collapsed_depth {
4402                            collapsed_state = None;
4403                        } else if let Some(buffer_snapshot) = buffer_snapshot.as_ref() {
4404                            let outline_start = outline.range.start;
4405                            if outline_start
4406                                .cmp(&collapsed_range.start, buffer_snapshot)
4407                                .is_ge()
4408                                && outline_start
4409                                    .cmp(&collapsed_range.end, buffer_snapshot)
4410                                    .is_lt()
4411                            {
4412                                should_include = false; // Skip - inside collapsed range
4413                            } else {
4414                                collapsed_state = None;
4415                            }
4416                        }
4417                    }
4418
4419                    // Check if this outline itself is collapsed
4420                    if should_include
4421                        && self.collapsed_entries.contains(&CollapsedEntry::Outline(
4422                            buffer_id,
4423                            excerpt_id,
4424                            outline.range.clone(),
4425                        ))
4426                    {
4427                        collapsed_state = Some((outline.depth, outline.range.clone()));
4428                    }
4429
4430                    if should_include {
4431                        visible_outlines.push(outline);
4432                    }
4433                }
4434
4435                self.outline_children_cache
4436                    .entry(buffer_id)
4437                    .or_default()
4438                    .extend(outline_has_children);
4439
4440                for outline in visible_outlines {
4441                    let outline_entry = OutlineEntryOutline {
4442                        buffer_id,
4443                        excerpt_id,
4444                        outline: outline.clone(),
4445                    };
4446
4447                    if outline.depth < last_depth_at_level.len() {
4448                        last_depth_at_level[outline.depth] = Some(outline.range.clone());
4449                        // Clear deeper levels when we go back to a shallower depth
4450                        for d in (outline.depth + 1)..last_depth_at_level.len() {
4451                            last_depth_at_level[d] = None;
4452                        }
4453                    }
4454
4455                    self.push_entry(
4456                        state,
4457                        track_matches,
4458                        PanelEntry::Outline(OutlineEntry::Outline(outline_entry)),
4459                        outline_base_depth + outline.depth,
4460                        cx,
4461                    );
4462                }
4463            }
4464        }
4465    }
4466
4467    fn add_search_entries(
4468        &mut self,
4469        state: &mut GenerationState,
4470        active_editor: &Entity<Editor>,
4471        parent_entry: FsEntry,
4472        parent_depth: usize,
4473        filter_query: Option<String>,
4474        is_singleton: bool,
4475        cx: &mut Context<Self>,
4476    ) {
4477        let ItemsDisplayMode::Search(search_state) = &mut self.mode else {
4478            return;
4479        };
4480
4481        let kind = search_state.kind;
4482        let related_excerpts = match &parent_entry {
4483            FsEntry::Directory(_) => return,
4484            FsEntry::ExternalFile(external) => &external.excerpts,
4485            FsEntry::File(file) => &file.excerpts,
4486        }
4487        .iter()
4488        .copied()
4489        .collect::<HashSet<_>>();
4490
4491        let depth = if is_singleton { 0 } else { parent_depth + 1 };
4492        let new_search_matches = search_state
4493            .matches
4494            .iter()
4495            .filter(|(match_range, _)| {
4496                related_excerpts.contains(&match_range.start.excerpt_id)
4497                    || related_excerpts.contains(&match_range.end.excerpt_id)
4498            })
4499            .filter(|(match_range, _)| {
4500                let editor = active_editor.read(cx);
4501                let snapshot = editor.buffer().read(cx).snapshot(cx);
4502                if let Some(buffer_id) = snapshot.buffer_id_for_anchor(match_range.start)
4503                    && editor.is_buffer_folded(buffer_id, cx)
4504                {
4505                    return false;
4506                }
4507                if let Some(buffer_id) = snapshot.buffer_id_for_anchor(match_range.end)
4508                    && editor.is_buffer_folded(buffer_id, cx)
4509                {
4510                    return false;
4511                }
4512                true
4513            });
4514
4515        let new_search_entries = new_search_matches
4516            .map(|(match_range, search_data)| SearchEntry {
4517                match_range: match_range.clone(),
4518                kind,
4519                render_data: Arc::clone(search_data),
4520            })
4521            .collect::<Vec<_>>();
4522        for new_search_entry in new_search_entries {
4523            self.push_entry(
4524                state,
4525                filter_query.is_some(),
4526                PanelEntry::Search(new_search_entry),
4527                depth,
4528                cx,
4529            );
4530        }
4531    }
4532
4533    fn active_editor(&self) -> Option<Entity<Editor>> {
4534        self.active_item.as_ref()?.active_editor.upgrade()
4535    }
4536
4537    fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
4538        self.active_item.as_ref()?.item_handle.upgrade()
4539    }
4540
4541    fn should_replace_active_item(&self, new_active_item: &dyn ItemHandle) -> bool {
4542        self.active_item().is_none_or(|active_item| {
4543            !self.pinned && active_item.item_id() != new_active_item.item_id()
4544        })
4545    }
4546
4547    pub fn toggle_active_editor_pin(
4548        &mut self,
4549        _: &ToggleActiveEditorPin,
4550        window: &mut Window,
4551        cx: &mut Context<Self>,
4552    ) {
4553        self.pinned = !self.pinned;
4554        if !self.pinned
4555            && let Some((active_item, active_editor)) = self
4556                .workspace
4557                .upgrade()
4558                .and_then(|workspace| workspace_active_editor(workspace.read(cx), cx))
4559            && self.should_replace_active_item(active_item.as_ref())
4560        {
4561            self.replace_active_editor(active_item, active_editor, window, cx);
4562        }
4563
4564        cx.notify();
4565    }
4566
4567    fn selected_entry(&self) -> Option<&PanelEntry> {
4568        match &self.selected_entry {
4569            SelectedEntry::Invalidated(entry) => entry.as_ref(),
4570            SelectedEntry::Valid(entry, _) => Some(entry),
4571            SelectedEntry::None => None,
4572        }
4573    }
4574
4575    fn select_entry(
4576        &mut self,
4577        entry: PanelEntry,
4578        focus: bool,
4579        window: &mut Window,
4580        cx: &mut Context<Self>,
4581    ) {
4582        if focus {
4583            self.focus_handle.focus(window, cx);
4584        }
4585        let ix = self
4586            .cached_entries
4587            .iter()
4588            .enumerate()
4589            .find(|(_, cached_entry)| &cached_entry.entry == &entry)
4590            .map(|(i, _)| i)
4591            .unwrap_or_default();
4592
4593        self.selected_entry = SelectedEntry::Valid(entry, ix);
4594
4595        self.autoscroll(cx);
4596        cx.notify();
4597    }
4598
4599    fn width_estimate(&self, depth: usize, entry: &PanelEntry, cx: &App) -> u64 {
4600        let item_text_chars = match entry {
4601            PanelEntry::Fs(FsEntry::ExternalFile(external)) => self
4602                .buffer_snapshot_for_id(external.buffer_id, cx)
4603                .and_then(|snapshot| Some(snapshot.file()?.path().file_name()?.len()))
4604                .unwrap_or_default(),
4605            PanelEntry::Fs(FsEntry::Directory(directory)) => directory
4606                .entry
4607                .path
4608                .file_name()
4609                .map(|name| name.len())
4610                .unwrap_or_default(),
4611            PanelEntry::Fs(FsEntry::File(file)) => file
4612                .entry
4613                .path
4614                .file_name()
4615                .map(|name| name.len())
4616                .unwrap_or_default(),
4617            PanelEntry::FoldedDirs(folded_dirs) => {
4618                folded_dirs
4619                    .entries
4620                    .iter()
4621                    .map(|dir| {
4622                        dir.path
4623                            .file_name()
4624                            .map(|name| name.len())
4625                            .unwrap_or_default()
4626                    })
4627                    .sum::<usize>()
4628                    + folded_dirs.entries.len().saturating_sub(1) * "/".len()
4629            }
4630            PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => self
4631                .excerpt_label(excerpt.buffer_id, &excerpt.range, cx)
4632                .map(|label| label.len())
4633                .unwrap_or_default(),
4634            PanelEntry::Outline(OutlineEntry::Outline(entry)) => entry.outline.text.len(),
4635            PanelEntry::Search(search) => search
4636                .render_data
4637                .get()
4638                .map(|data| data.context_text.len())
4639                .unwrap_or_default(),
4640        };
4641
4642        (item_text_chars + depth) as u64
4643    }
4644
4645    fn render_main_contents(
4646        &mut self,
4647        query: Option<String>,
4648        show_indent_guides: bool,
4649        indent_size: f32,
4650        window: &mut Window,
4651        cx: &mut Context<Self>,
4652    ) -> impl IntoElement {
4653        let contents = if self.cached_entries.is_empty() {
4654            let header = if query.is_some() {
4655                "No matches for query"
4656            } else {
4657                "No outlines available"
4658            };
4659
4660            v_flex()
4661                .id("empty-outline-state")
4662                .gap_0p5()
4663                .flex_1()
4664                .justify_center()
4665                .size_full()
4666                .child(h_flex().justify_center().child(Label::new(header)))
4667                .when_some(query, |panel, query| {
4668                    panel.child(
4669                        h_flex()
4670                            .px_0p5()
4671                            .justify_center()
4672                            .bg(cx.theme().colors().element_selected.opacity(0.2))
4673                            .child(Label::new(query)),
4674                    )
4675                })
4676                .child(h_flex().justify_center().child({
4677                    let keystroke = match self.position(window, cx) {
4678                        DockPosition::Left => window.keystroke_text_for(&workspace::ToggleLeftDock),
4679                        DockPosition::Bottom => {
4680                            window.keystroke_text_for(&workspace::ToggleBottomDock)
4681                        }
4682                        DockPosition::Right => {
4683                            window.keystroke_text_for(&workspace::ToggleRightDock)
4684                        }
4685                    };
4686                    Label::new(format!("Toggle Panel With {keystroke}")).color(Color::Muted)
4687                }))
4688        } else {
4689            let list_contents = {
4690                let items_len = self.cached_entries.len();
4691                let multi_buffer_snapshot = self
4692                    .active_editor()
4693                    .map(|editor| editor.read(cx).buffer().read(cx).snapshot(cx));
4694                uniform_list(
4695                    "entries",
4696                    items_len,
4697                    cx.processor(move |outline_panel, range: Range<usize>, window, cx| {
4698                        outline_panel.rendered_entries_len = range.end - range.start;
4699                        let entries = outline_panel.cached_entries.get(range);
4700                        entries
4701                            .map(|entries| entries.to_vec())
4702                            .unwrap_or_default()
4703                            .into_iter()
4704                            .filter_map(|cached_entry| match cached_entry.entry {
4705                                PanelEntry::Fs(entry) => Some(outline_panel.render_entry(
4706                                    &entry,
4707                                    cached_entry.depth,
4708                                    cached_entry.string_match.as_ref(),
4709                                    window,
4710                                    cx,
4711                                )),
4712                                PanelEntry::FoldedDirs(folded_dirs_entry) => {
4713                                    Some(outline_panel.render_folded_dirs(
4714                                        &folded_dirs_entry,
4715                                        cached_entry.depth,
4716                                        cached_entry.string_match.as_ref(),
4717                                        window,
4718                                        cx,
4719                                    ))
4720                                }
4721                                PanelEntry::Outline(OutlineEntry::Excerpt(excerpt)) => {
4722                                    outline_panel.render_excerpt(
4723                                        &excerpt,
4724                                        cached_entry.depth,
4725                                        window,
4726                                        cx,
4727                                    )
4728                                }
4729                                PanelEntry::Outline(OutlineEntry::Outline(entry)) => {
4730                                    Some(outline_panel.render_outline(
4731                                        &entry,
4732                                        cached_entry.depth,
4733                                        cached_entry.string_match.as_ref(),
4734                                        window,
4735                                        cx,
4736                                    ))
4737                                }
4738                                PanelEntry::Search(SearchEntry {
4739                                    match_range,
4740                                    render_data,
4741                                    kind,
4742                                    ..
4743                                }) => outline_panel.render_search_match(
4744                                    multi_buffer_snapshot.as_ref(),
4745                                    &match_range,
4746                                    &render_data,
4747                                    kind,
4748                                    cached_entry.depth,
4749                                    cached_entry.string_match.as_ref(),
4750                                    window,
4751                                    cx,
4752                                ),
4753                            })
4754                            .collect()
4755                    }),
4756                )
4757                .with_sizing_behavior(ListSizingBehavior::Infer)
4758                .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained)
4759                .with_width_from_item(self.max_width_item_index)
4760                .track_scroll(&self.scroll_handle)
4761                .when(show_indent_guides, |list| {
4762                    list.with_decoration(
4763                        ui::indent_guides(px(indent_size), IndentGuideColors::panel(cx))
4764                            .with_compute_indents_fn(cx.entity(), |outline_panel, range, _, _| {
4765                                let entries = outline_panel.cached_entries.get(range);
4766                                if let Some(entries) = entries {
4767                                    entries.iter().map(|item| item.depth).collect()
4768                                } else {
4769                                    smallvec::SmallVec::new()
4770                                }
4771                            })
4772                            .with_render_fn(cx.entity(), move |outline_panel, params, _, _| {
4773                                const LEFT_OFFSET: Pixels = px(14.);
4774
4775                                let indent_size = params.indent_size;
4776                                let item_height = params.item_height;
4777                                let active_indent_guide_ix = find_active_indent_guide_ix(
4778                                    outline_panel,
4779                                    &params.indent_guides,
4780                                );
4781
4782                                params
4783                                    .indent_guides
4784                                    .into_iter()
4785                                    .enumerate()
4786                                    .map(|(ix, layout)| {
4787                                        let bounds = Bounds::new(
4788                                            point(
4789                                                layout.offset.x * indent_size + LEFT_OFFSET,
4790                                                layout.offset.y * item_height,
4791                                            ),
4792                                            size(px(1.), layout.length * item_height),
4793                                        );
4794                                        ui::RenderedIndentGuide {
4795                                            bounds,
4796                                            layout,
4797                                            is_active: active_indent_guide_ix == Some(ix),
4798                                            hitbox: None,
4799                                        }
4800                                    })
4801                                    .collect()
4802                            }),
4803                    )
4804                })
4805            };
4806
4807            v_flex()
4808                .flex_shrink()
4809                .size_full()
4810                .child(list_contents.size_full().flex_shrink())
4811                .custom_scrollbars(
4812                    Scrollbars::for_settings::<OutlinePanelSettings>()
4813                        .tracked_scroll_handle(&self.scroll_handle.clone())
4814                        .with_track_along(
4815                            ScrollAxes::Horizontal,
4816                            cx.theme().colors().panel_background,
4817                        )
4818                        .tracked_entity(cx.entity_id()),
4819                    window,
4820                    cx,
4821                )
4822        }
4823        .children(self.context_menu.as_ref().map(|(menu, position, _)| {
4824            deferred(
4825                anchored()
4826                    .position(*position)
4827                    .anchor(gpui::Corner::TopLeft)
4828                    .child(menu.clone()),
4829            )
4830            .with_priority(1)
4831        }));
4832
4833        v_flex().w_full().flex_1().overflow_hidden().child(contents)
4834    }
4835
4836    fn render_filter_footer(&mut self, pinned: bool, cx: &mut Context<Self>) -> Div {
4837        let (icon, icon_tooltip) = if pinned {
4838            (IconName::Unpin, "Unpin Outline")
4839        } else {
4840            (IconName::Pin, "Pin Active Outline")
4841        };
4842
4843        let has_query = self.query(cx).is_some();
4844
4845        h_flex()
4846            .p_2()
4847            .h(Tab::container_height(cx))
4848            .justify_between()
4849            .border_b_1()
4850            .border_color(cx.theme().colors().border)
4851            .child(
4852                h_flex()
4853                    .w_full()
4854                    .gap_1p5()
4855                    .child(
4856                        Icon::new(IconName::MagnifyingGlass)
4857                            .size(IconSize::Small)
4858                            .color(Color::Muted),
4859                    )
4860                    .child(self.filter_editor.clone()),
4861            )
4862            .child(
4863                h_flex()
4864                    .when(has_query, |this| {
4865                        this.child(
4866                            IconButton::new("clear_filter", IconName::Close)
4867                                .shape(IconButtonShape::Square)
4868                                .tooltip(Tooltip::text("Clear Filter"))
4869                                .on_click(cx.listener(|outline_panel, _, window, cx| {
4870                                    outline_panel.filter_editor.update(cx, |editor, cx| {
4871                                        editor.set_text("", window, cx);
4872                                    });
4873                                    cx.notify();
4874                                })),
4875                        )
4876                    })
4877                    .child(
4878                        IconButton::new("pin_button", icon)
4879                            .tooltip(Tooltip::text(icon_tooltip))
4880                            .shape(IconButtonShape::Square)
4881                            .on_click(cx.listener(|outline_panel, _, window, cx| {
4882                                outline_panel.toggle_active_editor_pin(
4883                                    &ToggleActiveEditorPin,
4884                                    window,
4885                                    cx,
4886                                );
4887                            })),
4888                    ),
4889            )
4890    }
4891
4892    fn buffers_inside_directory(
4893        &self,
4894        dir_worktree: WorktreeId,
4895        dir_entry: &GitEntry,
4896    ) -> HashSet<BufferId> {
4897        if !dir_entry.is_dir() {
4898            debug_panic!("buffers_inside_directory called on a non-directory entry {dir_entry:?}");
4899            return HashSet::default();
4900        }
4901
4902        self.fs_entries
4903            .iter()
4904            .skip_while(|fs_entry| match fs_entry {
4905                FsEntry::Directory(directory) => {
4906                    directory.worktree_id != dir_worktree || &directory.entry != dir_entry
4907                }
4908                _ => true,
4909            })
4910            .skip(1)
4911            .take_while(|fs_entry| match fs_entry {
4912                FsEntry::ExternalFile(..) => false,
4913                FsEntry::Directory(directory) => {
4914                    directory.worktree_id == dir_worktree
4915                        && directory.entry.path.starts_with(&dir_entry.path)
4916                }
4917                FsEntry::File(file) => {
4918                    file.worktree_id == dir_worktree && file.entry.path.starts_with(&dir_entry.path)
4919                }
4920            })
4921            .filter_map(|fs_entry| match fs_entry {
4922                FsEntry::File(file) => Some(file.buffer_id),
4923                _ => None,
4924            })
4925            .collect()
4926    }
4927}
4928
4929fn workspace_active_editor(
4930    workspace: &Workspace,
4931    cx: &App,
4932) -> Option<(Box<dyn ItemHandle>, Entity<Editor>)> {
4933    let active_item = workspace.active_item(cx)?;
4934    let active_editor = active_item
4935        .act_as::<Editor>(cx)
4936        .filter(|editor| editor.read(cx).mode().is_full())?;
4937    Some((active_item, active_editor))
4938}
4939
4940fn back_to_common_visited_parent(
4941    visited_dirs: &mut Vec<(ProjectEntryId, Arc<RelPath>)>,
4942    worktree_id: &WorktreeId,
4943    new_entry: &Entry,
4944) -> Option<(WorktreeId, ProjectEntryId)> {
4945    while let Some((visited_dir_id, visited_path)) = visited_dirs.last() {
4946        match new_entry.path.parent() {
4947            Some(parent_path) => {
4948                if parent_path == visited_path.as_ref() {
4949                    return Some((*worktree_id, *visited_dir_id));
4950                }
4951            }
4952            None => {
4953                break;
4954            }
4955        }
4956        visited_dirs.pop();
4957    }
4958    None
4959}
4960
4961fn file_name(path: &Path) -> String {
4962    let mut current_path = path;
4963    loop {
4964        if let Some(file_name) = current_path.file_name() {
4965            return file_name.to_string_lossy().into_owned();
4966        }
4967        match current_path.parent() {
4968            Some(parent) => current_path = parent,
4969            None => return path.to_string_lossy().into_owned(),
4970        }
4971    }
4972}
4973
4974impl Panel for OutlinePanel {
4975    fn persistent_name() -> &'static str {
4976        "Outline Panel"
4977    }
4978
4979    fn panel_key() -> &'static str {
4980        OUTLINE_PANEL_KEY
4981    }
4982
4983    fn position(&self, _: &Window, cx: &App) -> DockPosition {
4984        match OutlinePanelSettings::get_global(cx).dock {
4985            DockSide::Left => DockPosition::Left,
4986            DockSide::Right => DockPosition::Right,
4987        }
4988    }
4989
4990    fn position_is_valid(&self, position: DockPosition) -> bool {
4991        matches!(position, DockPosition::Left | DockPosition::Right)
4992    }
4993
4994    fn set_position(&mut self, position: DockPosition, _: &mut Window, cx: &mut Context<Self>) {
4995        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
4996            let dock = match position {
4997                DockPosition::Left | DockPosition::Bottom => DockSide::Left,
4998                DockPosition::Right => DockSide::Right,
4999            };
5000            settings.outline_panel.get_or_insert_default().dock = Some(dock);
5001        });
5002    }
5003
5004    fn size(&self, _: &Window, cx: &App) -> Pixels {
5005        self.width
5006            .unwrap_or_else(|| OutlinePanelSettings::get_global(cx).default_width)
5007    }
5008
5009    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
5010        self.width = size;
5011        cx.notify();
5012        cx.defer_in(window, |this, _, cx| {
5013            this.serialize(cx);
5014        });
5015    }
5016
5017    fn icon(&self, _: &Window, cx: &App) -> Option<IconName> {
5018        OutlinePanelSettings::get_global(cx)
5019            .button
5020            .then_some(IconName::ListTree)
5021    }
5022
5023    fn icon_tooltip(&self, _window: &Window, _: &App) -> Option<&'static str> {
5024        Some("Outline Panel")
5025    }
5026
5027    fn toggle_action(&self) -> Box<dyn Action> {
5028        Box::new(ToggleFocus)
5029    }
5030
5031    fn starts_open(&self, _window: &Window, _: &App) -> bool {
5032        self.active
5033    }
5034
5035    fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
5036        cx.spawn_in(window, async move |outline_panel, cx| {
5037            outline_panel
5038                .update_in(cx, |outline_panel, window, cx| {
5039                    let old_active = outline_panel.active;
5040                    outline_panel.active = active;
5041                    if old_active != active {
5042                        if active
5043                            && let Some((active_item, active_editor)) =
5044                                outline_panel.workspace.upgrade().and_then(|workspace| {
5045                                    workspace_active_editor(workspace.read(cx), cx)
5046                                })
5047                        {
5048                            if outline_panel.should_replace_active_item(active_item.as_ref()) {
5049                                outline_panel.replace_active_editor(
5050                                    active_item,
5051                                    active_editor,
5052                                    window,
5053                                    cx,
5054                                );
5055                            } else {
5056                                outline_panel.update_fs_entries(active_editor, None, window, cx)
5057                            }
5058                            return;
5059                        }
5060
5061                        if !outline_panel.pinned {
5062                            outline_panel.clear_previous(window, cx);
5063                        }
5064                    }
5065                    outline_panel.serialize(cx);
5066                })
5067                .ok();
5068        })
5069        .detach()
5070    }
5071
5072    fn activation_priority(&self) -> u32 {
5073        5
5074    }
5075}
5076
5077impl Focusable for OutlinePanel {
5078    fn focus_handle(&self, cx: &App) -> FocusHandle {
5079        self.filter_editor.focus_handle(cx)
5080    }
5081}
5082
5083impl EventEmitter<Event> for OutlinePanel {}
5084
5085impl EventEmitter<PanelEvent> for OutlinePanel {}
5086
5087impl Render for OutlinePanel {
5088    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5089        let (is_local, is_via_ssh) = self.project.read_with(cx, |project, _| {
5090            (project.is_local(), project.is_via_remote_server())
5091        });
5092        let query = self.query(cx);
5093        let pinned = self.pinned;
5094        let settings = OutlinePanelSettings::get_global(cx);
5095        let indent_size = settings.indent_size;
5096        let show_indent_guides = settings.indent_guides.show == ShowIndentGuides::Always;
5097
5098        let search_query = match &self.mode {
5099            ItemsDisplayMode::Search(search_query) => Some(search_query),
5100            _ => None,
5101        };
5102
5103        let search_query_text = search_query.map(|sq| sq.query.to_string());
5104
5105        v_flex()
5106            .id("outline-panel")
5107            .size_full()
5108            .overflow_hidden()
5109            .relative()
5110            .key_context(self.dispatch_context(window, cx))
5111            .on_action(cx.listener(Self::open_selected_entry))
5112            .on_action(cx.listener(Self::cancel))
5113            .on_action(cx.listener(Self::scroll_up))
5114            .on_action(cx.listener(Self::scroll_down))
5115            .on_action(cx.listener(Self::select_next))
5116            .on_action(cx.listener(Self::scroll_cursor_center))
5117            .on_action(cx.listener(Self::scroll_cursor_top))
5118            .on_action(cx.listener(Self::scroll_cursor_bottom))
5119            .on_action(cx.listener(Self::select_previous))
5120            .on_action(cx.listener(Self::select_first))
5121            .on_action(cx.listener(Self::select_last))
5122            .on_action(cx.listener(Self::select_parent))
5123            .on_action(cx.listener(Self::expand_selected_entry))
5124            .on_action(cx.listener(Self::collapse_selected_entry))
5125            .on_action(cx.listener(Self::expand_all_entries))
5126            .on_action(cx.listener(Self::collapse_all_entries))
5127            .on_action(cx.listener(Self::copy_path))
5128            .on_action(cx.listener(Self::copy_relative_path))
5129            .on_action(cx.listener(Self::toggle_active_editor_pin))
5130            .on_action(cx.listener(Self::unfold_directory))
5131            .on_action(cx.listener(Self::fold_directory))
5132            .on_action(cx.listener(Self::open_excerpts))
5133            .on_action(cx.listener(Self::open_excerpts_split))
5134            .when(is_local, |el| {
5135                el.on_action(cx.listener(Self::reveal_in_finder))
5136            })
5137            .when(is_local || is_via_ssh, |el| {
5138                el.on_action(cx.listener(Self::open_in_terminal))
5139            })
5140            .on_mouse_down(
5141                MouseButton::Right,
5142                cx.listener(move |outline_panel, event: &MouseDownEvent, window, cx| {
5143                    if let Some(entry) = outline_panel.selected_entry().cloned() {
5144                        outline_panel.deploy_context_menu(event.position, entry, window, cx)
5145                    } else if let Some(entry) = outline_panel.fs_entries.first().cloned() {
5146                        outline_panel.deploy_context_menu(
5147                            event.position,
5148                            PanelEntry::Fs(entry),
5149                            window,
5150                            cx,
5151                        )
5152                    }
5153                }),
5154            )
5155            .track_focus(&self.focus_handle)
5156            .child(self.render_filter_footer(pinned, cx))
5157            .when_some(search_query_text, |outline_panel, query_text| {
5158                outline_panel.child(
5159                    h_flex()
5160                        .py_1p5()
5161                        .px_2()
5162                        .h(Tab::container_height(cx))
5163                        .gap_0p5()
5164                        .border_b_1()
5165                        .border_color(cx.theme().colors().border_variant)
5166                        .child(Label::new("Searching:").color(Color::Muted))
5167                        .child(Label::new(query_text)),
5168                )
5169            })
5170            .child(self.render_main_contents(query, show_indent_guides, indent_size, window, cx))
5171    }
5172}
5173
5174fn find_active_indent_guide_ix(
5175    outline_panel: &OutlinePanel,
5176    candidates: &[IndentGuideLayout],
5177) -> Option<usize> {
5178    let SelectedEntry::Valid(_, target_ix) = &outline_panel.selected_entry else {
5179        return None;
5180    };
5181    let target_depth = outline_panel
5182        .cached_entries
5183        .get(*target_ix)
5184        .map(|cached_entry| cached_entry.depth)?;
5185
5186    let (target_ix, target_depth) = if let Some(target_depth) = outline_panel
5187        .cached_entries
5188        .get(target_ix + 1)
5189        .filter(|cached_entry| cached_entry.depth > target_depth)
5190        .map(|entry| entry.depth)
5191    {
5192        (target_ix + 1, target_depth.saturating_sub(1))
5193    } else {
5194        (*target_ix, target_depth.saturating_sub(1))
5195    };
5196
5197    candidates
5198        .iter()
5199        .enumerate()
5200        .find(|(_, guide)| {
5201            guide.offset.y <= target_ix
5202                && target_ix < guide.offset.y + guide.length
5203                && guide.offset.x == target_depth
5204        })
5205        .map(|(ix, _)| ix)
5206}
5207
5208fn subscribe_for_editor_events(
5209    editor: &Entity<Editor>,
5210    window: &mut Window,
5211    cx: &mut Context<OutlinePanel>,
5212) -> Subscription {
5213    let debounce = Some(UPDATE_DEBOUNCE);
5214    cx.subscribe_in(
5215        editor,
5216        window,
5217        move |outline_panel, editor, e: &EditorEvent, window, cx| {
5218            if !outline_panel.active {
5219                return;
5220            }
5221            match e {
5222                EditorEvent::SelectionsChanged { local: true } => {
5223                    outline_panel.reveal_entry_for_selection(editor.clone(), window, cx);
5224                    cx.notify();
5225                }
5226                EditorEvent::ExcerptsAdded { excerpts, .. } => {
5227                    outline_panel
5228                        .new_entries_for_fs_update
5229                        .extend(excerpts.iter().map(|&(excerpt_id, _)| excerpt_id));
5230                    outline_panel.update_fs_entries(editor.clone(), debounce, window, cx);
5231                }
5232                EditorEvent::ExcerptsRemoved { ids, .. } => {
5233                    let mut ids = ids.iter().collect::<HashSet<_>>();
5234                    for excerpts in outline_panel.excerpts.values_mut() {
5235                        excerpts.retain(|excerpt_id, _| !ids.remove(excerpt_id));
5236                        if ids.is_empty() {
5237                            break;
5238                        }
5239                    }
5240                    outline_panel.update_fs_entries(editor.clone(), debounce, window, cx);
5241                }
5242                EditorEvent::ExcerptsExpanded { ids } => {
5243                    outline_panel.invalidate_outlines(ids);
5244                    let update_cached_items = outline_panel.update_non_fs_items(window, cx);
5245                    if update_cached_items {
5246                        outline_panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
5247                    }
5248                }
5249                EditorEvent::ExcerptsEdited { ids } => {
5250                    outline_panel.invalidate_outlines(ids);
5251                    let update_cached_items = outline_panel.update_non_fs_items(window, cx);
5252                    if update_cached_items {
5253                        outline_panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
5254                    }
5255                }
5256                EditorEvent::BufferFoldToggled { ids, .. } => {
5257                    outline_panel.invalidate_outlines(ids);
5258                    let mut latest_unfolded_buffer_id = None;
5259                    let mut latest_folded_buffer_id = None;
5260                    let mut ignore_selections_change = false;
5261                    outline_panel.new_entries_for_fs_update.extend(
5262                        ids.iter()
5263                            .filter(|id| {
5264                                outline_panel
5265                                    .excerpts
5266                                    .iter()
5267                                    .find_map(|(buffer_id, excerpts)| {
5268                                        if excerpts.contains_key(id) {
5269                                            ignore_selections_change |= outline_panel
5270                                                .preserve_selection_on_buffer_fold_toggles
5271                                                .remove(buffer_id);
5272                                            Some(buffer_id)
5273                                        } else {
5274                                            None
5275                                        }
5276                                    })
5277                                    .map(|buffer_id| {
5278                                        if editor.read(cx).is_buffer_folded(*buffer_id, cx) {
5279                                            latest_folded_buffer_id = Some(*buffer_id);
5280                                            false
5281                                        } else {
5282                                            latest_unfolded_buffer_id = Some(*buffer_id);
5283                                            true
5284                                        }
5285                                    })
5286                                    .unwrap_or(true)
5287                            })
5288                            .copied(),
5289                    );
5290                    if !ignore_selections_change
5291                        && let Some(entry_to_select) = latest_unfolded_buffer_id
5292                            .or(latest_folded_buffer_id)
5293                            .and_then(|toggled_buffer_id| {
5294                                outline_panel.fs_entries.iter().find_map(
5295                                    |fs_entry| match fs_entry {
5296                                        FsEntry::ExternalFile(external) => {
5297                                            if external.buffer_id == toggled_buffer_id {
5298                                                Some(fs_entry.clone())
5299                                            } else {
5300                                                None
5301                                            }
5302                                        }
5303                                        FsEntry::File(FsEntryFile { buffer_id, .. }) => {
5304                                            if *buffer_id == toggled_buffer_id {
5305                                                Some(fs_entry.clone())
5306                                            } else {
5307                                                None
5308                                            }
5309                                        }
5310                                        FsEntry::Directory(..) => None,
5311                                    },
5312                                )
5313                            })
5314                            .map(PanelEntry::Fs)
5315                    {
5316                        outline_panel.select_entry(entry_to_select, true, window, cx);
5317                    }
5318
5319                    outline_panel.update_fs_entries(editor.clone(), debounce, window, cx);
5320                }
5321                EditorEvent::Reparsed(buffer_id) => {
5322                    if let Some(excerpts) = outline_panel.excerpts.get_mut(buffer_id) {
5323                        for excerpt in excerpts.values_mut() {
5324                            excerpt.invalidate_outlines();
5325                        }
5326                    }
5327                    let update_cached_items = outline_panel.update_non_fs_items(window, cx);
5328                    if update_cached_items {
5329                        outline_panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
5330                    }
5331                }
5332                EditorEvent::OutlineSymbolsChanged => {
5333                    for excerpts in outline_panel.excerpts.values_mut() {
5334                        for excerpt in excerpts.values_mut() {
5335                            excerpt.invalidate_outlines();
5336                        }
5337                    }
5338                    if matches!(
5339                        outline_panel.selected_entry(),
5340                        Some(PanelEntry::Outline(..)),
5341                    ) {
5342                        outline_panel.selected_entry.invalidate();
5343                    }
5344                    if outline_panel.update_non_fs_items(window, cx) {
5345                        outline_panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
5346                    }
5347                }
5348                EditorEvent::TitleChanged => {
5349                    outline_panel.update_fs_entries(editor.clone(), debounce, window, cx);
5350                }
5351                _ => {}
5352            }
5353        },
5354    )
5355}
5356
5357fn empty_icon() -> AnyElement {
5358    h_flex()
5359        .size(IconSize::default().rems())
5360        .invisible()
5361        .flex_none()
5362        .into_any_element()
5363}
5364
5365#[derive(Debug, Default)]
5366struct GenerationState {
5367    entries: Vec<CachedEntry>,
5368    match_candidates: Vec<StringMatchCandidate>,
5369    max_width_estimate_and_index: Option<(u64, usize)>,
5370}
5371
5372impl GenerationState {
5373    fn clear(&mut self) {
5374        self.entries.clear();
5375        self.match_candidates.clear();
5376        self.max_width_estimate_and_index = None;
5377    }
5378}
5379
5380#[cfg(test)]
5381mod tests {
5382    use db::indoc;
5383    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext, WindowHandle};
5384    use language::{self, FakeLspAdapter, rust_lang};
5385    use pretty_assertions::assert_eq;
5386    use project::FakeFs;
5387    use search::{
5388        buffer_search,
5389        project_search::{self, perform_project_search},
5390    };
5391    use serde_json::json;
5392    use smol::stream::StreamExt as _;
5393    use util::path;
5394    use workspace::{MultiWorkspace, OpenOptions, OpenVisible, ToolbarItemView};
5395
5396    use super::*;
5397
5398    const SELECTED_MARKER: &str = "  <==== selected";
5399
5400    #[gpui::test(iterations = 10)]
5401    async fn test_project_search_results_toggling(cx: &mut TestAppContext) {
5402        init_test(cx);
5403
5404        let fs = FakeFs::new(cx.background_executor.clone());
5405        let root = path!("/rust-analyzer");
5406        populate_with_test_ra_project(&fs, root).await;
5407        let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
5408        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
5409        let (window, workspace) = add_outline_panel(&project, cx).await;
5410        let cx = &mut VisualTestContext::from_window(window.into(), cx);
5411        let outline_panel = outline_panel(&workspace, cx);
5412        outline_panel.update_in(cx, |outline_panel, window, cx| {
5413            outline_panel.set_active(true, window, cx)
5414        });
5415
5416        workspace.update_in(cx, |workspace, window, cx| {
5417            ProjectSearchView::deploy_search(
5418                workspace,
5419                &workspace::DeploySearch::default(),
5420                window,
5421                cx,
5422            )
5423        });
5424        let search_view = workspace.update_in(cx, |workspace, _window, cx| {
5425            workspace
5426                .active_pane()
5427                .read(cx)
5428                .items()
5429                .find_map(|item| item.downcast::<ProjectSearchView>())
5430                .expect("Project search view expected to appear after new search event trigger")
5431        });
5432
5433        let query = "param_names_for_lifetime_elision_hints";
5434        perform_project_search(&search_view, query, cx);
5435        search_view.update(cx, |search_view, cx| {
5436            search_view
5437                .results_editor()
5438                .update(cx, |results_editor, cx| {
5439                    assert_eq!(
5440                        results_editor.display_text(cx).match_indices(query).count(),
5441                        9
5442                    );
5443                });
5444        });
5445
5446        let all_matches = r#"rust-analyzer/
5447  crates/
5448    ide/src/
5449      inlay_hints/
5450        fn_lifetime_fn.rs
5451          search: match config.«param_names_for_lifetime_elision_hints» {
5452          search: allocated_lifetimes.push(if config.«param_names_for_lifetime_elision_hints» {
5453          search: Some(it) if config.«param_names_for_lifetime_elision_hints» => {
5454          search: InlayHintsConfig { «param_names_for_lifetime_elision_hints»: true, ..TEST_CONFIG },
5455      inlay_hints.rs
5456        search: pub «param_names_for_lifetime_elision_hints»: bool,
5457        search: «param_names_for_lifetime_elision_hints»: self
5458      static_index.rs
5459        search: «param_names_for_lifetime_elision_hints»: false,
5460    rust-analyzer/src/
5461      cli/
5462        analysis_stats.rs
5463          search: «param_names_for_lifetime_elision_hints»: true,
5464      config.rs
5465        search: «param_names_for_lifetime_elision_hints»: self"#
5466            .to_string();
5467
5468        let select_first_in_all_matches = |line_to_select: &str| {
5469            assert!(
5470                all_matches.contains(line_to_select),
5471                "`{line_to_select}` was not found in all matches `{all_matches}`"
5472            );
5473            all_matches.replacen(
5474                line_to_select,
5475                &format!("{line_to_select}{SELECTED_MARKER}"),
5476                1,
5477            )
5478        };
5479
5480        cx.executor()
5481            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5482        cx.run_until_parked();
5483        outline_panel.update(cx, |outline_panel, cx| {
5484            assert_eq!(
5485                display_entries(
5486                    &project,
5487                    &snapshot(outline_panel, cx),
5488                    &outline_panel.cached_entries,
5489                    outline_panel.selected_entry(),
5490                    cx,
5491                ),
5492                select_first_in_all_matches(
5493                    "search: match config.«param_names_for_lifetime_elision_hints» {"
5494                )
5495            );
5496        });
5497
5498        outline_panel.update_in(cx, |outline_panel, window, cx| {
5499            outline_panel.select_parent(&SelectParent, window, cx);
5500            assert_eq!(
5501                display_entries(
5502                    &project,
5503                    &snapshot(outline_panel, cx),
5504                    &outline_panel.cached_entries,
5505                    outline_panel.selected_entry(),
5506                    cx,
5507                ),
5508                select_first_in_all_matches("fn_lifetime_fn.rs")
5509            );
5510        });
5511        outline_panel.update_in(cx, |outline_panel, window, cx| {
5512            outline_panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx);
5513        });
5514        cx.executor()
5515            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5516        cx.run_until_parked();
5517        outline_panel.update(cx, |outline_panel, cx| {
5518            assert_eq!(
5519                display_entries(
5520                    &project,
5521                    &snapshot(outline_panel, cx),
5522                    &outline_panel.cached_entries,
5523                    outline_panel.selected_entry(),
5524                    cx,
5525                ),
5526                format!(
5527                    r#"rust-analyzer/
5528  crates/
5529    ide/src/
5530      inlay_hints/
5531        fn_lifetime_fn.rs{SELECTED_MARKER}
5532      inlay_hints.rs
5533        search: pub «param_names_for_lifetime_elision_hints»: bool,
5534        search: «param_names_for_lifetime_elision_hints»: self
5535      static_index.rs
5536        search: «param_names_for_lifetime_elision_hints»: false,
5537    rust-analyzer/src/
5538      cli/
5539        analysis_stats.rs
5540          search: «param_names_for_lifetime_elision_hints»: true,
5541      config.rs
5542        search: «param_names_for_lifetime_elision_hints»: self"#,
5543                )
5544            );
5545        });
5546
5547        outline_panel.update_in(cx, |outline_panel, window, cx| {
5548            outline_panel.expand_all_entries(&ExpandAllEntries, window, cx);
5549        });
5550        cx.executor()
5551            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5552        cx.run_until_parked();
5553        outline_panel.update_in(cx, |outline_panel, window, cx| {
5554            outline_panel.select_parent(&SelectParent, window, cx);
5555            assert_eq!(
5556                display_entries(
5557                    &project,
5558                    &snapshot(outline_panel, cx),
5559                    &outline_panel.cached_entries,
5560                    outline_panel.selected_entry(),
5561                    cx,
5562                ),
5563                select_first_in_all_matches("inlay_hints/")
5564            );
5565        });
5566
5567        outline_panel.update_in(cx, |outline_panel, window, cx| {
5568            outline_panel.select_parent(&SelectParent, window, cx);
5569            assert_eq!(
5570                display_entries(
5571                    &project,
5572                    &snapshot(outline_panel, cx),
5573                    &outline_panel.cached_entries,
5574                    outline_panel.selected_entry(),
5575                    cx,
5576                ),
5577                select_first_in_all_matches("ide/src/")
5578            );
5579        });
5580
5581        outline_panel.update_in(cx, |outline_panel, window, cx| {
5582            outline_panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx);
5583        });
5584        cx.executor()
5585            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5586        cx.run_until_parked();
5587        outline_panel.update(cx, |outline_panel, cx| {
5588            assert_eq!(
5589                display_entries(
5590                    &project,
5591                    &snapshot(outline_panel, cx),
5592                    &outline_panel.cached_entries,
5593                    outline_panel.selected_entry(),
5594                    cx,
5595                ),
5596                format!(
5597                    r#"rust-analyzer/
5598  crates/
5599    ide/src/{SELECTED_MARKER}
5600    rust-analyzer/src/
5601      cli/
5602        analysis_stats.rs
5603          search: «param_names_for_lifetime_elision_hints»: true,
5604      config.rs
5605        search: «param_names_for_lifetime_elision_hints»: self"#,
5606                )
5607            );
5608        });
5609        outline_panel.update_in(cx, |outline_panel, window, cx| {
5610            outline_panel.expand_selected_entry(&ExpandSelectedEntry, window, cx);
5611        });
5612        cx.executor()
5613            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5614        cx.run_until_parked();
5615        outline_panel.update(cx, |outline_panel, cx| {
5616            assert_eq!(
5617                display_entries(
5618                    &project,
5619                    &snapshot(outline_panel, cx),
5620                    &outline_panel.cached_entries,
5621                    outline_panel.selected_entry(),
5622                    cx,
5623                ),
5624                select_first_in_all_matches("ide/src/")
5625            );
5626        });
5627    }
5628
5629    #[gpui::test(iterations = 10)]
5630    async fn test_item_filtering(cx: &mut TestAppContext) {
5631        init_test(cx);
5632
5633        let fs = FakeFs::new(cx.background_executor.clone());
5634        let root = path!("/rust-analyzer");
5635        populate_with_test_ra_project(&fs, root).await;
5636        let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
5637        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
5638        let (window, workspace) = add_outline_panel(&project, cx).await;
5639        let cx = &mut VisualTestContext::from_window(window.into(), cx);
5640        let outline_panel = outline_panel(&workspace, cx);
5641        outline_panel.update_in(cx, |outline_panel, window, cx| {
5642            outline_panel.set_active(true, window, cx)
5643        });
5644
5645        workspace.update_in(cx, |workspace, window, cx| {
5646            ProjectSearchView::deploy_search(
5647                workspace,
5648                &workspace::DeploySearch::default(),
5649                window,
5650                cx,
5651            )
5652        });
5653        let search_view = workspace.update_in(cx, |workspace, _window, cx| {
5654            workspace
5655                .active_pane()
5656                .read(cx)
5657                .items()
5658                .find_map(|item| item.downcast::<ProjectSearchView>())
5659                .expect("Project search view expected to appear after new search event trigger")
5660        });
5661
5662        let query = "param_names_for_lifetime_elision_hints";
5663        perform_project_search(&search_view, query, cx);
5664        search_view.update(cx, |search_view, cx| {
5665            search_view
5666                .results_editor()
5667                .update(cx, |results_editor, cx| {
5668                    assert_eq!(
5669                        results_editor.display_text(cx).match_indices(query).count(),
5670                        9
5671                    );
5672                });
5673        });
5674        let all_matches = r#"rust-analyzer/
5675  crates/
5676    ide/src/
5677      inlay_hints/
5678        fn_lifetime_fn.rs
5679          search: match config.«param_names_for_lifetime_elision_hints» {
5680          search: allocated_lifetimes.push(if config.«param_names_for_lifetime_elision_hints» {
5681          search: Some(it) if config.«param_names_for_lifetime_elision_hints» => {
5682          search: InlayHintsConfig { «param_names_for_lifetime_elision_hints»: true, ..TEST_CONFIG },
5683      inlay_hints.rs
5684        search: pub «param_names_for_lifetime_elision_hints»: bool,
5685        search: «param_names_for_lifetime_elision_hints»: self
5686      static_index.rs
5687        search: «param_names_for_lifetime_elision_hints»: false,
5688    rust-analyzer/src/
5689      cli/
5690        analysis_stats.rs
5691          search: «param_names_for_lifetime_elision_hints»: true,
5692      config.rs
5693        search: «param_names_for_lifetime_elision_hints»: self"#
5694            .to_string();
5695
5696        cx.executor()
5697            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5698        cx.run_until_parked();
5699        outline_panel.update(cx, |outline_panel, cx| {
5700            assert_eq!(
5701                display_entries(
5702                    &project,
5703                    &snapshot(outline_panel, cx),
5704                    &outline_panel.cached_entries,
5705                    None,
5706                    cx,
5707                ),
5708                all_matches,
5709            );
5710        });
5711
5712        let filter_text = "a";
5713        outline_panel.update_in(cx, |outline_panel, window, cx| {
5714            outline_panel.filter_editor.update(cx, |filter_editor, cx| {
5715                filter_editor.set_text(filter_text, window, cx);
5716            });
5717        });
5718        cx.executor()
5719            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5720        cx.run_until_parked();
5721
5722        outline_panel.update(cx, |outline_panel, cx| {
5723            assert_eq!(
5724                display_entries(
5725                    &project,
5726                    &snapshot(outline_panel, cx),
5727                    &outline_panel.cached_entries,
5728                    None,
5729                    cx,
5730                ),
5731                all_matches
5732                    .lines()
5733                    .skip(1) // `/rust-analyzer/` is a root entry with path `` and it will be filtered out
5734                    .filter(|item| item.contains(filter_text))
5735                    .collect::<Vec<_>>()
5736                    .join("\n"),
5737            );
5738        });
5739
5740        outline_panel.update_in(cx, |outline_panel, window, cx| {
5741            outline_panel.filter_editor.update(cx, |filter_editor, cx| {
5742                filter_editor.set_text("", window, cx);
5743            });
5744        });
5745        cx.executor()
5746            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5747        cx.run_until_parked();
5748        outline_panel.update(cx, |outline_panel, cx| {
5749            assert_eq!(
5750                display_entries(
5751                    &project,
5752                    &snapshot(outline_panel, cx),
5753                    &outline_panel.cached_entries,
5754                    None,
5755                    cx,
5756                ),
5757                all_matches,
5758            );
5759        });
5760    }
5761
5762    #[gpui::test(iterations = 10)]
5763    async fn test_item_opening(cx: &mut TestAppContext) {
5764        init_test(cx);
5765
5766        let fs = FakeFs::new(cx.background_executor.clone());
5767        let root = path!("/rust-analyzer");
5768        populate_with_test_ra_project(&fs, root).await;
5769        let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
5770        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
5771        let (window, workspace) = add_outline_panel(&project, cx).await;
5772        let cx = &mut VisualTestContext::from_window(window.into(), cx);
5773        let outline_panel = outline_panel(&workspace, cx);
5774        outline_panel.update_in(cx, |outline_panel, window, cx| {
5775            outline_panel.set_active(true, window, cx)
5776        });
5777
5778        workspace.update_in(cx, |workspace, window, cx| {
5779            ProjectSearchView::deploy_search(
5780                workspace,
5781                &workspace::DeploySearch::default(),
5782                window,
5783                cx,
5784            )
5785        });
5786        let search_view = workspace.update_in(cx, |workspace, _window, cx| {
5787            workspace
5788                .active_pane()
5789                .read(cx)
5790                .items()
5791                .find_map(|item| item.downcast::<ProjectSearchView>())
5792                .expect("Project search view expected to appear after new search event trigger")
5793        });
5794
5795        let query = "param_names_for_lifetime_elision_hints";
5796        perform_project_search(&search_view, query, cx);
5797        search_view.update(cx, |search_view, cx| {
5798            search_view
5799                .results_editor()
5800                .update(cx, |results_editor, cx| {
5801                    assert_eq!(
5802                        results_editor.display_text(cx).match_indices(query).count(),
5803                        9
5804                    );
5805                });
5806        });
5807        let all_matches = r#"rust-analyzer/
5808  crates/
5809    ide/src/
5810      inlay_hints/
5811        fn_lifetime_fn.rs
5812          search: match config.«param_names_for_lifetime_elision_hints» {
5813          search: allocated_lifetimes.push(if config.«param_names_for_lifetime_elision_hints» {
5814          search: Some(it) if config.«param_names_for_lifetime_elision_hints» => {
5815          search: InlayHintsConfig { «param_names_for_lifetime_elision_hints»: true, ..TEST_CONFIG },
5816      inlay_hints.rs
5817        search: pub «param_names_for_lifetime_elision_hints»: bool,
5818        search: «param_names_for_lifetime_elision_hints»: self
5819      static_index.rs
5820        search: «param_names_for_lifetime_elision_hints»: false,
5821    rust-analyzer/src/
5822      cli/
5823        analysis_stats.rs
5824          search: «param_names_for_lifetime_elision_hints»: true,
5825      config.rs
5826        search: «param_names_for_lifetime_elision_hints»: self"#
5827            .to_string();
5828        let select_first_in_all_matches = |line_to_select: &str| {
5829            assert!(
5830                all_matches.contains(line_to_select),
5831                "`{line_to_select}` was not found in all matches `{all_matches}`"
5832            );
5833            all_matches.replacen(
5834                line_to_select,
5835                &format!("{line_to_select}{SELECTED_MARKER}"),
5836                1,
5837            )
5838        };
5839        let clear_outline_metadata = |input: &str| {
5840            input
5841                .replace("search: ", "")
5842                .replace("«", "")
5843                .replace("»", "")
5844        };
5845
5846        cx.executor()
5847            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5848        cx.run_until_parked();
5849
5850        let active_editor = outline_panel.read_with(cx, |outline_panel, _| {
5851            outline_panel
5852                .active_editor()
5853                .expect("should have an active editor open")
5854        });
5855        let initial_outline_selection =
5856            "search: match config.«param_names_for_lifetime_elision_hints» {";
5857        outline_panel.update_in(cx, |outline_panel, window, cx| {
5858            assert_eq!(
5859                display_entries(
5860                    &project,
5861                    &snapshot(outline_panel, cx),
5862                    &outline_panel.cached_entries,
5863                    outline_panel.selected_entry(),
5864                    cx,
5865                ),
5866                select_first_in_all_matches(initial_outline_selection)
5867            );
5868            assert_eq!(
5869                selected_row_text(&active_editor, cx),
5870                clear_outline_metadata(initial_outline_selection),
5871                "Should place the initial editor selection on the corresponding search result"
5872            );
5873
5874            outline_panel.select_next(&SelectNext, window, cx);
5875            outline_panel.select_next(&SelectNext, window, cx);
5876        });
5877
5878        let navigated_outline_selection =
5879            "search: Some(it) if config.«param_names_for_lifetime_elision_hints» => {";
5880        outline_panel.update(cx, |outline_panel, cx| {
5881            assert_eq!(
5882                display_entries(
5883                    &project,
5884                    &snapshot(outline_panel, cx),
5885                    &outline_panel.cached_entries,
5886                    outline_panel.selected_entry(),
5887                    cx,
5888                ),
5889                select_first_in_all_matches(navigated_outline_selection)
5890            );
5891        });
5892        cx.executor()
5893            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5894        outline_panel.update(cx, |_, cx| {
5895            assert_eq!(
5896                selected_row_text(&active_editor, cx),
5897                clear_outline_metadata(navigated_outline_selection),
5898                "Should still have the initial caret position after SelectNext calls"
5899            );
5900        });
5901
5902        outline_panel.update_in(cx, |outline_panel, window, cx| {
5903            outline_panel.open_selected_entry(&OpenSelectedEntry, window, cx);
5904        });
5905        outline_panel.update(cx, |_outline_panel, cx| {
5906            assert_eq!(
5907                selected_row_text(&active_editor, cx),
5908                clear_outline_metadata(navigated_outline_selection),
5909                "After opening, should move the caret to the opened outline entry's position"
5910            );
5911        });
5912
5913        outline_panel.update_in(cx, |outline_panel, window, cx| {
5914            outline_panel.select_next(&SelectNext, window, cx);
5915        });
5916        let next_navigated_outline_selection = "search: InlayHintsConfig { «param_names_for_lifetime_elision_hints»: true, ..TEST_CONFIG },";
5917        outline_panel.update(cx, |outline_panel, cx| {
5918            assert_eq!(
5919                display_entries(
5920                    &project,
5921                    &snapshot(outline_panel, cx),
5922                    &outline_panel.cached_entries,
5923                    outline_panel.selected_entry(),
5924                    cx,
5925                ),
5926                select_first_in_all_matches(next_navigated_outline_selection)
5927            );
5928        });
5929        cx.executor()
5930            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5931        outline_panel.update(cx, |_outline_panel, cx| {
5932            assert_eq!(
5933                selected_row_text(&active_editor, cx),
5934                clear_outline_metadata(next_navigated_outline_selection),
5935                "Should again preserve the selection after another SelectNext call"
5936            );
5937        });
5938
5939        outline_panel.update_in(cx, |outline_panel, window, cx| {
5940            outline_panel.open_excerpts(&editor::actions::OpenExcerpts, window, cx);
5941        });
5942        cx.executor()
5943            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
5944        cx.run_until_parked();
5945        let new_active_editor = outline_panel.read_with(cx, |outline_panel, _| {
5946            outline_panel
5947                .active_editor()
5948                .expect("should have an active editor open")
5949        });
5950        outline_panel.update(cx, |outline_panel, cx| {
5951            assert_ne!(
5952                active_editor, new_active_editor,
5953                "After opening an excerpt, new editor should be open"
5954            );
5955            assert_eq!(
5956                display_entries(
5957                    &project,
5958                    &snapshot(outline_panel, cx),
5959                    &outline_panel.cached_entries,
5960                    outline_panel.selected_entry(),
5961                    cx,
5962                ),
5963                "outline: pub(super) fn hints
5964outline: fn hints_lifetimes_named  <==== selected"
5965            );
5966            assert_eq!(
5967                selected_row_text(&new_active_editor, cx),
5968                clear_outline_metadata(next_navigated_outline_selection),
5969                "When opening the excerpt, should navigate to the place corresponding the outline entry"
5970            );
5971        });
5972    }
5973
5974    #[gpui::test]
5975    async fn test_multiple_worktrees(cx: &mut TestAppContext) {
5976        init_test(cx);
5977
5978        let fs = FakeFs::new(cx.background_executor.clone());
5979        fs.insert_tree(
5980            path!("/root"),
5981            json!({
5982                "one": {
5983                    "a.txt": "aaa aaa"
5984                },
5985                "two": {
5986                    "b.txt": "a aaa"
5987                }
5988
5989            }),
5990        )
5991        .await;
5992        let project = Project::test(fs.clone(), [Path::new(path!("/root/one"))], cx).await;
5993        let (window, workspace) = add_outline_panel(&project, cx).await;
5994        let cx = &mut VisualTestContext::from_window(window.into(), cx);
5995        let outline_panel = outline_panel(&workspace, cx);
5996        outline_panel.update_in(cx, |outline_panel, window, cx| {
5997            outline_panel.set_active(true, window, cx)
5998        });
5999
6000        let items = workspace
6001            .update_in(cx, |workspace, window, cx| {
6002                workspace.open_paths(
6003                    vec![PathBuf::from(path!("/root/two"))],
6004                    OpenOptions {
6005                        visible: Some(OpenVisible::OnlyDirectories),
6006                        ..Default::default()
6007                    },
6008                    None,
6009                    window,
6010                    cx,
6011                )
6012            })
6013            .await;
6014        assert_eq!(items.len(), 1, "Were opening another worktree directory");
6015        assert!(
6016            items[0].is_none(),
6017            "Directory should be opened successfully"
6018        );
6019
6020        workspace.update_in(cx, |workspace, window, cx| {
6021            ProjectSearchView::deploy_search(
6022                workspace,
6023                &workspace::DeploySearch::default(),
6024                window,
6025                cx,
6026            )
6027        });
6028        let search_view = workspace.update_in(cx, |workspace, _window, cx| {
6029            workspace
6030                .active_pane()
6031                .read(cx)
6032                .items()
6033                .find_map(|item| item.downcast::<ProjectSearchView>())
6034                .expect("Project search view expected to appear after new search event trigger")
6035        });
6036
6037        let query = "aaa";
6038        perform_project_search(&search_view, query, cx);
6039        search_view.update(cx, |search_view, cx| {
6040            search_view
6041                .results_editor()
6042                .update(cx, |results_editor, cx| {
6043                    assert_eq!(
6044                        results_editor.display_text(cx).match_indices(query).count(),
6045                        3
6046                    );
6047                });
6048        });
6049
6050        cx.executor()
6051            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6052        cx.run_until_parked();
6053        outline_panel.update(cx, |outline_panel, cx| {
6054            assert_eq!(
6055                display_entries(
6056                    &project,
6057                    &snapshot(outline_panel, cx),
6058                    &outline_panel.cached_entries,
6059                    outline_panel.selected_entry(),
6060                    cx,
6061                ),
6062                format!(
6063                    r#"one/
6064  a.txt
6065    search: «aaa» aaa  <==== selected
6066    search: aaa «aaa»
6067two/
6068  b.txt
6069    search: a «aaa»"#,
6070                ),
6071            );
6072        });
6073
6074        outline_panel.update_in(cx, |outline_panel, window, cx| {
6075            outline_panel.select_previous(&SelectPrevious, window, cx);
6076            outline_panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx);
6077        });
6078        cx.executor()
6079            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6080        cx.run_until_parked();
6081        outline_panel.update(cx, |outline_panel, cx| {
6082            assert_eq!(
6083                display_entries(
6084                    &project,
6085                    &snapshot(outline_panel, cx),
6086                    &outline_panel.cached_entries,
6087                    outline_panel.selected_entry(),
6088                    cx,
6089                ),
6090                format!(
6091                    r#"one/
6092  a.txt  <==== selected
6093two/
6094  b.txt
6095    search: a «aaa»"#,
6096                ),
6097            );
6098        });
6099
6100        outline_panel.update_in(cx, |outline_panel, window, cx| {
6101            outline_panel.select_next(&SelectNext, window, cx);
6102            outline_panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx);
6103        });
6104        cx.executor()
6105            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6106        cx.run_until_parked();
6107        outline_panel.update(cx, |outline_panel, cx| {
6108            assert_eq!(
6109                display_entries(
6110                    &project,
6111                    &snapshot(outline_panel, cx),
6112                    &outline_panel.cached_entries,
6113                    outline_panel.selected_entry(),
6114                    cx,
6115                ),
6116                format!(
6117                    r#"one/
6118  a.txt
6119two/  <==== selected"#,
6120                ),
6121            );
6122        });
6123
6124        outline_panel.update_in(cx, |outline_panel, window, cx| {
6125            outline_panel.expand_selected_entry(&ExpandSelectedEntry, window, cx);
6126        });
6127        cx.executor()
6128            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6129        cx.run_until_parked();
6130        outline_panel.update(cx, |outline_panel, cx| {
6131            assert_eq!(
6132                display_entries(
6133                    &project,
6134                    &snapshot(outline_panel, cx),
6135                    &outline_panel.cached_entries,
6136                    outline_panel.selected_entry(),
6137                    cx,
6138                ),
6139                format!(
6140                    r#"one/
6141  a.txt
6142two/  <==== selected
6143  b.txt
6144    search: a «aaa»"#,
6145                )
6146            );
6147        });
6148    }
6149
6150    #[gpui::test]
6151    async fn test_navigating_in_singleton(cx: &mut TestAppContext) {
6152        init_test(cx);
6153
6154        let root = path!("/root");
6155        let fs = FakeFs::new(cx.background_executor.clone());
6156        fs.insert_tree(
6157            root,
6158            json!({
6159                "src": {
6160                    "lib.rs": indoc!("
6161#[derive(Clone, Debug, PartialEq, Eq, Hash)]
6162struct OutlineEntryExcerpt {
6163    id: ExcerptId,
6164    buffer_id: BufferId,
6165    range: ExcerptRange<language::Anchor>,
6166}"),
6167                }
6168            }),
6169        )
6170        .await;
6171        let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
6172        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
6173        let (window, workspace) = add_outline_panel(&project, cx).await;
6174        let cx = &mut VisualTestContext::from_window(window.into(), cx);
6175        let outline_panel = outline_panel(&workspace, cx);
6176        cx.update(|window, cx| {
6177            outline_panel.update(cx, |outline_panel, cx| {
6178                outline_panel.set_active(true, window, cx)
6179            });
6180        });
6181
6182        let _editor = workspace
6183            .update_in(cx, |workspace, window, cx| {
6184                workspace.open_abs_path(
6185                    PathBuf::from(path!("/root/src/lib.rs")),
6186                    OpenOptions {
6187                        visible: Some(OpenVisible::All),
6188                        ..Default::default()
6189                    },
6190                    window,
6191                    cx,
6192                )
6193            })
6194            .await
6195            .expect("Failed to open Rust source file")
6196            .downcast::<Editor>()
6197            .expect("Should open an editor for Rust source file");
6198
6199        cx.executor()
6200            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6201        cx.run_until_parked();
6202        outline_panel.update(cx, |outline_panel, cx| {
6203            assert_eq!(
6204                display_entries(
6205                    &project,
6206                    &snapshot(outline_panel, cx),
6207                    &outline_panel.cached_entries,
6208                    outline_panel.selected_entry(),
6209                    cx,
6210                ),
6211                indoc!(
6212                    "
6213outline: struct OutlineEntryExcerpt
6214  outline: id
6215  outline: buffer_id
6216  outline: range"
6217                )
6218            );
6219        });
6220
6221        cx.update(|window, cx| {
6222            outline_panel.update(cx, |outline_panel, cx| {
6223                outline_panel.select_next(&SelectNext, window, cx);
6224            });
6225        });
6226        cx.executor()
6227            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6228        cx.run_until_parked();
6229        outline_panel.update(cx, |outline_panel, cx| {
6230            assert_eq!(
6231                display_entries(
6232                    &project,
6233                    &snapshot(outline_panel, cx),
6234                    &outline_panel.cached_entries,
6235                    outline_panel.selected_entry(),
6236                    cx,
6237                ),
6238                indoc!(
6239                    "
6240outline: struct OutlineEntryExcerpt  <==== selected
6241  outline: id
6242  outline: buffer_id
6243  outline: range"
6244                )
6245            );
6246        });
6247
6248        cx.update(|window, cx| {
6249            outline_panel.update(cx, |outline_panel, cx| {
6250                outline_panel.select_next(&SelectNext, window, cx);
6251            });
6252        });
6253        cx.executor()
6254            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6255        cx.run_until_parked();
6256        outline_panel.update(cx, |outline_panel, cx| {
6257            assert_eq!(
6258                display_entries(
6259                    &project,
6260                    &snapshot(outline_panel, cx),
6261                    &outline_panel.cached_entries,
6262                    outline_panel.selected_entry(),
6263                    cx,
6264                ),
6265                indoc!(
6266                    "
6267outline: struct OutlineEntryExcerpt
6268  outline: id  <==== selected
6269  outline: buffer_id
6270  outline: range"
6271                )
6272            );
6273        });
6274
6275        cx.update(|window, cx| {
6276            outline_panel.update(cx, |outline_panel, cx| {
6277                outline_panel.select_next(&SelectNext, window, cx);
6278            });
6279        });
6280        cx.executor()
6281            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6282        cx.run_until_parked();
6283        outline_panel.update(cx, |outline_panel, cx| {
6284            assert_eq!(
6285                display_entries(
6286                    &project,
6287                    &snapshot(outline_panel, cx),
6288                    &outline_panel.cached_entries,
6289                    outline_panel.selected_entry(),
6290                    cx,
6291                ),
6292                indoc!(
6293                    "
6294outline: struct OutlineEntryExcerpt
6295  outline: id
6296  outline: buffer_id  <==== selected
6297  outline: range"
6298                )
6299            );
6300        });
6301
6302        cx.update(|window, cx| {
6303            outline_panel.update(cx, |outline_panel, cx| {
6304                outline_panel.select_next(&SelectNext, window, cx);
6305            });
6306        });
6307        cx.executor()
6308            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6309        cx.run_until_parked();
6310        outline_panel.update(cx, |outline_panel, cx| {
6311            assert_eq!(
6312                display_entries(
6313                    &project,
6314                    &snapshot(outline_panel, cx),
6315                    &outline_panel.cached_entries,
6316                    outline_panel.selected_entry(),
6317                    cx,
6318                ),
6319                indoc!(
6320                    "
6321outline: struct OutlineEntryExcerpt
6322  outline: id
6323  outline: buffer_id
6324  outline: range  <==== selected"
6325                )
6326            );
6327        });
6328
6329        cx.update(|window, cx| {
6330            outline_panel.update(cx, |outline_panel, cx| {
6331                outline_panel.select_next(&SelectNext, window, cx);
6332            });
6333        });
6334        cx.executor()
6335            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6336        cx.run_until_parked();
6337        outline_panel.update(cx, |outline_panel, cx| {
6338            assert_eq!(
6339                display_entries(
6340                    &project,
6341                    &snapshot(outline_panel, cx),
6342                    &outline_panel.cached_entries,
6343                    outline_panel.selected_entry(),
6344                    cx,
6345                ),
6346                indoc!(
6347                    "
6348outline: struct OutlineEntryExcerpt  <==== selected
6349  outline: id
6350  outline: buffer_id
6351  outline: range"
6352                )
6353            );
6354        });
6355
6356        cx.update(|window, cx| {
6357            outline_panel.update(cx, |outline_panel, cx| {
6358                outline_panel.select_previous(&SelectPrevious, window, cx);
6359            });
6360        });
6361        cx.executor()
6362            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6363        cx.run_until_parked();
6364        outline_panel.update(cx, |outline_panel, cx| {
6365            assert_eq!(
6366                display_entries(
6367                    &project,
6368                    &snapshot(outline_panel, cx),
6369                    &outline_panel.cached_entries,
6370                    outline_panel.selected_entry(),
6371                    cx,
6372                ),
6373                indoc!(
6374                    "
6375outline: struct OutlineEntryExcerpt
6376  outline: id
6377  outline: buffer_id
6378  outline: range  <==== selected"
6379                )
6380            );
6381        });
6382
6383        cx.update(|window, cx| {
6384            outline_panel.update(cx, |outline_panel, cx| {
6385                outline_panel.select_previous(&SelectPrevious, window, cx);
6386            });
6387        });
6388        cx.executor()
6389            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6390        cx.run_until_parked();
6391        outline_panel.update(cx, |outline_panel, cx| {
6392            assert_eq!(
6393                display_entries(
6394                    &project,
6395                    &snapshot(outline_panel, cx),
6396                    &outline_panel.cached_entries,
6397                    outline_panel.selected_entry(),
6398                    cx,
6399                ),
6400                indoc!(
6401                    "
6402outline: struct OutlineEntryExcerpt
6403  outline: id
6404  outline: buffer_id  <==== selected
6405  outline: range"
6406                )
6407            );
6408        });
6409
6410        cx.update(|window, cx| {
6411            outline_panel.update(cx, |outline_panel, cx| {
6412                outline_panel.select_previous(&SelectPrevious, window, cx);
6413            });
6414        });
6415        cx.executor()
6416            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6417        cx.run_until_parked();
6418        outline_panel.update(cx, |outline_panel, cx| {
6419            assert_eq!(
6420                display_entries(
6421                    &project,
6422                    &snapshot(outline_panel, cx),
6423                    &outline_panel.cached_entries,
6424                    outline_panel.selected_entry(),
6425                    cx,
6426                ),
6427                indoc!(
6428                    "
6429outline: struct OutlineEntryExcerpt
6430  outline: id  <==== selected
6431  outline: buffer_id
6432  outline: range"
6433                )
6434            );
6435        });
6436
6437        cx.update(|window, cx| {
6438            outline_panel.update(cx, |outline_panel, cx| {
6439                outline_panel.select_previous(&SelectPrevious, window, cx);
6440            });
6441        });
6442        cx.executor()
6443            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6444        cx.run_until_parked();
6445        outline_panel.update(cx, |outline_panel, cx| {
6446            assert_eq!(
6447                display_entries(
6448                    &project,
6449                    &snapshot(outline_panel, cx),
6450                    &outline_panel.cached_entries,
6451                    outline_panel.selected_entry(),
6452                    cx,
6453                ),
6454                indoc!(
6455                    "
6456outline: struct OutlineEntryExcerpt  <==== selected
6457  outline: id
6458  outline: buffer_id
6459  outline: range"
6460                )
6461            );
6462        });
6463
6464        cx.update(|window, cx| {
6465            outline_panel.update(cx, |outline_panel, cx| {
6466                outline_panel.select_previous(&SelectPrevious, window, cx);
6467            });
6468        });
6469        cx.executor()
6470            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6471        cx.run_until_parked();
6472        outline_panel.update(cx, |outline_panel, cx| {
6473            assert_eq!(
6474                display_entries(
6475                    &project,
6476                    &snapshot(outline_panel, cx),
6477                    &outline_panel.cached_entries,
6478                    outline_panel.selected_entry(),
6479                    cx,
6480                ),
6481                indoc!(
6482                    "
6483outline: struct OutlineEntryExcerpt
6484  outline: id
6485  outline: buffer_id
6486  outline: range  <==== selected"
6487                )
6488            );
6489        });
6490    }
6491
6492    #[gpui::test(iterations = 10)]
6493    async fn test_frontend_repo_structure(cx: &mut TestAppContext) {
6494        init_test(cx);
6495
6496        let root = path!("/frontend-project");
6497        let fs = FakeFs::new(cx.background_executor.clone());
6498        fs.insert_tree(
6499            root,
6500            json!({
6501                "public": {
6502                    "lottie": {
6503                        "syntax-tree.json": r#"{ "something": "static" }"#
6504                    }
6505                },
6506                "src": {
6507                    "app": {
6508                        "(site)": {
6509                            "(about)": {
6510                                "jobs": {
6511                                    "[slug]": {
6512                                        "page.tsx": r#"static"#
6513                                    }
6514                                }
6515                            },
6516                            "(blog)": {
6517                                "post": {
6518                                    "[slug]": {
6519                                        "page.tsx": r#"static"#
6520                                    }
6521                                }
6522                            },
6523                        }
6524                    },
6525                    "components": {
6526                        "ErrorBoundary.tsx": r#"static"#,
6527                    }
6528                }
6529
6530            }),
6531        )
6532        .await;
6533        let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
6534        let (window, workspace) = add_outline_panel(&project, cx).await;
6535        let cx = &mut VisualTestContext::from_window(window.into(), cx);
6536        let outline_panel = outline_panel(&workspace, cx);
6537        outline_panel.update_in(cx, |outline_panel, window, cx| {
6538            outline_panel.set_active(true, window, cx)
6539        });
6540
6541        workspace.update_in(cx, |workspace, window, cx| {
6542            ProjectSearchView::deploy_search(
6543                workspace,
6544                &workspace::DeploySearch::default(),
6545                window,
6546                cx,
6547            )
6548        });
6549        let search_view = workspace.update_in(cx, |workspace, _window, cx| {
6550            workspace
6551                .active_pane()
6552                .read(cx)
6553                .items()
6554                .find_map(|item| item.downcast::<ProjectSearchView>())
6555                .expect("Project search view expected to appear after new search event trigger")
6556        });
6557
6558        let query = "static";
6559        perform_project_search(&search_view, query, cx);
6560        search_view.update(cx, |search_view, cx| {
6561            search_view
6562                .results_editor()
6563                .update(cx, |results_editor, cx| {
6564                    assert_eq!(
6565                        results_editor.display_text(cx).match_indices(query).count(),
6566                        4
6567                    );
6568                });
6569        });
6570
6571        cx.executor()
6572            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6573        cx.run_until_parked();
6574        outline_panel.update(cx, |outline_panel, cx| {
6575            assert_eq!(
6576                display_entries(
6577                    &project,
6578                    &snapshot(outline_panel, cx),
6579                    &outline_panel.cached_entries,
6580                    outline_panel.selected_entry(),
6581                    cx,
6582                ),
6583                format!(
6584                    r#"frontend-project/
6585  public/lottie/
6586    syntax-tree.json
6587      search: {{ "something": "«static»" }}  <==== selected
6588  src/
6589    app/(site)/
6590      (about)/jobs/[slug]/
6591        page.tsx
6592          search: «static»
6593      (blog)/post/[slug]/
6594        page.tsx
6595          search: «static»
6596    components/
6597      ErrorBoundary.tsx
6598        search: «static»"#
6599                )
6600            );
6601        });
6602
6603        outline_panel.update_in(cx, |outline_panel, window, cx| {
6604            // Move to 5th element in the list, 3 items down.
6605            for _ in 0..2 {
6606                outline_panel.select_next(&SelectNext, window, cx);
6607            }
6608            outline_panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx);
6609        });
6610        cx.executor()
6611            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6612        cx.run_until_parked();
6613        outline_panel.update(cx, |outline_panel, cx| {
6614            assert_eq!(
6615                display_entries(
6616                    &project,
6617                    &snapshot(outline_panel, cx),
6618                    &outline_panel.cached_entries,
6619                    outline_panel.selected_entry(),
6620                    cx,
6621                ),
6622                format!(
6623                    r#"frontend-project/
6624  public/lottie/
6625    syntax-tree.json
6626      search: {{ "something": "«static»" }}
6627  src/
6628    app/(site)/  <==== selected
6629    components/
6630      ErrorBoundary.tsx
6631        search: «static»"#
6632                )
6633            );
6634        });
6635
6636        outline_panel.update_in(cx, |outline_panel, window, cx| {
6637            // Move to the next visible non-FS entry
6638            for _ in 0..3 {
6639                outline_panel.select_next(&SelectNext, window, cx);
6640            }
6641        });
6642        cx.run_until_parked();
6643        outline_panel.update(cx, |outline_panel, cx| {
6644            assert_eq!(
6645                display_entries(
6646                    &project,
6647                    &snapshot(outline_panel, cx),
6648                    &outline_panel.cached_entries,
6649                    outline_panel.selected_entry(),
6650                    cx,
6651                ),
6652                format!(
6653                    r#"frontend-project/
6654  public/lottie/
6655    syntax-tree.json
6656      search: {{ "something": "«static»" }}
6657  src/
6658    app/(site)/
6659    components/
6660      ErrorBoundary.tsx
6661        search: «static»  <==== selected"#
6662                )
6663            );
6664        });
6665
6666        outline_panel.update_in(cx, |outline_panel, window, cx| {
6667            outline_panel
6668                .active_editor()
6669                .expect("Should have an active editor")
6670                .update(cx, |editor, cx| {
6671                    editor.toggle_fold(&editor::actions::ToggleFold, window, cx)
6672                });
6673        });
6674        cx.executor()
6675            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6676        cx.run_until_parked();
6677        outline_panel.update(cx, |outline_panel, cx| {
6678            assert_eq!(
6679                display_entries(
6680                    &project,
6681                    &snapshot(outline_panel, cx),
6682                    &outline_panel.cached_entries,
6683                    outline_panel.selected_entry(),
6684                    cx,
6685                ),
6686                format!(
6687                    r#"frontend-project/
6688  public/lottie/
6689    syntax-tree.json
6690      search: {{ "something": "«static»" }}
6691  src/
6692    app/(site)/
6693    components/
6694      ErrorBoundary.tsx  <==== selected"#
6695                )
6696            );
6697        });
6698
6699        outline_panel.update_in(cx, |outline_panel, window, cx| {
6700            outline_panel
6701                .active_editor()
6702                .expect("Should have an active editor")
6703                .update(cx, |editor, cx| {
6704                    editor.toggle_fold(&editor::actions::ToggleFold, window, cx)
6705                });
6706        });
6707        cx.executor()
6708            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6709        cx.run_until_parked();
6710        outline_panel.update(cx, |outline_panel, cx| {
6711            assert_eq!(
6712                display_entries(
6713                    &project,
6714                    &snapshot(outline_panel, cx),
6715                    &outline_panel.cached_entries,
6716                    outline_panel.selected_entry(),
6717                    cx,
6718                ),
6719                format!(
6720                    r#"frontend-project/
6721  public/lottie/
6722    syntax-tree.json
6723      search: {{ "something": "«static»" }}
6724  src/
6725    app/(site)/
6726    components/
6727      ErrorBoundary.tsx  <==== selected
6728        search: «static»"#
6729                )
6730            );
6731        });
6732
6733        outline_panel.update_in(cx, |outline_panel, window, cx| {
6734            outline_panel.collapse_all_entries(&CollapseAllEntries, window, cx);
6735        });
6736        cx.executor()
6737            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6738        cx.run_until_parked();
6739        outline_panel.update(cx, |outline_panel, cx| {
6740            assert_eq!(
6741                display_entries(
6742                    &project,
6743                    &snapshot(outline_panel, cx),
6744                    &outline_panel.cached_entries,
6745                    outline_panel.selected_entry(),
6746                    cx,
6747                ),
6748                format!(r#"frontend-project/"#)
6749            );
6750        });
6751
6752        outline_panel.update_in(cx, |outline_panel, window, cx| {
6753            outline_panel.expand_all_entries(&ExpandAllEntries, window, cx);
6754        });
6755        cx.executor()
6756            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
6757        cx.run_until_parked();
6758        outline_panel.update(cx, |outline_panel, cx| {
6759            assert_eq!(
6760                display_entries(
6761                    &project,
6762                    &snapshot(outline_panel, cx),
6763                    &outline_panel.cached_entries,
6764                    outline_panel.selected_entry(),
6765                    cx,
6766                ),
6767                format!(
6768                    r#"frontend-project/
6769  public/lottie/
6770    syntax-tree.json
6771      search: {{ "something": "«static»" }}
6772  src/
6773    app/(site)/
6774      (about)/jobs/[slug]/
6775        page.tsx
6776          search: «static»
6777      (blog)/post/[slug]/
6778        page.tsx
6779          search: «static»
6780    components/
6781      ErrorBoundary.tsx  <==== selected
6782        search: «static»"#
6783                )
6784            );
6785        });
6786    }
6787
6788    async fn add_outline_panel(
6789        project: &Entity<Project>,
6790        cx: &mut TestAppContext,
6791    ) -> (WindowHandle<MultiWorkspace>, Entity<Workspace>) {
6792        let window =
6793            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
6794        let workspace = window
6795            .read_with(cx, |mw, _| mw.workspace().clone())
6796            .unwrap();
6797
6798        let workspace_weak = workspace.downgrade();
6799        let outline_panel = window
6800            .update(cx, |_, window, cx| {
6801                cx.spawn_in(window, async move |_this, cx| {
6802                    OutlinePanel::load(workspace_weak, cx.clone()).await
6803                })
6804            })
6805            .unwrap()
6806            .await
6807            .expect("Failed to load outline panel");
6808
6809        window
6810            .update(cx, |multi_workspace, window, cx| {
6811                multi_workspace.workspace().update(cx, |workspace, cx| {
6812                    workspace.add_panel(outline_panel, window, cx);
6813                });
6814            })
6815            .unwrap();
6816        (window, workspace)
6817    }
6818
6819    fn outline_panel(
6820        workspace: &Entity<Workspace>,
6821        cx: &mut VisualTestContext,
6822    ) -> Entity<OutlinePanel> {
6823        workspace.update_in(cx, |workspace, _window, cx| {
6824            workspace
6825                .panel::<OutlinePanel>(cx)
6826                .expect("no outline panel")
6827        })
6828    }
6829
6830    fn display_entries(
6831        project: &Entity<Project>,
6832        multi_buffer_snapshot: &MultiBufferSnapshot,
6833        cached_entries: &[CachedEntry],
6834        selected_entry: Option<&PanelEntry>,
6835        cx: &mut App,
6836    ) -> String {
6837        let project = project.read(cx);
6838        let mut display_string = String::new();
6839        for entry in cached_entries {
6840            if !display_string.is_empty() {
6841                display_string += "\n";
6842            }
6843            for _ in 0..entry.depth {
6844                display_string += "  ";
6845            }
6846            display_string += &match &entry.entry {
6847                PanelEntry::Fs(entry) => match entry {
6848                    FsEntry::ExternalFile(_) => {
6849                        panic!("Did not cover external files with tests")
6850                    }
6851                    FsEntry::Directory(directory) => {
6852                        let path = if let Some(worktree) = project
6853                            .worktree_for_id(directory.worktree_id, cx)
6854                            .filter(|worktree| {
6855                                worktree.read(cx).root_entry() == Some(&directory.entry.entry)
6856                            }) {
6857                            worktree
6858                                .read(cx)
6859                                .root_name()
6860                                .join(&directory.entry.path)
6861                                .as_unix_str()
6862                                .to_string()
6863                        } else {
6864                            directory
6865                                .entry
6866                                .path
6867                                .file_name()
6868                                .unwrap_or_default()
6869                                .to_string()
6870                        };
6871                        format!("{path}/")
6872                    }
6873                    FsEntry::File(file) => file
6874                        .entry
6875                        .path
6876                        .file_name()
6877                        .map(|name| name.to_string())
6878                        .unwrap_or_default(),
6879                },
6880                PanelEntry::FoldedDirs(folded_dirs) => folded_dirs
6881                    .entries
6882                    .iter()
6883                    .filter_map(|dir| dir.path.file_name())
6884                    .map(|name| name.to_string() + "/")
6885                    .collect(),
6886                PanelEntry::Outline(outline_entry) => match outline_entry {
6887                    OutlineEntry::Excerpt(_) => continue,
6888                    OutlineEntry::Outline(outline_entry) => {
6889                        format!("outline: {}", outline_entry.outline.text)
6890                    }
6891                },
6892                PanelEntry::Search(search_entry) => {
6893                    let search_data = search_entry.render_data.get_or_init(|| {
6894                        SearchData::new(&search_entry.match_range, multi_buffer_snapshot)
6895                    });
6896                    let mut search_result = String::new();
6897                    let mut last_end = 0;
6898                    for range in &search_data.search_match_indices {
6899                        search_result.push_str(&search_data.context_text[last_end..range.start]);
6900                        search_result.push('«');
6901                        search_result.push_str(&search_data.context_text[range.start..range.end]);
6902                        search_result.push('»');
6903                        last_end = range.end;
6904                    }
6905                    search_result.push_str(&search_data.context_text[last_end..]);
6906
6907                    format!("search: {search_result}")
6908                }
6909            };
6910
6911            if Some(&entry.entry) == selected_entry {
6912                display_string += SELECTED_MARKER;
6913            }
6914        }
6915        display_string
6916    }
6917
6918    fn init_test(cx: &mut TestAppContext) {
6919        cx.update(|cx| {
6920            let settings = SettingsStore::test(cx);
6921            cx.set_global(settings);
6922
6923            theme::init(theme::LoadThemes::JustBase, cx);
6924
6925            editor::init(cx);
6926            project_search::init(cx);
6927            buffer_search::init(cx);
6928            super::init(cx);
6929        });
6930    }
6931
6932    // Based on https://github.com/rust-lang/rust-analyzer/
6933    async fn populate_with_test_ra_project(fs: &FakeFs, root: &str) {
6934        fs.insert_tree(
6935            root,
6936            json!({
6937                    "crates": {
6938                        "ide": {
6939                            "src": {
6940                                "inlay_hints": {
6941                                    "fn_lifetime_fn.rs": r##"
6942        pub(super) fn hints(
6943            acc: &mut Vec<InlayHint>,
6944            config: &InlayHintsConfig,
6945            func: ast::Fn,
6946        ) -> Option<()> {
6947            // ... snip
6948
6949            let mut used_names: FxHashMap<SmolStr, usize> =
6950                match config.param_names_for_lifetime_elision_hints {
6951                    true => generic_param_list
6952                        .iter()
6953                        .flat_map(|gpl| gpl.lifetime_params())
6954                        .filter_map(|param| param.lifetime())
6955                        .filter_map(|lt| Some((SmolStr::from(lt.text().as_str().get(1..)?), 0)))
6956                        .collect(),
6957                    false => Default::default(),
6958                };
6959            {
6960                let mut potential_lt_refs = potential_lt_refs.iter().filter(|&&(.., is_elided)| is_elided);
6961                if self_param.is_some() && potential_lt_refs.next().is_some() {
6962                    allocated_lifetimes.push(if config.param_names_for_lifetime_elision_hints {
6963                        // self can't be used as a lifetime, so no need to check for collisions
6964                        "'self".into()
6965                    } else {
6966                        gen_idx_name()
6967                    });
6968                }
6969                potential_lt_refs.for_each(|(name, ..)| {
6970                    let name = match name {
6971                        Some(it) if config.param_names_for_lifetime_elision_hints => {
6972                            if let Some(c) = used_names.get_mut(it.text().as_str()) {
6973                                *c += 1;
6974                                SmolStr::from(format!("'{text}{c}", text = it.text().as_str()))
6975                            } else {
6976                                used_names.insert(it.text().as_str().into(), 0);
6977                                SmolStr::from_iter(["\'", it.text().as_str()])
6978                            }
6979                        }
6980                        _ => gen_idx_name(),
6981                    };
6982                    allocated_lifetimes.push(name);
6983                });
6984            }
6985
6986            // ... snip
6987        }
6988
6989        // ... snip
6990
6991            #[test]
6992            fn hints_lifetimes_named() {
6993                check_with_config(
6994                    InlayHintsConfig { param_names_for_lifetime_elision_hints: true, ..TEST_CONFIG },
6995                    r#"
6996        fn nested_in<'named>(named: &        &X<      &()>) {}
6997        //          ^'named1, 'named2, 'named3, $
6998                                  //^'named1 ^'named2 ^'named3
6999        "#,
7000                );
7001            }
7002
7003        // ... snip
7004        "##,
7005                                },
7006                        "inlay_hints.rs": r#"
7007    #[derive(Clone, Debug, PartialEq, Eq)]
7008    pub struct InlayHintsConfig {
7009        // ... snip
7010        pub param_names_for_lifetime_elision_hints: bool,
7011        pub max_length: Option<usize>,
7012        // ... snip
7013    }
7014
7015    impl Config {
7016        pub fn inlay_hints(&self) -> InlayHintsConfig {
7017            InlayHintsConfig {
7018                // ... snip
7019                param_names_for_lifetime_elision_hints: self
7020                    .inlayHints_lifetimeElisionHints_useParameterNames()
7021                    .to_owned(),
7022                max_length: self.inlayHints_maxLength().to_owned(),
7023                // ... snip
7024            }
7025        }
7026    }
7027    "#,
7028                        "static_index.rs": r#"
7029// ... snip
7030        fn add_file(&mut self, file_id: FileId) {
7031            let current_crate = crates_for(self.db, file_id).pop().map(Into::into);
7032            let folds = self.analysis.folding_ranges(file_id).unwrap();
7033            let inlay_hints = self
7034                .analysis
7035                .inlay_hints(
7036                    &InlayHintsConfig {
7037                        // ... snip
7038                        closure_style: hir::ClosureStyle::ImplFn,
7039                        param_names_for_lifetime_elision_hints: false,
7040                        binding_mode_hints: false,
7041                        max_length: Some(25),
7042                        closure_capture_hints: false,
7043                        // ... snip
7044                    },
7045                    file_id,
7046                    None,
7047                )
7048                .unwrap();
7049            // ... snip
7050    }
7051// ... snip
7052    "#
7053                            }
7054                        },
7055                        "rust-analyzer": {
7056                            "src": {
7057                                "cli": {
7058                                    "analysis_stats.rs": r#"
7059        // ... snip
7060                for &file_id in &file_ids {
7061                    _ = analysis.inlay_hints(
7062                        &InlayHintsConfig {
7063                            // ... snip
7064                            implicit_drop_hints: true,
7065                            lifetime_elision_hints: ide::LifetimeElisionHints::Always,
7066                            param_names_for_lifetime_elision_hints: true,
7067                            hide_named_constructor_hints: false,
7068                            hide_closure_initialization_hints: false,
7069                            closure_style: hir::ClosureStyle::ImplFn,
7070                            max_length: Some(25),
7071                            closing_brace_hints_min_lines: Some(20),
7072                            fields_to_resolve: InlayFieldsToResolve::empty(),
7073                            range_exclusive_hints: true,
7074                        },
7075                        file_id.into(),
7076                        None,
7077                    );
7078                }
7079        // ... snip
7080                                    "#,
7081                                },
7082                                "config.rs": r#"
7083                config_data! {
7084                    /// Configs that only make sense when they are set by a client. As such they can only be defined
7085                    /// by setting them using client's settings (e.g `settings.json` on VS Code).
7086                    client: struct ClientDefaultConfigData <- ClientConfigInput -> {
7087                        // ... snip
7088                        /// Maximum length for inlay hints. Set to null to have an unlimited length.
7089                        inlayHints_maxLength: Option<usize>                        = Some(25),
7090                        // ... snip
7091                        /// Whether to prefer using parameter names as the name for elided lifetime hints if possible.
7092                        inlayHints_lifetimeElisionHints_useParameterNames: bool    = false,
7093                        // ... snip
7094                    }
7095                }
7096
7097                impl Config {
7098                    // ... snip
7099                    pub fn inlay_hints(&self) -> InlayHintsConfig {
7100                        InlayHintsConfig {
7101                            // ... snip
7102                            param_names_for_lifetime_elision_hints: self
7103                                .inlayHints_lifetimeElisionHints_useParameterNames()
7104                                .to_owned(),
7105                            max_length: self.inlayHints_maxLength().to_owned(),
7106                            // ... snip
7107                        }
7108                    }
7109                    // ... snip
7110                }
7111                "#
7112                                }
7113                        }
7114                    }
7115            }),
7116        )
7117        .await;
7118    }
7119
7120    fn snapshot(outline_panel: &OutlinePanel, cx: &App) -> MultiBufferSnapshot {
7121        outline_panel
7122            .active_editor()
7123            .unwrap()
7124            .read(cx)
7125            .buffer()
7126            .read(cx)
7127            .snapshot(cx)
7128    }
7129
7130    fn selected_row_text(editor: &Entity<Editor>, cx: &mut App) -> String {
7131        editor.update(cx, |editor, cx| {
7132            let selections = editor.selections.all::<language::Point>(&editor.display_snapshot(cx));
7133            assert_eq!(selections.len(), 1, "Active editor should have exactly one selection after any outline panel interactions");
7134            let selection = selections.first().unwrap();
7135            let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
7136            let line_start = language::Point::new(selection.start.row, 0);
7137            let line_end = multi_buffer_snapshot.clip_point(language::Point::new(selection.end.row, u32::MAX), language::Bias::Right);
7138            multi_buffer_snapshot.text_for_range(line_start..line_end).collect::<String>().trim().to_owned()
7139        })
7140    }
7141
7142    #[gpui::test]
7143    async fn test_outline_keyboard_expand_collapse(cx: &mut TestAppContext) {
7144        init_test(cx);
7145
7146        let fs = FakeFs::new(cx.background_executor.clone());
7147        fs.insert_tree(
7148            "/test",
7149            json!({
7150                "src": {
7151                    "lib.rs": indoc!("
7152                            mod outer {
7153                                pub struct OuterStruct {
7154                                    field: String,
7155                                }
7156                                impl OuterStruct {
7157                                    pub fn new() -> Self {
7158                                        Self { field: String::new() }
7159                                    }
7160                                    pub fn method(&self) {
7161                                        println!(\"{}\", self.field);
7162                                    }
7163                                }
7164                                mod inner {
7165                                    pub fn inner_function() {
7166                                        let x = 42;
7167                                        println!(\"{}\", x);
7168                                    }
7169                                    pub struct InnerStruct {
7170                                        value: i32,
7171                                    }
7172                                }
7173                            }
7174                            fn main() {
7175                                let s = outer::OuterStruct::new();
7176                                s.method();
7177                            }
7178                        "),
7179                }
7180            }),
7181        )
7182        .await;
7183
7184        let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
7185        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
7186        let (window, workspace) = add_outline_panel(&project, cx).await;
7187        let cx = &mut VisualTestContext::from_window(window.into(), cx);
7188        let outline_panel = outline_panel(&workspace, cx);
7189
7190        outline_panel.update_in(cx, |outline_panel, window, cx| {
7191            outline_panel.set_active(true, window, cx)
7192        });
7193
7194        workspace
7195            .update_in(cx, |workspace, window, cx| {
7196                workspace.open_abs_path(
7197                    PathBuf::from("/test/src/lib.rs"),
7198                    OpenOptions {
7199                        visible: Some(OpenVisible::All),
7200                        ..Default::default()
7201                    },
7202                    window,
7203                    cx,
7204                )
7205            })
7206            .await
7207            .unwrap();
7208
7209        cx.executor()
7210            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(500));
7211        cx.run_until_parked();
7212
7213        // Force another update cycle to ensure outlines are fetched
7214        outline_panel.update_in(cx, |panel, window, cx| {
7215            panel.update_non_fs_items(window, cx);
7216            panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
7217        });
7218        cx.executor()
7219            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(500));
7220        cx.run_until_parked();
7221
7222        outline_panel.update(cx, |outline_panel, cx| {
7223            assert_eq!(
7224                display_entries(
7225                    &project,
7226                    &snapshot(outline_panel, cx),
7227                    &outline_panel.cached_entries,
7228                    outline_panel.selected_entry(),
7229                    cx,
7230                ),
7231                indoc!(
7232                    "
7233outline: mod outer  <==== selected
7234  outline: pub struct OuterStruct
7235    outline: field
7236  outline: impl OuterStruct
7237    outline: pub fn new
7238    outline: pub fn method
7239  outline: mod inner
7240    outline: pub fn inner_function
7241    outline: pub struct InnerStruct
7242      outline: value
7243outline: fn main"
7244                )
7245            );
7246        });
7247
7248        let parent_outline = outline_panel
7249            .read_with(cx, |panel, _cx| {
7250                panel
7251                    .cached_entries
7252                    .iter()
7253                    .find_map(|entry| match &entry.entry {
7254                        PanelEntry::Outline(OutlineEntry::Outline(outline))
7255                            if panel
7256                                .outline_children_cache
7257                                .get(&outline.buffer_id)
7258                                .and_then(|children_map| {
7259                                    let key =
7260                                        (outline.outline.range.clone(), outline.outline.depth);
7261                                    children_map.get(&key)
7262                                })
7263                                .copied()
7264                                .unwrap_or(false) =>
7265                        {
7266                            Some(entry.entry.clone())
7267                        }
7268                        _ => None,
7269                    })
7270            })
7271            .expect("Should find an outline with children");
7272
7273        outline_panel.update_in(cx, |panel, window, cx| {
7274            panel.select_entry(parent_outline.clone(), true, window, cx);
7275            panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx);
7276        });
7277        cx.executor()
7278            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7279        cx.run_until_parked();
7280
7281        outline_panel.update(cx, |outline_panel, cx| {
7282            assert_eq!(
7283                display_entries(
7284                    &project,
7285                    &snapshot(outline_panel, cx),
7286                    &outline_panel.cached_entries,
7287                    outline_panel.selected_entry(),
7288                    cx,
7289                ),
7290                indoc!(
7291                    "
7292outline: mod outer  <==== selected
7293outline: fn main"
7294                )
7295            );
7296        });
7297
7298        outline_panel.update_in(cx, |panel, window, cx| {
7299            panel.expand_selected_entry(&ExpandSelectedEntry, window, cx);
7300        });
7301        cx.executor()
7302            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7303        cx.run_until_parked();
7304
7305        outline_panel.update(cx, |outline_panel, cx| {
7306            assert_eq!(
7307                display_entries(
7308                    &project,
7309                    &snapshot(outline_panel, cx),
7310                    &outline_panel.cached_entries,
7311                    outline_panel.selected_entry(),
7312                    cx,
7313                ),
7314                indoc!(
7315                    "
7316outline: mod outer  <==== selected
7317  outline: pub struct OuterStruct
7318    outline: field
7319  outline: impl OuterStruct
7320    outline: pub fn new
7321    outline: pub fn method
7322  outline: mod inner
7323    outline: pub fn inner_function
7324    outline: pub struct InnerStruct
7325      outline: value
7326outline: fn main"
7327                )
7328            );
7329        });
7330
7331        outline_panel.update_in(cx, |panel, window, cx| {
7332            panel.collapsed_entries.clear();
7333            panel.update_cached_entries(None, window, cx);
7334        });
7335        cx.executor()
7336            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7337        cx.run_until_parked();
7338
7339        outline_panel.update_in(cx, |panel, window, cx| {
7340            let outlines_with_children: Vec<_> = panel
7341                .cached_entries
7342                .iter()
7343                .filter_map(|entry| match &entry.entry {
7344                    PanelEntry::Outline(OutlineEntry::Outline(outline))
7345                        if panel
7346                            .outline_children_cache
7347                            .get(&outline.buffer_id)
7348                            .and_then(|children_map| {
7349                                let key = (outline.outline.range.clone(), outline.outline.depth);
7350                                children_map.get(&key)
7351                            })
7352                            .copied()
7353                            .unwrap_or(false) =>
7354                    {
7355                        Some(entry.entry.clone())
7356                    }
7357                    _ => None,
7358                })
7359                .collect();
7360
7361            for outline in outlines_with_children {
7362                panel.select_entry(outline, false, window, cx);
7363                panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx);
7364            }
7365        });
7366        cx.executor()
7367            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7368        cx.run_until_parked();
7369
7370        outline_panel.update(cx, |outline_panel, cx| {
7371            assert_eq!(
7372                display_entries(
7373                    &project,
7374                    &snapshot(outline_panel, cx),
7375                    &outline_panel.cached_entries,
7376                    outline_panel.selected_entry(),
7377                    cx,
7378                ),
7379                indoc!(
7380                    "
7381outline: mod outer
7382outline: fn main"
7383                )
7384            );
7385        });
7386
7387        let collapsed_entries_count =
7388            outline_panel.read_with(cx, |panel, _| panel.collapsed_entries.len());
7389        assert!(
7390            collapsed_entries_count > 0,
7391            "Should have collapsed entries tracked"
7392        );
7393    }
7394
7395    #[gpui::test]
7396    async fn test_outline_click_toggle_behavior(cx: &mut TestAppContext) {
7397        init_test(cx);
7398
7399        let fs = FakeFs::new(cx.background_executor.clone());
7400        fs.insert_tree(
7401            "/test",
7402            json!({
7403                "src": {
7404                    "main.rs": indoc!("
7405                            struct Config {
7406                                name: String,
7407                                value: i32,
7408                            }
7409                            impl Config {
7410                                fn new(name: String) -> Self {
7411                                    Self { name, value: 0 }
7412                                }
7413                                fn get_value(&self) -> i32 {
7414                                    self.value
7415                                }
7416                            }
7417                            enum Status {
7418                                Active,
7419                                Inactive,
7420                            }
7421                            fn process_config(config: Config) -> Status {
7422                                if config.get_value() > 0 {
7423                                    Status::Active
7424                                } else {
7425                                    Status::Inactive
7426                                }
7427                            }
7428                            fn main() {
7429                                let config = Config::new(\"test\".to_string());
7430                                let status = process_config(config);
7431                            }
7432                        "),
7433                }
7434            }),
7435        )
7436        .await;
7437
7438        let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
7439        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
7440
7441        let (window, workspace) = add_outline_panel(&project, cx).await;
7442        let cx = &mut VisualTestContext::from_window(window.into(), cx);
7443        let outline_panel = outline_panel(&workspace, cx);
7444
7445        outline_panel.update_in(cx, |outline_panel, window, cx| {
7446            outline_panel.set_active(true, window, cx)
7447        });
7448
7449        let _editor = workspace
7450            .update_in(cx, |workspace, window, cx| {
7451                workspace.open_abs_path(
7452                    PathBuf::from("/test/src/main.rs"),
7453                    OpenOptions {
7454                        visible: Some(OpenVisible::All),
7455                        ..Default::default()
7456                    },
7457                    window,
7458                    cx,
7459                )
7460            })
7461            .await
7462            .unwrap();
7463
7464        cx.executor()
7465            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7466        cx.run_until_parked();
7467
7468        outline_panel.update(cx, |outline_panel, _cx| {
7469            outline_panel.selected_entry = SelectedEntry::None;
7470        });
7471
7472        // Check initial state - all entries should be expanded by default
7473        outline_panel.update(cx, |outline_panel, cx| {
7474            assert_eq!(
7475                display_entries(
7476                    &project,
7477                    &snapshot(outline_panel, cx),
7478                    &outline_panel.cached_entries,
7479                    outline_panel.selected_entry(),
7480                    cx,
7481                ),
7482                indoc!(
7483                    "
7484outline: struct Config
7485  outline: name
7486  outline: value
7487outline: impl Config
7488  outline: fn new
7489  outline: fn get_value
7490outline: enum Status
7491  outline: Active
7492  outline: Inactive
7493outline: fn process_config
7494outline: fn main"
7495                )
7496            );
7497        });
7498
7499        outline_panel.update(cx, |outline_panel, _cx| {
7500            outline_panel.selected_entry = SelectedEntry::None;
7501        });
7502
7503        cx.update(|window, cx| {
7504            outline_panel.update(cx, |outline_panel, cx| {
7505                outline_panel.select_first(&SelectFirst, window, cx);
7506            });
7507        });
7508
7509        cx.executor()
7510            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7511        cx.run_until_parked();
7512
7513        outline_panel.update(cx, |outline_panel, cx| {
7514            assert_eq!(
7515                display_entries(
7516                    &project,
7517                    &snapshot(outline_panel, cx),
7518                    &outline_panel.cached_entries,
7519                    outline_panel.selected_entry(),
7520                    cx,
7521                ),
7522                indoc!(
7523                    "
7524outline: struct Config  <==== selected
7525  outline: name
7526  outline: value
7527outline: impl Config
7528  outline: fn new
7529  outline: fn get_value
7530outline: enum Status
7531  outline: Active
7532  outline: Inactive
7533outline: fn process_config
7534outline: fn main"
7535                )
7536            );
7537        });
7538
7539        cx.update(|window, cx| {
7540            outline_panel.update(cx, |outline_panel, cx| {
7541                outline_panel.collapse_selected_entry(&CollapseSelectedEntry, window, cx);
7542            });
7543        });
7544
7545        cx.executor()
7546            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7547        cx.run_until_parked();
7548
7549        outline_panel.update(cx, |outline_panel, cx| {
7550            assert_eq!(
7551                display_entries(
7552                    &project,
7553                    &snapshot(outline_panel, cx),
7554                    &outline_panel.cached_entries,
7555                    outline_panel.selected_entry(),
7556                    cx,
7557                ),
7558                indoc!(
7559                    "
7560outline: struct Config  <==== selected
7561outline: impl Config
7562  outline: fn new
7563  outline: fn get_value
7564outline: enum Status
7565  outline: Active
7566  outline: Inactive
7567outline: fn process_config
7568outline: fn main"
7569                )
7570            );
7571        });
7572
7573        cx.update(|window, cx| {
7574            outline_panel.update(cx, |outline_panel, cx| {
7575                outline_panel.expand_selected_entry(&ExpandSelectedEntry, window, cx);
7576            });
7577        });
7578
7579        cx.executor()
7580            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7581        cx.run_until_parked();
7582
7583        outline_panel.update(cx, |outline_panel, cx| {
7584            assert_eq!(
7585                display_entries(
7586                    &project,
7587                    &snapshot(outline_panel, cx),
7588                    &outline_panel.cached_entries,
7589                    outline_panel.selected_entry(),
7590                    cx,
7591                ),
7592                indoc!(
7593                    "
7594outline: struct Config  <==== selected
7595  outline: name
7596  outline: value
7597outline: impl Config
7598  outline: fn new
7599  outline: fn get_value
7600outline: enum Status
7601  outline: Active
7602  outline: Inactive
7603outline: fn process_config
7604outline: fn main"
7605                )
7606            );
7607        });
7608    }
7609
7610    #[gpui::test]
7611    async fn test_outline_expand_collapse_all(cx: &mut TestAppContext) {
7612        init_test(cx);
7613
7614        let fs = FakeFs::new(cx.background_executor.clone());
7615        fs.insert_tree(
7616            "/test",
7617            json!({
7618                "src": {
7619                    "lib.rs": indoc!("
7620                            mod outer {
7621                                pub struct OuterStruct {
7622                                    field: String,
7623                                }
7624                                impl OuterStruct {
7625                                    pub fn new() -> Self {
7626                                        Self { field: String::new() }
7627                                    }
7628                                    pub fn method(&self) {
7629                                        println!(\"{}\", self.field);
7630                                    }
7631                                }
7632                                mod inner {
7633                                    pub fn inner_function() {
7634                                        let x = 42;
7635                                        println!(\"{}\", x);
7636                                    }
7637                                    pub struct InnerStruct {
7638                                        value: i32,
7639                                    }
7640                                }
7641                            }
7642                            fn main() {
7643                                let s = outer::OuterStruct::new();
7644                                s.method();
7645                            }
7646                        "),
7647                }
7648            }),
7649        )
7650        .await;
7651
7652        let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
7653        project.read_with(cx, |project, _| project.languages().add(rust_lang()));
7654        let (window, workspace) = add_outline_panel(&project, cx).await;
7655        let cx = &mut VisualTestContext::from_window(window.into(), cx);
7656        let outline_panel = outline_panel(&workspace, cx);
7657
7658        outline_panel.update_in(cx, |outline_panel, window, cx| {
7659            outline_panel.set_active(true, window, cx)
7660        });
7661
7662        workspace
7663            .update_in(cx, |workspace, window, cx| {
7664                workspace.open_abs_path(
7665                    PathBuf::from("/test/src/lib.rs"),
7666                    OpenOptions {
7667                        visible: Some(OpenVisible::All),
7668                        ..Default::default()
7669                    },
7670                    window,
7671                    cx,
7672                )
7673            })
7674            .await
7675            .unwrap();
7676
7677        cx.executor()
7678            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(500));
7679        cx.run_until_parked();
7680
7681        // Force another update cycle to ensure outlines are fetched
7682        outline_panel.update_in(cx, |panel, window, cx| {
7683            panel.update_non_fs_items(window, cx);
7684            panel.update_cached_entries(Some(UPDATE_DEBOUNCE), window, cx);
7685        });
7686        cx.executor()
7687            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(500));
7688        cx.run_until_parked();
7689
7690        outline_panel.update(cx, |outline_panel, cx| {
7691            assert_eq!(
7692                display_entries(
7693                    &project,
7694                    &snapshot(outline_panel, cx),
7695                    &outline_panel.cached_entries,
7696                    outline_panel.selected_entry(),
7697                    cx,
7698                ),
7699                indoc!(
7700                    "
7701outline: mod outer  <==== selected
7702  outline: pub struct OuterStruct
7703    outline: field
7704  outline: impl OuterStruct
7705    outline: pub fn new
7706    outline: pub fn method
7707  outline: mod inner
7708    outline: pub fn inner_function
7709    outline: pub struct InnerStruct
7710      outline: value
7711outline: fn main"
7712                )
7713            );
7714        });
7715
7716        let _parent_outline = outline_panel
7717            .read_with(cx, |panel, _cx| {
7718                panel
7719                    .cached_entries
7720                    .iter()
7721                    .find_map(|entry| match &entry.entry {
7722                        PanelEntry::Outline(OutlineEntry::Outline(outline))
7723                            if panel
7724                                .outline_children_cache
7725                                .get(&outline.buffer_id)
7726                                .and_then(|children_map| {
7727                                    let key =
7728                                        (outline.outline.range.clone(), outline.outline.depth);
7729                                    children_map.get(&key)
7730                                })
7731                                .copied()
7732                                .unwrap_or(false) =>
7733                        {
7734                            Some(entry.entry.clone())
7735                        }
7736                        _ => None,
7737                    })
7738            })
7739            .expect("Should find an outline with children");
7740
7741        // Collapse all entries
7742        outline_panel.update_in(cx, |panel, window, cx| {
7743            panel.collapse_all_entries(&CollapseAllEntries, window, cx);
7744        });
7745        cx.executor()
7746            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7747        cx.run_until_parked();
7748
7749        let expected_collapsed_output = indoc!(
7750            "
7751        outline: mod outer  <==== selected
7752        outline: fn main"
7753        );
7754
7755        outline_panel.update(cx, |panel, cx| {
7756            assert_eq! {
7757                display_entries(
7758                    &project,
7759                    &snapshot(panel, cx),
7760                    &panel.cached_entries,
7761                    panel.selected_entry(),
7762                    cx,
7763                ),
7764                expected_collapsed_output
7765            };
7766        });
7767
7768        // Expand all entries
7769        outline_panel.update_in(cx, |panel, window, cx| {
7770            panel.expand_all_entries(&ExpandAllEntries, window, cx);
7771        });
7772        cx.executor()
7773            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
7774        cx.run_until_parked();
7775
7776        let expected_expanded_output = indoc!(
7777            "
7778        outline: mod outer  <==== selected
7779          outline: pub struct OuterStruct
7780            outline: field
7781          outline: impl OuterStruct
7782            outline: pub fn new
7783            outline: pub fn method
7784          outline: mod inner
7785            outline: pub fn inner_function
7786            outline: pub struct InnerStruct
7787              outline: value
7788        outline: fn main"
7789        );
7790
7791        outline_panel.update(cx, |panel, cx| {
7792            assert_eq! {
7793                display_entries(
7794                    &project,
7795                    &snapshot(panel, cx),
7796                    &panel.cached_entries,
7797                    panel.selected_entry(),
7798                    cx,
7799                ),
7800                expected_expanded_output
7801            };
7802        });
7803    }
7804
7805    #[gpui::test]
7806    async fn test_buffer_search(cx: &mut TestAppContext) {
7807        init_test(cx);
7808
7809        let fs = FakeFs::new(cx.background_executor.clone());
7810        fs.insert_tree(
7811            "/test",
7812            json!({
7813                "foo.txt": r#"<_constitution>
7814
7815</_constitution>
7816
7817
7818
7819## 📊 Output
7820
7821| Field          | Meaning                |
7822"#
7823            }),
7824        )
7825        .await;
7826
7827        let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
7828        let (window, workspace) = add_outline_panel(&project, cx).await;
7829        let cx = &mut VisualTestContext::from_window(window.into(), cx);
7830
7831        let editor = workspace
7832            .update_in(cx, |workspace, window, cx| {
7833                workspace.open_abs_path(
7834                    PathBuf::from("/test/foo.txt"),
7835                    OpenOptions {
7836                        visible: Some(OpenVisible::All),
7837                        ..OpenOptions::default()
7838                    },
7839                    window,
7840                    cx,
7841                )
7842            })
7843            .await
7844            .unwrap()
7845            .downcast::<Editor>()
7846            .unwrap();
7847
7848        let search_bar = workspace.update_in(cx, |_, window, cx| {
7849            cx.new(|cx| {
7850                let mut search_bar = BufferSearchBar::new(None, window, cx);
7851                search_bar.set_active_pane_item(Some(&editor), window, cx);
7852                search_bar.show(window, cx);
7853                search_bar
7854            })
7855        });
7856
7857        let outline_panel = outline_panel(&workspace, cx);
7858
7859        outline_panel.update_in(cx, |outline_panel, window, cx| {
7860            outline_panel.set_active(true, window, cx)
7861        });
7862
7863        search_bar
7864            .update_in(cx, |search_bar, window, cx| {
7865                search_bar.search("  ", None, true, window, cx)
7866            })
7867            .await
7868            .unwrap();
7869
7870        cx.executor()
7871            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(500));
7872        cx.run_until_parked();
7873
7874        outline_panel.update(cx, |outline_panel, cx| {
7875            assert_eq!(
7876                display_entries(
7877                    &project,
7878                    &snapshot(outline_panel, cx),
7879                    &outline_panel.cached_entries,
7880                    outline_panel.selected_entry(),
7881                    cx,
7882                ),
7883                "search: | Field«  »        | Meaning                |  <==== selected
7884search: | Field  «  »      | Meaning                |
7885search: | Field    «  »    | Meaning                |
7886search: | Field      «  »  | Meaning                |
7887search: | Field        «  »| Meaning                |
7888search: | Field          | Meaning«  »              |
7889search: | Field          | Meaning  «  »            |
7890search: | Field          | Meaning    «  »          |
7891search: | Field          | Meaning      «  »        |
7892search: | Field          | Meaning        «  »      |
7893search: | Field          | Meaning          «  »    |
7894search: | Field          | Meaning            «  »  |
7895search: | Field          | Meaning              «  »|"
7896            );
7897        });
7898    }
7899
7900    #[gpui::test]
7901    async fn test_outline_panel_lsp_document_symbols(cx: &mut TestAppContext) {
7902        init_test(cx);
7903
7904        let root = path!("/root");
7905        let fs = FakeFs::new(cx.background_executor.clone());
7906        fs.insert_tree(
7907            root,
7908            json!({
7909                "src": {
7910                    "lib.rs": "struct Foo {\n    bar: u32,\n    baz: String,\n}\n",
7911                }
7912            }),
7913        )
7914        .await;
7915
7916        let project = Project::test(fs.clone(), [Path::new(root)], cx).await;
7917        let language_registry = project.read_with(cx, |project, _| {
7918            project.languages().add(rust_lang());
7919            project.languages().clone()
7920        });
7921
7922        let mut fake_language_servers = language_registry.register_fake_lsp(
7923            "Rust",
7924            FakeLspAdapter {
7925                capabilities: lsp::ServerCapabilities {
7926                    document_symbol_provider: Some(lsp::OneOf::Left(true)),
7927                    ..lsp::ServerCapabilities::default()
7928                },
7929                initializer: Some(Box::new(|fake_language_server| {
7930                    fake_language_server
7931                        .set_request_handler::<lsp::request::DocumentSymbolRequest, _, _>(
7932                            move |_, _| async move {
7933                                #[allow(deprecated)]
7934                                Ok(Some(lsp::DocumentSymbolResponse::Nested(vec![
7935                                    lsp::DocumentSymbol {
7936                                        name: "Foo".to_string(),
7937                                        detail: None,
7938                                        kind: lsp::SymbolKind::STRUCT,
7939                                        tags: None,
7940                                        deprecated: None,
7941                                        range: lsp::Range::new(
7942                                            lsp::Position::new(0, 0),
7943                                            lsp::Position::new(3, 1),
7944                                        ),
7945                                        selection_range: lsp::Range::new(
7946                                            lsp::Position::new(0, 7),
7947                                            lsp::Position::new(0, 10),
7948                                        ),
7949                                        children: Some(vec![
7950                                            lsp::DocumentSymbol {
7951                                                name: "bar".to_string(),
7952                                                detail: None,
7953                                                kind: lsp::SymbolKind::FIELD,
7954                                                tags: None,
7955                                                deprecated: None,
7956                                                range: lsp::Range::new(
7957                                                    lsp::Position::new(1, 4),
7958                                                    lsp::Position::new(1, 13),
7959                                                ),
7960                                                selection_range: lsp::Range::new(
7961                                                    lsp::Position::new(1, 4),
7962                                                    lsp::Position::new(1, 7),
7963                                                ),
7964                                                children: None,
7965                                            },
7966                                            lsp::DocumentSymbol {
7967                                                name: "lsp_only_field".to_string(),
7968                                                detail: None,
7969                                                kind: lsp::SymbolKind::FIELD,
7970                                                tags: None,
7971                                                deprecated: None,
7972                                                range: lsp::Range::new(
7973                                                    lsp::Position::new(2, 4),
7974                                                    lsp::Position::new(2, 15),
7975                                                ),
7976                                                selection_range: lsp::Range::new(
7977                                                    lsp::Position::new(2, 4),
7978                                                    lsp::Position::new(2, 7),
7979                                                ),
7980                                                children: None,
7981                                            },
7982                                        ]),
7983                                    },
7984                                ])))
7985                            },
7986                        );
7987                })),
7988                ..FakeLspAdapter::default()
7989            },
7990        );
7991
7992        let (window, workspace) = add_outline_panel(&project, cx).await;
7993        let cx = &mut VisualTestContext::from_window(window.into(), cx);
7994        let outline_panel = outline_panel(&workspace, cx);
7995        cx.update(|window, cx| {
7996            outline_panel.update(cx, |outline_panel, cx| {
7997                outline_panel.set_active(true, window, cx)
7998            });
7999        });
8000
8001        let _editor = workspace
8002            .update_in(cx, |workspace, window, cx| {
8003                workspace.open_abs_path(
8004                    PathBuf::from(path!("/root/src/lib.rs")),
8005                    OpenOptions {
8006                        visible: Some(OpenVisible::All),
8007                        ..OpenOptions::default()
8008                    },
8009                    window,
8010                    cx,
8011                )
8012            })
8013            .await
8014            .expect("Failed to open Rust source file")
8015            .downcast::<Editor>()
8016            .expect("Should open an editor for Rust source file");
8017        let _fake_language_server = fake_language_servers.next().await.unwrap();
8018        cx.executor()
8019            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
8020        cx.run_until_parked();
8021
8022        // Step 1: tree-sitter outlines by default
8023        outline_panel.update(cx, |outline_panel, cx| {
8024            assert_eq!(
8025                display_entries(
8026                    &project,
8027                    &snapshot(outline_panel, cx),
8028                    &outline_panel.cached_entries,
8029                    outline_panel.selected_entry(),
8030                    cx,
8031                ),
8032                indoc!(
8033                    "
8034outline: struct Foo  <==== selected
8035  outline: bar
8036  outline: baz"
8037                ),
8038                "Step 1: tree-sitter outlines should be displayed by default"
8039            );
8040        });
8041
8042        // Step 2: Switch to LSP document symbols
8043        cx.update(|_, cx| {
8044            settings::SettingsStore::update_global(
8045                cx,
8046                |store: &mut settings::SettingsStore, cx| {
8047                    store.update_user_settings(cx, |settings| {
8048                        settings.project.all_languages.defaults.document_symbols =
8049                            Some(settings::DocumentSymbols::On);
8050                    });
8051                },
8052            );
8053        });
8054        cx.executor()
8055            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
8056        cx.run_until_parked();
8057
8058        outline_panel.update(cx, |outline_panel, cx| {
8059            assert_eq!(
8060                display_entries(
8061                    &project,
8062                    &snapshot(outline_panel, cx),
8063                    &outline_panel.cached_entries,
8064                    outline_panel.selected_entry(),
8065                    cx,
8066                ),
8067                indoc!(
8068                    "
8069outline: struct Foo  <==== selected
8070  outline: bar
8071  outline: lsp_only_field"
8072                ),
8073                "Step 2: After switching to LSP, should see LSP-provided symbols"
8074            );
8075        });
8076
8077        // Step 3: Switch back to tree-sitter
8078        cx.update(|_, cx| {
8079            settings::SettingsStore::update_global(
8080                cx,
8081                |store: &mut settings::SettingsStore, cx| {
8082                    store.update_user_settings(cx, |settings| {
8083                        settings.project.all_languages.defaults.document_symbols =
8084                            Some(settings::DocumentSymbols::Off);
8085                    });
8086                },
8087            );
8088        });
8089        cx.executor()
8090            .advance_clock(UPDATE_DEBOUNCE + Duration::from_millis(100));
8091        cx.run_until_parked();
8092
8093        outline_panel.update(cx, |outline_panel, cx| {
8094            assert_eq!(
8095                display_entries(
8096                    &project,
8097                    &snapshot(outline_panel, cx),
8098                    &outline_panel.cached_entries,
8099                    outline_panel.selected_entry(),
8100                    cx,
8101                ),
8102                indoc!(
8103                    "
8104outline: struct Foo  <==== selected
8105  outline: bar
8106  outline: baz"
8107                ),
8108                "Step 3: tree-sitter outlines should be restored"
8109            );
8110        });
8111    }
8112}