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