1#[cfg(test)]
2mod file_finder_tests;
3
4use futures::future::join_all;
5pub use open_path_prompt::OpenPathDelegate;
6
7use channel::ChannelStore;
8use client::ChannelId;
9use collections::HashMap;
10use editor::Editor;
11use file_icons::FileIcons;
12use fuzzy::{CharBag, PathMatch, PathMatchCandidate, StringMatch, StringMatchCandidate};
13use gpui::{
14 Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
15 KeyContext, Modifiers, ModifiersChangedEvent, ParentElement, Render, Styled, Task, WeakEntity,
16 Window, actions, rems,
17};
18use open_path_prompt::{
19 OpenPathPrompt,
20 file_finder_settings::{FileFinderSettings, FileFinderWidth},
21};
22use picker::{Picker, PickerDelegate};
23use project::{
24 PathMatchCandidateSet, Project, ProjectPath, WorktreeId, worktree_store::WorktreeStore,
25};
26use project_panel::project_panel_settings::ProjectPanelSettings;
27use settings::Settings;
28use std::{
29 borrow::Cow,
30 cmp,
31 ops::Range,
32 path::{Component, Path, PathBuf},
33 sync::{
34 Arc,
35 atomic::{self, AtomicBool},
36 },
37};
38use ui::{
39 ButtonLike, ContextMenu, HighlightedLabel, Indicator, KeyBinding, ListItem, ListItemSpacing,
40 PopoverMenu, PopoverMenuHandle, TintColor, Tooltip, prelude::*,
41};
42use util::{
43 ResultExt, maybe,
44 paths::{PathStyle, PathWithPosition},
45 post_inc,
46 rel_path::RelPath,
47};
48use workspace::{
49 ModalView, OpenChannelNotesById, OpenOptions, OpenVisible, SplitDirection, Workspace,
50 item::PreviewTabsSettings, notifications::NotifyResultExt, pane,
51};
52use zed_actions::search::ToggleIncludeIgnored;
53
54actions!(
55 file_finder,
56 [
57 /// Selects the previous item in the file finder.
58 SelectPrevious,
59 /// Toggles the file filter menu.
60 ToggleFilterMenu,
61 /// Toggles the split direction menu.
62 ToggleSplitMenu
63 ]
64);
65
66impl ModalView for FileFinder {
67 fn on_before_dismiss(
68 &mut self,
69 window: &mut Window,
70 cx: &mut Context<Self>,
71 ) -> workspace::DismissDecision {
72 let submenu_focused = self.picker.update(cx, |picker, cx| {
73 picker
74 .delegate
75 .filter_popover_menu_handle
76 .is_focused(window, cx)
77 || picker
78 .delegate
79 .split_popover_menu_handle
80 .is_focused(window, cx)
81 });
82 workspace::DismissDecision::Dismiss(!submenu_focused)
83 }
84}
85
86pub struct FileFinder {
87 picker: Entity<Picker<FileFinderDelegate>>,
88 picker_focus_handle: FocusHandle,
89 init_modifiers: Option<Modifiers>,
90}
91
92pub fn init(cx: &mut App) {
93 cx.observe_new(FileFinder::register).detach();
94 cx.observe_new(OpenPathPrompt::register).detach();
95 cx.observe_new(OpenPathPrompt::register_new_path).detach();
96}
97
98impl FileFinder {
99 fn register(
100 workspace: &mut Workspace,
101 _window: Option<&mut Window>,
102 _: &mut Context<Workspace>,
103 ) {
104 workspace.register_action(
105 |workspace, action: &workspace::ToggleFileFinder, window, cx| {
106 let Some(file_finder) = workspace.active_modal::<Self>(cx) else {
107 Self::open(workspace, action.separate_history, window, cx).detach();
108 return;
109 };
110
111 file_finder.update(cx, |file_finder, cx| {
112 file_finder.init_modifiers = Some(window.modifiers());
113 file_finder.picker.update(cx, |picker, cx| {
114 picker.cycle_selection(window, cx);
115 });
116 });
117 },
118 );
119 }
120
121 fn open(
122 workspace: &mut Workspace,
123 separate_history: bool,
124 window: &mut Window,
125 cx: &mut Context<Workspace>,
126 ) -> Task<()> {
127 let project = workspace.project().read(cx);
128 let fs = project.fs();
129
130 let currently_opened_path = workspace.active_item(cx).and_then(|item| {
131 let project_path = item.project_path(cx)?;
132 let abs_path = project
133 .worktree_for_id(project_path.worktree_id, cx)?
134 .read(cx)
135 .absolutize(&project_path.path);
136 Some(FoundPath::new(project_path, abs_path))
137 });
138
139 let history_items = workspace
140 .recent_navigation_history(Some(MAX_RECENT_SELECTIONS), cx)
141 .into_iter()
142 .filter_map(|(project_path, abs_path)| {
143 if project.entry_for_path(&project_path, cx).is_some() {
144 return Some(Task::ready(Some(FoundPath::new(project_path, abs_path?))));
145 }
146 let abs_path = abs_path?;
147 if project.is_local() {
148 let fs = fs.clone();
149 Some(cx.background_spawn(async move {
150 if fs.is_file(&abs_path).await {
151 Some(FoundPath::new(project_path, abs_path))
152 } else {
153 None
154 }
155 }))
156 } else {
157 Some(Task::ready(Some(FoundPath::new(project_path, abs_path))))
158 }
159 })
160 .collect::<Vec<_>>();
161 cx.spawn_in(window, async move |workspace, cx| {
162 let history_items = join_all(history_items).await.into_iter().flatten();
163
164 workspace
165 .update_in(cx, |workspace, window, cx| {
166 let project = workspace.project().clone();
167 let weak_workspace = cx.entity().downgrade();
168 workspace.toggle_modal(window, cx, |window, cx| {
169 let delegate = FileFinderDelegate::new(
170 cx.entity().downgrade(),
171 weak_workspace,
172 project,
173 currently_opened_path,
174 history_items.collect(),
175 separate_history,
176 window,
177 cx,
178 );
179
180 FileFinder::new(delegate, window, cx)
181 });
182 })
183 .ok();
184 })
185 }
186
187 fn new(delegate: FileFinderDelegate, window: &mut Window, cx: &mut Context<Self>) -> Self {
188 let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
189 let picker_focus_handle = picker.focus_handle(cx);
190 picker.update(cx, |picker, _| {
191 picker.delegate.focus_handle = picker_focus_handle.clone();
192 });
193 Self {
194 picker,
195 picker_focus_handle,
196 init_modifiers: window.modifiers().modified().then_some(window.modifiers()),
197 }
198 }
199
200 fn handle_modifiers_changed(
201 &mut self,
202 event: &ModifiersChangedEvent,
203 window: &mut Window,
204 cx: &mut Context<Self>,
205 ) {
206 let Some(init_modifiers) = self.init_modifiers.take() else {
207 return;
208 };
209 if self.picker.read(cx).delegate.has_changed_selected_index
210 && (!event.modified() || !init_modifiers.is_subset_of(event))
211 {
212 self.init_modifiers = None;
213 window.dispatch_action(menu::Confirm.boxed_clone(), cx);
214 }
215 }
216
217 fn handle_select_prev(
218 &mut self,
219 _: &SelectPrevious,
220 window: &mut Window,
221 cx: &mut Context<Self>,
222 ) {
223 self.init_modifiers = Some(window.modifiers());
224 window.dispatch_action(Box::new(menu::SelectPrevious), cx);
225 }
226
227 fn handle_filter_toggle_menu(
228 &mut self,
229 _: &ToggleFilterMenu,
230 window: &mut Window,
231 cx: &mut Context<Self>,
232 ) {
233 self.picker.update(cx, |picker, cx| {
234 let menu_handle = &picker.delegate.filter_popover_menu_handle;
235 if menu_handle.is_deployed() {
236 menu_handle.hide(cx);
237 } else {
238 menu_handle.show(window, cx);
239 }
240 });
241 }
242
243 fn handle_split_toggle_menu(
244 &mut self,
245 _: &ToggleSplitMenu,
246 window: &mut Window,
247 cx: &mut Context<Self>,
248 ) {
249 self.picker.update(cx, |picker, cx| {
250 let menu_handle = &picker.delegate.split_popover_menu_handle;
251 if menu_handle.is_deployed() {
252 menu_handle.hide(cx);
253 } else {
254 menu_handle.show(window, cx);
255 }
256 });
257 }
258
259 fn handle_toggle_ignored(
260 &mut self,
261 _: &ToggleIncludeIgnored,
262 window: &mut Window,
263 cx: &mut Context<Self>,
264 ) {
265 self.picker.update(cx, |picker, cx| {
266 picker.delegate.include_ignored = match picker.delegate.include_ignored {
267 Some(true) => FileFinderSettings::get_global(cx)
268 .include_ignored
269 .map(|_| false),
270 Some(false) => Some(true),
271 None => Some(true),
272 };
273 picker.delegate.include_ignored_refresh =
274 picker.delegate.update_matches(picker.query(cx), window, cx);
275 });
276 }
277
278 fn go_to_file_split_left(
279 &mut self,
280 _: &pane::SplitLeft,
281 window: &mut Window,
282 cx: &mut Context<Self>,
283 ) {
284 self.go_to_file_split_inner(SplitDirection::Left, window, cx)
285 }
286
287 fn go_to_file_split_right(
288 &mut self,
289 _: &pane::SplitRight,
290 window: &mut Window,
291 cx: &mut Context<Self>,
292 ) {
293 self.go_to_file_split_inner(SplitDirection::Right, window, cx)
294 }
295
296 fn go_to_file_split_up(
297 &mut self,
298 _: &pane::SplitUp,
299 window: &mut Window,
300 cx: &mut Context<Self>,
301 ) {
302 self.go_to_file_split_inner(SplitDirection::Up, window, cx)
303 }
304
305 fn go_to_file_split_down(
306 &mut self,
307 _: &pane::SplitDown,
308 window: &mut Window,
309 cx: &mut Context<Self>,
310 ) {
311 self.go_to_file_split_inner(SplitDirection::Down, window, cx)
312 }
313
314 fn go_to_file_split_inner(
315 &mut self,
316 split_direction: SplitDirection,
317 window: &mut Window,
318 cx: &mut Context<Self>,
319 ) {
320 self.picker.update(cx, |picker, cx| {
321 let delegate = &mut picker.delegate;
322 if let Some(workspace) = delegate.workspace.upgrade()
323 && let Some(m) = delegate.matches.get(delegate.selected_index())
324 {
325 let path = match m {
326 Match::History { path, .. } => {
327 let worktree_id = path.project.worktree_id;
328 ProjectPath {
329 worktree_id,
330 path: Arc::clone(&path.project.path),
331 }
332 }
333 Match::Search(m) => ProjectPath {
334 worktree_id: WorktreeId::from_usize(m.0.worktree_id),
335 path: m.0.path.clone(),
336 },
337 Match::CreateNew(p) => p.clone(),
338 Match::Channel { .. } => return,
339 };
340 let open_task = workspace.update(cx, move |workspace, cx| {
341 workspace.split_path_preview(path, false, Some(split_direction), window, cx)
342 });
343 open_task.detach_and_log_err(cx);
344 }
345 })
346 }
347
348 pub fn modal_max_width(width_setting: FileFinderWidth, window: &mut Window) -> Pixels {
349 let window_width = window.viewport_size().width;
350 let small_width = rems(34.).to_pixels(window.rem_size());
351
352 match width_setting {
353 FileFinderWidth::Small => small_width,
354 FileFinderWidth::Full => window_width,
355 FileFinderWidth::XLarge => (window_width - px(512.)).max(small_width),
356 FileFinderWidth::Large => (window_width - px(768.)).max(small_width),
357 FileFinderWidth::Medium => (window_width - px(1024.)).max(small_width),
358 }
359 }
360}
361
362impl EventEmitter<DismissEvent> for FileFinder {}
363
364impl Focusable for FileFinder {
365 fn focus_handle(&self, _: &App) -> FocusHandle {
366 self.picker_focus_handle.clone()
367 }
368}
369
370impl Render for FileFinder {
371 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
372 let key_context = self.picker.read(cx).delegate.key_context(window, cx);
373
374 let file_finder_settings = FileFinderSettings::get_global(cx);
375 let modal_max_width = Self::modal_max_width(file_finder_settings.modal_max_width, window);
376
377 v_flex()
378 .key_context(key_context)
379 .w(modal_max_width)
380 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
381 .on_action(cx.listener(Self::handle_select_prev))
382 .on_action(cx.listener(Self::handle_filter_toggle_menu))
383 .on_action(cx.listener(Self::handle_split_toggle_menu))
384 .on_action(cx.listener(Self::handle_toggle_ignored))
385 .on_action(cx.listener(Self::go_to_file_split_left))
386 .on_action(cx.listener(Self::go_to_file_split_right))
387 .on_action(cx.listener(Self::go_to_file_split_up))
388 .on_action(cx.listener(Self::go_to_file_split_down))
389 .child(self.picker.clone())
390 }
391}
392
393pub struct FileFinderDelegate {
394 file_finder: WeakEntity<FileFinder>,
395 workspace: WeakEntity<Workspace>,
396 project: Entity<Project>,
397 channel_store: Option<Entity<ChannelStore>>,
398 search_count: usize,
399 latest_search_id: usize,
400 latest_search_did_cancel: bool,
401 latest_search_query: Option<FileSearchQuery>,
402 currently_opened_path: Option<FoundPath>,
403 matches: Matches,
404 selected_index: usize,
405 has_changed_selected_index: bool,
406 cancel_flag: Arc<AtomicBool>,
407 history_items: Vec<FoundPath>,
408 separate_history: bool,
409 first_update: bool,
410 filter_popover_menu_handle: PopoverMenuHandle<ContextMenu>,
411 split_popover_menu_handle: PopoverMenuHandle<ContextMenu>,
412 focus_handle: FocusHandle,
413 include_ignored: Option<bool>,
414 include_ignored_refresh: Task<()>,
415}
416
417/// Use a custom ordering for file finder: the regular one
418/// defines max element with the highest score and the latest alphanumerical path (in case of a tie on other params), e.g:
419/// `[{score: 0.5, path = "c/d" }, { score: 0.5, path = "/a/b" }]`
420///
421/// In the file finder, we would prefer to have the max element with the highest score and the earliest alphanumerical path, e.g:
422/// `[{ score: 0.5, path = "/a/b" }, {score: 0.5, path = "c/d" }]`
423/// as the files are shown in the project panel lists.
424#[derive(Debug, Clone, PartialEq, Eq)]
425struct ProjectPanelOrdMatch(PathMatch);
426
427impl Ord for ProjectPanelOrdMatch {
428 fn cmp(&self, other: &Self) -> cmp::Ordering {
429 self.0
430 .score
431 .partial_cmp(&other.0.score)
432 .unwrap_or(cmp::Ordering::Equal)
433 .then_with(|| self.0.worktree_id.cmp(&other.0.worktree_id))
434 .then_with(|| {
435 other
436 .0
437 .distance_to_relative_ancestor
438 .cmp(&self.0.distance_to_relative_ancestor)
439 })
440 .then_with(|| self.0.path.cmp(&other.0.path).reverse())
441 }
442}
443
444impl PartialOrd for ProjectPanelOrdMatch {
445 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
446 Some(self.cmp(other))
447 }
448}
449
450#[derive(Debug, Default)]
451struct Matches {
452 separate_history: bool,
453 matches: Vec<Match>,
454}
455
456#[derive(Debug, Clone)]
457enum Match {
458 History {
459 path: FoundPath,
460 panel_match: Option<ProjectPanelOrdMatch>,
461 },
462 Search(ProjectPanelOrdMatch),
463 Channel {
464 channel_id: ChannelId,
465 channel_name: SharedString,
466 string_match: StringMatch,
467 },
468 CreateNew(ProjectPath),
469}
470
471impl Match {
472 fn relative_path(&self) -> Option<&Arc<RelPath>> {
473 match self {
474 Match::History { path, .. } => Some(&path.project.path),
475 Match::Search(panel_match) => Some(&panel_match.0.path),
476 Match::Channel { .. } | Match::CreateNew(_) => None,
477 }
478 }
479
480 fn abs_path(&self, project: &Entity<Project>, cx: &App) -> Option<PathBuf> {
481 match self {
482 Match::History { path, .. } => Some(path.absolute.clone()),
483 Match::Search(ProjectPanelOrdMatch(path_match)) => Some(
484 project
485 .read(cx)
486 .worktree_for_id(WorktreeId::from_usize(path_match.worktree_id), cx)?
487 .read(cx)
488 .absolutize(&path_match.path),
489 ),
490 Match::Channel { .. } | Match::CreateNew(_) => None,
491 }
492 }
493
494 fn panel_match(&self) -> Option<&ProjectPanelOrdMatch> {
495 match self {
496 Match::History { panel_match, .. } => panel_match.as_ref(),
497 Match::Search(panel_match) => Some(panel_match),
498 Match::Channel { .. } | Match::CreateNew(_) => None,
499 }
500 }
501}
502
503impl Matches {
504 fn len(&self) -> usize {
505 self.matches.len()
506 }
507
508 fn get(&self, index: usize) -> Option<&Match> {
509 self.matches.get(index)
510 }
511
512 fn position(
513 &self,
514 entry: &Match,
515 currently_opened: Option<&FoundPath>,
516 ) -> Result<usize, usize> {
517 if let Match::History {
518 path,
519 panel_match: None,
520 } = entry
521 {
522 // Slow case: linear search by path. Should not happen actually,
523 // since we call `position` only if matches set changed, but the query has not changed.
524 // And History entries do not have panel_match if query is empty, so there's no
525 // reason for the matches set to change.
526 self.matches
527 .iter()
528 .position(|m| match m.relative_path() {
529 Some(p) => path.project.path == *p,
530 None => false,
531 })
532 .ok_or(0)
533 } else {
534 self.matches.binary_search_by(|m| {
535 // `reverse()` since if cmp_matches(a, b) == Ordering::Greater, then a is better than b.
536 // And we want the better entries go first.
537 Self::cmp_matches(self.separate_history, currently_opened, m, entry).reverse()
538 })
539 }
540 }
541
542 fn push_new_matches<'a>(
543 &'a mut self,
544 worktree_store: Entity<WorktreeStore>,
545 cx: &'a App,
546 history_items: impl IntoIterator<Item = &'a FoundPath> + Clone,
547 currently_opened: Option<&'a FoundPath>,
548 query: Option<&FileSearchQuery>,
549 new_search_matches: impl Iterator<Item = ProjectPanelOrdMatch>,
550 extend_old_matches: bool,
551 path_style: PathStyle,
552 ) {
553 let Some(query) = query else {
554 // assuming that if there's no query, then there's no search matches.
555 self.matches.clear();
556 let path_to_entry = |found_path: &FoundPath| Match::History {
557 path: found_path.clone(),
558 panel_match: None,
559 };
560
561 self.matches
562 .extend(history_items.into_iter().map(path_to_entry));
563 return;
564 };
565
566 let worktree_name_by_id = if should_hide_root_in_entry_path(&worktree_store, cx) {
567 None
568 } else {
569 Some(
570 worktree_store
571 .read(cx)
572 .worktrees()
573 .map(|worktree| {
574 let snapshot = worktree.read(cx).snapshot();
575 (snapshot.id(), snapshot.root_name().into())
576 })
577 .collect(),
578 )
579 };
580 let new_history_matches = matching_history_items(
581 history_items,
582 currently_opened,
583 worktree_name_by_id,
584 query,
585 path_style,
586 );
587 let new_search_matches: Vec<Match> = new_search_matches
588 .filter(|path_match| {
589 !new_history_matches.contains_key(&ProjectPath {
590 path: path_match.0.path.clone(),
591 worktree_id: WorktreeId::from_usize(path_match.0.worktree_id),
592 })
593 })
594 .map(Match::Search)
595 .collect();
596
597 if extend_old_matches {
598 // since we take history matches instead of new search matches
599 // and history matches has not changed(since the query has not changed and we do not extend old matches otherwise),
600 // old matches can't contain paths present in history_matches as well.
601 self.matches.retain(|m| matches!(m, Match::Search(_)));
602 } else {
603 self.matches.clear();
604 }
605
606 // At this point we have an unsorted set of new history matches, an unsorted set of new search matches
607 // and a sorted set of old search matches.
608 // It is possible that the new search matches' paths contain some of the old search matches' paths.
609 // History matches' paths are unique, since store in a HashMap by path.
610 // We build a sorted Vec<Match>, eliminating duplicate search matches.
611 // Search matches with the same paths should have equal `ProjectPanelOrdMatch`, so we should
612 // not have any duplicates after building the final list.
613 for new_match in new_history_matches
614 .into_values()
615 .chain(new_search_matches.into_iter())
616 {
617 match self.position(&new_match, currently_opened) {
618 Ok(_duplicate) => continue,
619 Err(i) => {
620 self.matches.insert(i, new_match);
621 if self.matches.len() == 100 {
622 break;
623 }
624 }
625 }
626 }
627 }
628
629 /// If a < b, then a is a worse match, aligning with the `ProjectPanelOrdMatch` ordering.
630 fn cmp_matches(
631 separate_history: bool,
632 currently_opened: Option<&FoundPath>,
633 a: &Match,
634 b: &Match,
635 ) -> cmp::Ordering {
636 // Handle CreateNew variant - always put it at the end
637 match (a, b) {
638 (Match::CreateNew(_), _) => return cmp::Ordering::Less,
639 (_, Match::CreateNew(_)) => return cmp::Ordering::Greater,
640 _ => {}
641 }
642
643 match (&a, &b) {
644 // bubble currently opened files to the top
645 (Match::History { path, .. }, _) if Some(path) == currently_opened => {
646 return cmp::Ordering::Greater;
647 }
648 (_, Match::History { path, .. }) if Some(path) == currently_opened => {
649 return cmp::Ordering::Less;
650 }
651
652 _ => {}
653 }
654
655 if separate_history {
656 match (a, b) {
657 (Match::History { .. }, Match::Search(_)) => return cmp::Ordering::Greater,
658 (Match::Search(_), Match::History { .. }) => return cmp::Ordering::Less,
659
660 _ => {}
661 }
662 }
663
664 // For file-vs-file matches, use the existing detailed comparison.
665 if let (Some(a_panel), Some(b_panel)) = (a.panel_match(), b.panel_match()) {
666 let a_in_filename = Self::is_filename_match(a_panel);
667 let b_in_filename = Self::is_filename_match(b_panel);
668
669 match (a_in_filename, b_in_filename) {
670 (true, false) => return cmp::Ordering::Greater,
671 (false, true) => return cmp::Ordering::Less,
672 _ => {}
673 }
674
675 return a_panel.cmp(b_panel);
676 }
677
678 let a_score = Self::match_score(a);
679 let b_score = Self::match_score(b);
680 // When at least one side is a channel, compare by raw score.
681 a_score
682 .partial_cmp(&b_score)
683 .unwrap_or(cmp::Ordering::Equal)
684 }
685
686 fn match_score(m: &Match) -> f64 {
687 match m {
688 Match::History { panel_match, .. } => panel_match.as_ref().map_or(0.0, |pm| pm.0.score),
689 Match::Search(pm) => pm.0.score,
690 Match::Channel { string_match, .. } => string_match.score,
691 Match::CreateNew(_) => 0.0,
692 }
693 }
694
695 /// Determines if the match occurred within the filename rather than in the path
696 fn is_filename_match(panel_match: &ProjectPanelOrdMatch) -> bool {
697 if panel_match.0.positions.is_empty() {
698 return false;
699 }
700
701 if let Some(filename) = panel_match.0.path.file_name() {
702 let path_str = panel_match.0.path.as_unix_str();
703
704 if let Some(filename_pos) = path_str.rfind(filename)
705 && panel_match.0.positions[0] >= filename_pos
706 {
707 let mut prev_position = panel_match.0.positions[0];
708 for p in &panel_match.0.positions[1..] {
709 if *p != prev_position + 1 {
710 return false;
711 }
712 prev_position = *p;
713 }
714 return true;
715 }
716 }
717
718 false
719 }
720}
721
722fn matching_history_items<'a>(
723 history_items: impl IntoIterator<Item = &'a FoundPath>,
724 currently_opened: Option<&'a FoundPath>,
725 worktree_name_by_id: Option<HashMap<WorktreeId, Arc<RelPath>>>,
726 query: &FileSearchQuery,
727 path_style: PathStyle,
728) -> HashMap<ProjectPath, Match> {
729 let mut candidates_paths = HashMap::default();
730
731 let history_items_by_worktrees = history_items
732 .into_iter()
733 .chain(currently_opened)
734 .filter_map(|found_path| {
735 let candidate = PathMatchCandidate {
736 is_dir: false, // You can't open directories as project items
737 path: &found_path.project.path,
738 // Only match history items names, otherwise their paths may match too many queries, producing false positives.
739 // E.g. `foo` would match both `something/foo/bar.rs` and `something/foo/foo.rs` and if the former is a history item,
740 // it would be shown first always, despite the latter being a better match.
741 char_bag: CharBag::from_iter(
742 found_path
743 .project
744 .path
745 .file_name()?
746 .to_string()
747 .to_lowercase()
748 .chars(),
749 ),
750 };
751 candidates_paths.insert(&found_path.project, found_path);
752 Some((found_path.project.worktree_id, candidate))
753 })
754 .fold(
755 HashMap::default(),
756 |mut candidates, (worktree_id, new_candidate)| {
757 candidates
758 .entry(worktree_id)
759 .or_insert_with(Vec::new)
760 .push(new_candidate);
761 candidates
762 },
763 );
764 let mut matching_history_paths = HashMap::default();
765 for (worktree, candidates) in history_items_by_worktrees {
766 let max_results = candidates.len() + 1;
767 let worktree_root_name = worktree_name_by_id
768 .as_ref()
769 .and_then(|w| w.get(&worktree).cloned());
770 matching_history_paths.extend(
771 fuzzy::match_fixed_path_set(
772 candidates,
773 worktree.to_usize(),
774 worktree_root_name,
775 query.path_query(),
776 false,
777 max_results,
778 path_style,
779 )
780 .into_iter()
781 .filter_map(|path_match| {
782 candidates_paths
783 .remove_entry(&ProjectPath {
784 worktree_id: WorktreeId::from_usize(path_match.worktree_id),
785 path: Arc::clone(&path_match.path),
786 })
787 .map(|(project_path, found_path)| {
788 (
789 project_path.clone(),
790 Match::History {
791 path: found_path.clone(),
792 panel_match: Some(ProjectPanelOrdMatch(path_match)),
793 },
794 )
795 })
796 }),
797 );
798 }
799 matching_history_paths
800}
801
802fn should_hide_root_in_entry_path(worktree_store: &Entity<WorktreeStore>, cx: &App) -> bool {
803 let multiple_worktrees = worktree_store
804 .read(cx)
805 .visible_worktrees(cx)
806 .filter(|worktree| !worktree.read(cx).is_single_file())
807 .nth(1)
808 .is_some();
809 ProjectPanelSettings::get_global(cx).hide_root && !multiple_worktrees
810}
811
812#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
813struct FoundPath {
814 project: ProjectPath,
815 absolute: PathBuf,
816}
817
818impl FoundPath {
819 fn new(project: ProjectPath, absolute: PathBuf) -> Self {
820 Self { project, absolute }
821 }
822}
823
824const MAX_RECENT_SELECTIONS: usize = 20;
825
826pub enum Event {
827 Selected(ProjectPath),
828 Dismissed,
829}
830
831#[derive(Debug, Clone)]
832struct FileSearchQuery {
833 raw_query: String,
834 file_query_end: Option<usize>,
835 path_position: PathWithPosition,
836}
837
838impl FileSearchQuery {
839 fn path_query(&self) -> &str {
840 match self.file_query_end {
841 Some(file_path_end) => &self.raw_query[..file_path_end],
842 None => &self.raw_query,
843 }
844 }
845}
846
847impl FileFinderDelegate {
848 fn new(
849 file_finder: WeakEntity<FileFinder>,
850 workspace: WeakEntity<Workspace>,
851 project: Entity<Project>,
852 currently_opened_path: Option<FoundPath>,
853 history_items: Vec<FoundPath>,
854 separate_history: bool,
855 window: &mut Window,
856 cx: &mut Context<FileFinder>,
857 ) -> Self {
858 Self::subscribe_to_updates(&project, window, cx);
859 let channel_store = if FileFinderSettings::get_global(cx).include_channels {
860 ChannelStore::try_global(cx)
861 } else {
862 None
863 };
864 Self {
865 file_finder,
866 workspace,
867 project,
868 channel_store,
869 search_count: 0,
870 latest_search_id: 0,
871 latest_search_did_cancel: false,
872 latest_search_query: None,
873 currently_opened_path,
874 matches: Matches::default(),
875 has_changed_selected_index: false,
876 selected_index: 0,
877 cancel_flag: Arc::new(AtomicBool::new(false)),
878 history_items,
879 separate_history,
880 first_update: true,
881 filter_popover_menu_handle: PopoverMenuHandle::default(),
882 split_popover_menu_handle: PopoverMenuHandle::default(),
883 focus_handle: cx.focus_handle(),
884 include_ignored: FileFinderSettings::get_global(cx).include_ignored,
885 include_ignored_refresh: Task::ready(()),
886 }
887 }
888
889 fn subscribe_to_updates(
890 project: &Entity<Project>,
891 window: &mut Window,
892 cx: &mut Context<FileFinder>,
893 ) {
894 cx.subscribe_in(project, window, |file_finder, _, event, window, cx| {
895 match event {
896 project::Event::WorktreeUpdatedEntries(_, _)
897 | project::Event::WorktreeAdded(_)
898 | project::Event::WorktreeRemoved(_) => file_finder
899 .picker
900 .update(cx, |picker, cx| picker.refresh(window, cx)),
901 _ => {}
902 };
903 })
904 .detach();
905 }
906
907 fn spawn_search(
908 &mut self,
909 query: FileSearchQuery,
910 window: &mut Window,
911 cx: &mut Context<Picker<Self>>,
912 ) -> Task<()> {
913 let relative_to = self
914 .currently_opened_path
915 .as_ref()
916 .map(|found_path| Arc::clone(&found_path.project.path));
917 let worktree_store = self.project.read(cx).worktree_store();
918 let worktrees = worktree_store
919 .read(cx)
920 .visible_worktrees_and_single_files(cx)
921 .collect::<Vec<_>>();
922 let include_root_name = !should_hide_root_in_entry_path(&worktree_store, cx);
923 let candidate_sets = worktrees
924 .into_iter()
925 .map(|worktree| {
926 let worktree = worktree.read(cx);
927 PathMatchCandidateSet {
928 snapshot: worktree.snapshot(),
929 include_ignored: self.include_ignored.unwrap_or_else(|| {
930 worktree.root_entry().is_some_and(|entry| entry.is_ignored)
931 }),
932 include_root_name,
933 candidates: project::Candidates::Files,
934 }
935 })
936 .collect::<Vec<_>>();
937
938 let search_id = util::post_inc(&mut self.search_count);
939 self.cancel_flag.store(true, atomic::Ordering::Release);
940 self.cancel_flag = Arc::new(AtomicBool::new(false));
941 let cancel_flag = self.cancel_flag.clone();
942 cx.spawn_in(window, async move |picker, cx| {
943 let matches = fuzzy::match_path_sets(
944 candidate_sets.as_slice(),
945 query.path_query(),
946 &relative_to,
947 false,
948 100,
949 &cancel_flag,
950 cx.background_executor().clone(),
951 )
952 .await
953 .into_iter()
954 .map(ProjectPanelOrdMatch);
955 let did_cancel = cancel_flag.load(atomic::Ordering::Acquire);
956 picker
957 .update(cx, |picker, cx| {
958 picker
959 .delegate
960 .set_search_matches(search_id, did_cancel, query, matches, cx)
961 })
962 .log_err();
963 })
964 }
965
966 fn set_search_matches(
967 &mut self,
968 search_id: usize,
969 did_cancel: bool,
970 query: FileSearchQuery,
971 matches: impl IntoIterator<Item = ProjectPanelOrdMatch>,
972 cx: &mut Context<Picker<Self>>,
973 ) {
974 if search_id >= self.latest_search_id {
975 self.latest_search_id = search_id;
976 let query_changed = Some(query.path_query())
977 != self
978 .latest_search_query
979 .as_ref()
980 .map(|query| query.path_query());
981 let extend_old_matches = self.latest_search_did_cancel && !query_changed;
982
983 let selected_match = if query_changed {
984 None
985 } else {
986 self.matches.get(self.selected_index).cloned()
987 };
988
989 let path_style = self.project.read(cx).path_style(cx);
990 self.matches.push_new_matches(
991 self.project.read(cx).worktree_store(),
992 cx,
993 &self.history_items,
994 self.currently_opened_path.as_ref(),
995 Some(&query),
996 matches.into_iter(),
997 extend_old_matches,
998 path_style,
999 );
1000
1001 // Add channel matches
1002 if let Some(channel_store) = &self.channel_store {
1003 let channel_store = channel_store.read(cx);
1004 let channels: Vec<_> = channel_store.channels().cloned().collect();
1005 if !channels.is_empty() {
1006 let candidates = channels
1007 .iter()
1008 .enumerate()
1009 .map(|(id, channel)| StringMatchCandidate::new(id, &channel.name));
1010 let channel_query = query.path_query();
1011 let query_lower = channel_query.to_lowercase();
1012 let mut channel_matches = Vec::new();
1013 for candidate in candidates {
1014 let channel_name = candidate.string;
1015 let name_lower = channel_name.to_lowercase();
1016
1017 let mut positions = Vec::new();
1018 let mut query_idx = 0;
1019 for (name_idx, name_char) in name_lower.char_indices() {
1020 if query_idx < query_lower.len() {
1021 let query_char =
1022 query_lower[query_idx..].chars().next().unwrap_or_default();
1023 if name_char == query_char {
1024 positions.push(name_idx);
1025 query_idx += query_char.len_utf8();
1026 }
1027 }
1028 }
1029
1030 if query_idx == query_lower.len() {
1031 let channel = &channels[candidate.id];
1032 let score = if name_lower == query_lower {
1033 1.0
1034 } else if name_lower.starts_with(&query_lower) {
1035 0.8
1036 } else {
1037 0.5 * (query_lower.len() as f64 / name_lower.len() as f64)
1038 };
1039 channel_matches.push(Match::Channel {
1040 channel_id: channel.id,
1041 channel_name: channel.name.clone(),
1042 string_match: StringMatch {
1043 candidate_id: candidate.id,
1044 score,
1045 positions,
1046 string: channel_name,
1047 },
1048 });
1049 }
1050 }
1051 for channel_match in channel_matches {
1052 match self
1053 .matches
1054 .position(&channel_match, self.currently_opened_path.as_ref())
1055 {
1056 Ok(_duplicate) => {}
1057 Err(ix) => self.matches.matches.insert(ix, channel_match),
1058 }
1059 }
1060 }
1061 }
1062
1063 let query_path = query.raw_query.as_str();
1064 if let Ok(mut query_path) = RelPath::new(Path::new(query_path), path_style) {
1065 let available_worktree = self
1066 .project
1067 .read(cx)
1068 .visible_worktrees(cx)
1069 .filter(|worktree| !worktree.read(cx).is_single_file())
1070 .collect::<Vec<_>>();
1071 let worktree_count = available_worktree.len();
1072 let mut expect_worktree = available_worktree.first().cloned();
1073 for worktree in &available_worktree {
1074 let worktree_root = worktree.read(cx).root_name();
1075 if worktree_count > 1 {
1076 if let Ok(suffix) = query_path.strip_prefix(worktree_root) {
1077 query_path = Cow::Owned(suffix.to_owned());
1078 expect_worktree = Some(worktree.clone());
1079 break;
1080 }
1081 }
1082 }
1083
1084 if let Some(FoundPath { ref project, .. }) = self.currently_opened_path {
1085 let worktree_id = project.worktree_id;
1086 let focused_file_in_available_worktree = available_worktree
1087 .iter()
1088 .any(|wt| wt.read(cx).id() == worktree_id);
1089
1090 if focused_file_in_available_worktree {
1091 expect_worktree = self.project.read(cx).worktree_for_id(worktree_id, cx);
1092 }
1093 }
1094
1095 if let Some(worktree) = expect_worktree {
1096 let worktree = worktree.read(cx);
1097 if worktree.entry_for_path(&query_path).is_none()
1098 && !query.raw_query.ends_with("/")
1099 && !(path_style.is_windows() && query.raw_query.ends_with("\\"))
1100 {
1101 self.matches.matches.push(Match::CreateNew(ProjectPath {
1102 worktree_id: worktree.id(),
1103 path: query_path.into_arc(),
1104 }));
1105 }
1106 }
1107 }
1108
1109 self.selected_index = selected_match.map_or_else(
1110 || self.calculate_selected_index(cx),
1111 |m| {
1112 self.matches
1113 .position(&m, self.currently_opened_path.as_ref())
1114 .unwrap_or(0)
1115 },
1116 );
1117
1118 self.latest_search_query = Some(query);
1119 self.latest_search_did_cancel = did_cancel;
1120
1121 cx.notify();
1122 }
1123 }
1124
1125 fn labels_for_match(
1126 &self,
1127 path_match: &Match,
1128 window: &mut Window,
1129 cx: &App,
1130 ) -> (HighlightedLabel, HighlightedLabel) {
1131 let path_style = self.project.read(cx).path_style(cx);
1132 let (file_name, file_name_positions, mut full_path, mut full_path_positions) =
1133 match &path_match {
1134 Match::History {
1135 path: entry_path,
1136 panel_match,
1137 } => {
1138 let worktree_id = entry_path.project.worktree_id;
1139 let worktree = self
1140 .project
1141 .read(cx)
1142 .worktree_for_id(worktree_id, cx)
1143 .filter(|worktree| worktree.read(cx).is_visible());
1144
1145 if let Some(panel_match) = panel_match {
1146 self.labels_for_path_match(&panel_match.0, path_style)
1147 } else if let Some(worktree) = worktree {
1148 let worktree_store = self.project.read(cx).worktree_store();
1149 let full_path = if should_hide_root_in_entry_path(&worktree_store, cx) {
1150 entry_path.project.path.clone()
1151 } else {
1152 worktree.read(cx).root_name().join(&entry_path.project.path)
1153 };
1154 let mut components = full_path.components();
1155 let filename = components.next_back().unwrap_or("");
1156 let prefix = components.rest();
1157 (
1158 filename.to_string(),
1159 Vec::new(),
1160 prefix.display(path_style).to_string() + path_style.primary_separator(),
1161 Vec::new(),
1162 )
1163 } else {
1164 (
1165 entry_path
1166 .absolute
1167 .file_name()
1168 .map_or(String::new(), |f| f.to_string_lossy().into_owned()),
1169 Vec::new(),
1170 entry_path.absolute.parent().map_or(String::new(), |path| {
1171 path.to_string_lossy().into_owned() + path_style.primary_separator()
1172 }),
1173 Vec::new(),
1174 )
1175 }
1176 }
1177 Match::Search(path_match) => self.labels_for_path_match(&path_match.0, path_style),
1178 Match::Channel {
1179 channel_name,
1180 string_match,
1181 ..
1182 } => (
1183 channel_name.to_string(),
1184 string_match.positions.clone(),
1185 "Channel Notes".to_string(),
1186 vec![],
1187 ),
1188 Match::CreateNew(project_path) => (
1189 format!("Create file: {}", project_path.path.display(path_style)),
1190 vec![],
1191 String::from(""),
1192 vec![],
1193 ),
1194 };
1195
1196 if file_name_positions.is_empty() {
1197 let user_home_path = util::paths::home_dir().to_string_lossy();
1198 if !user_home_path.is_empty() && full_path.starts_with(&*user_home_path) {
1199 full_path.replace_range(0..user_home_path.len(), "~");
1200 full_path_positions.retain_mut(|pos| {
1201 if *pos >= user_home_path.len() {
1202 *pos -= user_home_path.len();
1203 *pos += 1;
1204 true
1205 } else {
1206 false
1207 }
1208 })
1209 }
1210 }
1211
1212 if full_path.is_ascii() {
1213 let file_finder_settings = FileFinderSettings::get_global(cx);
1214 let max_width =
1215 FileFinder::modal_max_width(file_finder_settings.modal_max_width, window);
1216 let (normal_em, small_em) = {
1217 let style = window.text_style();
1218 let font_id = window.text_system().resolve_font(&style.font());
1219 let font_size = TextSize::Default.rems(cx).to_pixels(window.rem_size());
1220 let normal = cx
1221 .text_system()
1222 .em_width(font_id, font_size)
1223 .unwrap_or(px(16.));
1224 let font_size = TextSize::Small.rems(cx).to_pixels(window.rem_size());
1225 let small = cx
1226 .text_system()
1227 .em_width(font_id, font_size)
1228 .unwrap_or(px(10.));
1229 (normal, small)
1230 };
1231 let budget = full_path_budget(&file_name, normal_em, small_em, max_width);
1232 // If the computed budget is zero, we certainly won't be able to achieve it,
1233 // so no point trying to elide the path.
1234 if budget > 0 && full_path.len() > budget {
1235 let components = PathComponentSlice::new(&full_path);
1236 if let Some(elided_range) =
1237 components.elision_range(budget - 1, &full_path_positions)
1238 {
1239 let elided_len = elided_range.end - elided_range.start;
1240 let placeholder = "…";
1241 full_path_positions.retain_mut(|mat| {
1242 if *mat >= elided_range.end {
1243 *mat -= elided_len;
1244 *mat += placeholder.len();
1245 } else if *mat >= elided_range.start {
1246 return false;
1247 }
1248 true
1249 });
1250 full_path.replace_range(elided_range, placeholder);
1251 }
1252 }
1253 }
1254
1255 (
1256 HighlightedLabel::new(file_name, file_name_positions),
1257 HighlightedLabel::new(full_path, full_path_positions)
1258 .size(LabelSize::Small)
1259 .color(Color::Muted),
1260 )
1261 }
1262
1263 fn labels_for_path_match(
1264 &self,
1265 path_match: &PathMatch,
1266 path_style: PathStyle,
1267 ) -> (String, Vec<usize>, String, Vec<usize>) {
1268 let full_path = path_match.path_prefix.join(&path_match.path);
1269 let mut path_positions = path_match.positions.clone();
1270
1271 let file_name = full_path.file_name().unwrap_or("");
1272 let file_name_start = full_path.as_unix_str().len() - file_name.len();
1273 let file_name_positions = path_positions
1274 .iter()
1275 .filter_map(|pos| {
1276 if pos >= &file_name_start {
1277 Some(pos - file_name_start)
1278 } else {
1279 None
1280 }
1281 })
1282 .collect::<Vec<_>>();
1283
1284 let full_path = full_path
1285 .display(path_style)
1286 .trim_end_matches(&file_name)
1287 .to_string();
1288 path_positions.retain(|idx| *idx < full_path.len());
1289
1290 debug_assert!(
1291 file_name_positions
1292 .iter()
1293 .all(|ix| file_name[*ix..].chars().next().is_some()),
1294 "invalid file name positions {file_name:?} {file_name_positions:?}"
1295 );
1296 debug_assert!(
1297 path_positions
1298 .iter()
1299 .all(|ix| full_path[*ix..].chars().next().is_some()),
1300 "invalid path positions {full_path:?} {path_positions:?}"
1301 );
1302
1303 (
1304 file_name.to_string(),
1305 file_name_positions,
1306 full_path,
1307 path_positions,
1308 )
1309 }
1310
1311 /// Attempts to resolve an absolute file path and update the search matches if found.
1312 ///
1313 /// If the query path resolves to an absolute file that exists in the project,
1314 /// this method will find the corresponding worktree and relative path, create a
1315 /// match for it, and update the picker's search results.
1316 ///
1317 /// Returns `true` if the absolute path exists, otherwise returns `false`.
1318 fn lookup_absolute_path(
1319 &self,
1320 query: FileSearchQuery,
1321 window: &mut Window,
1322 cx: &mut Context<Picker<Self>>,
1323 ) -> Task<bool> {
1324 cx.spawn_in(window, async move |picker, cx| {
1325 let Some(project) = picker
1326 .read_with(cx, |picker, _| picker.delegate.project.clone())
1327 .log_err()
1328 else {
1329 return false;
1330 };
1331
1332 let query_path = Path::new(query.path_query());
1333 let mut path_matches = Vec::new();
1334
1335 let abs_file_exists = project
1336 .update(cx, |this, cx| {
1337 this.resolve_abs_file_path(query.path_query(), cx)
1338 })
1339 .await
1340 .is_some();
1341
1342 if abs_file_exists {
1343 project.update(cx, |project, cx| {
1344 if let Some((worktree, relative_path)) = project.find_worktree(query_path, cx) {
1345 path_matches.push(ProjectPanelOrdMatch(PathMatch {
1346 score: 1.0,
1347 positions: Vec::new(),
1348 worktree_id: worktree.read(cx).id().to_usize(),
1349 path: relative_path,
1350 path_prefix: RelPath::empty().into(),
1351 is_dir: false, // File finder doesn't support directories
1352 distance_to_relative_ancestor: usize::MAX,
1353 }));
1354 }
1355 });
1356 }
1357
1358 picker
1359 .update_in(cx, |picker, _, cx| {
1360 let picker_delegate = &mut picker.delegate;
1361 let search_id = util::post_inc(&mut picker_delegate.search_count);
1362 picker_delegate.set_search_matches(search_id, false, query, path_matches, cx);
1363
1364 anyhow::Ok(())
1365 })
1366 .log_err();
1367 abs_file_exists
1368 })
1369 }
1370
1371 /// Skips first history match (that is displayed topmost) if it's currently opened.
1372 fn calculate_selected_index(&self, cx: &mut Context<Picker<Self>>) -> usize {
1373 if FileFinderSettings::get_global(cx).skip_focus_for_active_in_search
1374 && let Some(Match::History { path, .. }) = self.matches.get(0)
1375 && Some(path) == self.currently_opened_path.as_ref()
1376 {
1377 let elements_after_first = self.matches.len() - 1;
1378 if elements_after_first > 0 {
1379 return 1;
1380 }
1381 }
1382
1383 0
1384 }
1385
1386 fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
1387 let mut key_context = KeyContext::new_with_defaults();
1388 key_context.add("FileFinder");
1389
1390 if self.filter_popover_menu_handle.is_focused(window, cx) {
1391 key_context.add("filter_menu_open");
1392 }
1393
1394 if self.split_popover_menu_handle.is_focused(window, cx) {
1395 key_context.add("split_menu_open");
1396 }
1397 key_context
1398 }
1399}
1400
1401fn full_path_budget(
1402 file_name: &str,
1403 normal_em: Pixels,
1404 small_em: Pixels,
1405 max_width: Pixels,
1406) -> usize {
1407 (((max_width / 0.8) - file_name.len() * normal_em) / small_em) as usize
1408}
1409
1410impl PickerDelegate for FileFinderDelegate {
1411 type ListItem = ListItem;
1412
1413 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
1414 "Search project files...".into()
1415 }
1416
1417 fn match_count(&self) -> usize {
1418 self.matches.len()
1419 }
1420
1421 fn selected_index(&self) -> usize {
1422 self.selected_index
1423 }
1424
1425 fn set_selected_index(&mut self, ix: usize, _: &mut Window, cx: &mut Context<Picker<Self>>) {
1426 self.has_changed_selected_index = true;
1427 self.selected_index = ix;
1428 cx.notify();
1429 }
1430
1431 fn separators_after_indices(&self) -> Vec<usize> {
1432 if self.separate_history {
1433 let first_non_history_index = self
1434 .matches
1435 .matches
1436 .iter()
1437 .enumerate()
1438 .find(|(_, m)| !matches!(m, Match::History { .. }))
1439 .map(|(i, _)| i);
1440 if let Some(first_non_history_index) = first_non_history_index
1441 && first_non_history_index > 0
1442 {
1443 return vec![first_non_history_index - 1];
1444 }
1445 }
1446 Vec::new()
1447 }
1448
1449 fn update_matches(
1450 &mut self,
1451 raw_query: String,
1452 window: &mut Window,
1453 cx: &mut Context<Picker<Self>>,
1454 ) -> Task<()> {
1455 let raw_query = raw_query.replace(' ', "");
1456 let raw_query = raw_query.trim();
1457
1458 let raw_query = match &raw_query.get(0..2) {
1459 Some(".\\" | "./") => &raw_query[2..],
1460 Some(prefix @ ("a\\" | "a/" | "b\\" | "b/")) => {
1461 if self
1462 .workspace
1463 .upgrade()
1464 .into_iter()
1465 .flat_map(|workspace| workspace.read(cx).worktrees(cx))
1466 .all(|worktree| {
1467 worktree
1468 .read(cx)
1469 .entry_for_path(RelPath::unix(prefix.split_at(1).0).unwrap())
1470 .is_none_or(|entry| !entry.is_dir())
1471 })
1472 {
1473 &raw_query[2..]
1474 } else {
1475 raw_query
1476 }
1477 }
1478 _ => raw_query,
1479 };
1480
1481 if raw_query.is_empty() {
1482 // if there was no query before, and we already have some (history) matches
1483 // there's no need to update anything, since nothing has changed.
1484 // We also want to populate matches set from history entries on the first update.
1485 if self.latest_search_query.is_some() || self.first_update {
1486 let project = self.project.read(cx);
1487
1488 self.latest_search_id = post_inc(&mut self.search_count);
1489 self.latest_search_query = None;
1490 self.matches = Matches {
1491 separate_history: self.separate_history,
1492 ..Matches::default()
1493 };
1494 let path_style = self.project.read(cx).path_style(cx);
1495
1496 self.matches.push_new_matches(
1497 project.worktree_store(),
1498 cx,
1499 self.history_items.iter().filter(|history_item| {
1500 project
1501 .worktree_for_id(history_item.project.worktree_id, cx)
1502 .is_some()
1503 || project.is_local()
1504 || project.is_via_remote_server()
1505 }),
1506 self.currently_opened_path.as_ref(),
1507 None,
1508 None.into_iter(),
1509 false,
1510 path_style,
1511 );
1512
1513 self.first_update = false;
1514 self.selected_index = 0;
1515 }
1516 cx.notify();
1517 Task::ready(())
1518 } else {
1519 let path_position = PathWithPosition::parse_str(raw_query);
1520 let raw_query = raw_query.trim().trim_end_matches(':').to_owned();
1521 let path = path_position.path.clone();
1522 let path_str = path_position.path.to_str();
1523 let path_trimmed = path_str.unwrap_or(&raw_query).trim_end_matches(':');
1524 let file_query_end = if path_trimmed == raw_query {
1525 None
1526 } else {
1527 // Safe to unwrap as we won't get here when the unwrap in if fails
1528 Some(path_str.unwrap().len())
1529 };
1530
1531 let query = FileSearchQuery {
1532 raw_query,
1533 file_query_end,
1534 path_position,
1535 };
1536
1537 cx.spawn_in(window, async move |this, cx| {
1538 let _ = maybe!(async move {
1539 let is_absolute_path = path.is_absolute();
1540 let did_resolve_abs_path = is_absolute_path
1541 && this
1542 .update_in(cx, |this, window, cx| {
1543 this.delegate
1544 .lookup_absolute_path(query.clone(), window, cx)
1545 })?
1546 .await;
1547
1548 // Only check for relative paths if no absolute paths were
1549 // found.
1550 if !did_resolve_abs_path {
1551 this.update_in(cx, |this, window, cx| {
1552 this.delegate.spawn_search(query, window, cx)
1553 })?
1554 .await;
1555 }
1556 anyhow::Ok(())
1557 })
1558 .await;
1559 })
1560 }
1561 }
1562
1563 fn confirm(
1564 &mut self,
1565 secondary: bool,
1566 window: &mut Window,
1567 cx: &mut Context<Picker<FileFinderDelegate>>,
1568 ) {
1569 if let Some(m) = self.matches.get(self.selected_index())
1570 && let Some(workspace) = self.workspace.upgrade()
1571 {
1572 // Channel matches are handled separately since they dispatch an action
1573 // rather than directly opening a file path.
1574 if let Match::Channel { channel_id, .. } = m {
1575 let channel_id = channel_id.0;
1576 let finder = self.file_finder.clone();
1577 window.dispatch_action(OpenChannelNotesById { channel_id }.boxed_clone(), cx);
1578 finder.update(cx, |_, cx| cx.emit(DismissEvent)).log_err();
1579 return;
1580 }
1581
1582 let open_task = workspace.update(cx, |workspace, cx| {
1583 let split_or_open =
1584 |workspace: &mut Workspace,
1585 project_path,
1586 window: &mut Window,
1587 cx: &mut Context<Workspace>| {
1588 let allow_preview =
1589 PreviewTabsSettings::get_global(cx).enable_preview_from_file_finder;
1590 if secondary {
1591 workspace.split_path_preview(
1592 project_path,
1593 allow_preview,
1594 None,
1595 window,
1596 cx,
1597 )
1598 } else {
1599 workspace.open_path_preview(
1600 project_path,
1601 None,
1602 true,
1603 allow_preview,
1604 true,
1605 window,
1606 cx,
1607 )
1608 }
1609 };
1610 match &m {
1611 Match::CreateNew(project_path) => {
1612 // Create a new file with the given filename
1613 if secondary {
1614 workspace.split_path_preview(
1615 project_path.clone(),
1616 false,
1617 None,
1618 window,
1619 cx,
1620 )
1621 } else {
1622 workspace.open_path_preview(
1623 project_path.clone(),
1624 None,
1625 true,
1626 false,
1627 true,
1628 window,
1629 cx,
1630 )
1631 }
1632 }
1633
1634 Match::History { path, .. } => {
1635 let worktree_id = path.project.worktree_id;
1636 if workspace
1637 .project()
1638 .read(cx)
1639 .worktree_for_id(worktree_id, cx)
1640 .is_some()
1641 {
1642 split_or_open(
1643 workspace,
1644 ProjectPath {
1645 worktree_id,
1646 path: Arc::clone(&path.project.path),
1647 },
1648 window,
1649 cx,
1650 )
1651 } else if secondary {
1652 workspace.split_abs_path(path.absolute.clone(), false, window, cx)
1653 } else {
1654 workspace.open_abs_path(
1655 path.absolute.clone(),
1656 OpenOptions {
1657 visible: Some(OpenVisible::None),
1658 ..Default::default()
1659 },
1660 window,
1661 cx,
1662 )
1663 }
1664 }
1665 Match::Search(m) => split_or_open(
1666 workspace,
1667 ProjectPath {
1668 worktree_id: WorktreeId::from_usize(m.0.worktree_id),
1669 path: m.0.path.clone(),
1670 },
1671 window,
1672 cx,
1673 ),
1674 Match::Channel { .. } => unreachable!("handled above"),
1675 }
1676 });
1677
1678 let row = self
1679 .latest_search_query
1680 .as_ref()
1681 .and_then(|query| query.path_position.row)
1682 .map(|row| row.saturating_sub(1));
1683 let col = self
1684 .latest_search_query
1685 .as_ref()
1686 .and_then(|query| query.path_position.column)
1687 .unwrap_or(0)
1688 .saturating_sub(1);
1689 let finder = self.file_finder.clone();
1690 let workspace = self.workspace.clone();
1691
1692 cx.spawn_in(window, async move |_, mut cx| {
1693 let item = open_task
1694 .await
1695 .notify_workspace_async_err(workspace, &mut cx)?;
1696 if let Some(row) = row
1697 && let Some(active_editor) = item.downcast::<Editor>()
1698 {
1699 active_editor
1700 .downgrade()
1701 .update_in(cx, |editor, window, cx| {
1702 let Some(buffer) = editor.buffer().read(cx).as_singleton() else {
1703 return;
1704 };
1705 let buffer_snapshot = buffer.read(cx).snapshot();
1706 let point = buffer_snapshot.point_from_external_input(row, col);
1707 editor.go_to_singleton_buffer_point(point, window, cx);
1708 })
1709 .log_err();
1710 }
1711 finder.update(cx, |_, cx| cx.emit(DismissEvent)).ok()?;
1712
1713 Some(())
1714 })
1715 .detach();
1716 }
1717 }
1718
1719 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<FileFinderDelegate>>) {
1720 self.file_finder
1721 .update(cx, |_, cx| cx.emit(DismissEvent))
1722 .log_err();
1723 }
1724
1725 fn render_match(
1726 &self,
1727 ix: usize,
1728 selected: bool,
1729 window: &mut Window,
1730 cx: &mut Context<Picker<Self>>,
1731 ) -> Option<Self::ListItem> {
1732 let settings = FileFinderSettings::get_global(cx);
1733
1734 let path_match = self.matches.get(ix)?;
1735
1736 let end_icon = match path_match {
1737 Match::History { .. } => Icon::new(IconName::HistoryRerun)
1738 .color(Color::Muted)
1739 .size(IconSize::Small)
1740 .into_any_element(),
1741 Match::Search(_) => v_flex()
1742 .flex_none()
1743 .size(IconSize::Small.rems())
1744 .into_any_element(),
1745 Match::Channel { .. } => v_flex()
1746 .flex_none()
1747 .size(IconSize::Small.rems())
1748 .into_any_element(),
1749 Match::CreateNew(_) => Icon::new(IconName::Plus)
1750 .color(Color::Muted)
1751 .size(IconSize::Small)
1752 .into_any_element(),
1753 };
1754 let (file_name_label, full_path_label) = self.labels_for_match(path_match, window, cx);
1755
1756 let file_icon = match path_match {
1757 Match::Channel { .. } => Some(Icon::new(IconName::Hash).color(Color::Muted)),
1758 _ => maybe!({
1759 if !settings.file_icons {
1760 return None;
1761 }
1762 let abs_path = path_match.abs_path(&self.project, cx)?;
1763 let file_name = abs_path.file_name()?;
1764 let icon = FileIcons::get_icon(file_name.as_ref(), cx)?;
1765 Some(Icon::from_path(icon).color(Color::Muted))
1766 }),
1767 };
1768
1769 Some(
1770 ListItem::new(ix)
1771 .spacing(ListItemSpacing::Sparse)
1772 .start_slot::<Icon>(file_icon)
1773 .end_slot::<AnyElement>(end_icon)
1774 .inset(true)
1775 .toggle_state(selected)
1776 .child(
1777 h_flex()
1778 .gap_2()
1779 .py_px()
1780 .child(file_name_label)
1781 .child(full_path_label),
1782 ),
1783 )
1784 }
1785
1786 fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
1787 let focus_handle = self.focus_handle.clone();
1788
1789 Some(
1790 h_flex()
1791 .w_full()
1792 .p_1p5()
1793 .justify_between()
1794 .border_t_1()
1795 .border_color(cx.theme().colors().border_variant)
1796 .child(
1797 PopoverMenu::new("filter-menu-popover")
1798 .with_handle(self.filter_popover_menu_handle.clone())
1799 .attach(gpui::Corner::BottomRight)
1800 .anchor(gpui::Corner::BottomLeft)
1801 .offset(gpui::Point {
1802 x: px(1.0),
1803 y: px(1.0),
1804 })
1805 .trigger_with_tooltip(
1806 IconButton::new("filter-trigger", IconName::Sliders)
1807 .icon_size(IconSize::Small)
1808 .icon_size(IconSize::Small)
1809 .toggle_state(self.include_ignored.unwrap_or(false))
1810 .when(self.include_ignored.is_some(), |this| {
1811 this.indicator(Indicator::dot().color(Color::Info))
1812 }),
1813 {
1814 let focus_handle = focus_handle.clone();
1815 move |_window, cx| {
1816 Tooltip::for_action_in(
1817 "Filter Options",
1818 &ToggleFilterMenu,
1819 &focus_handle,
1820 cx,
1821 )
1822 }
1823 },
1824 )
1825 .menu({
1826 let focus_handle = focus_handle.clone();
1827 let include_ignored = self.include_ignored;
1828
1829 move |window, cx| {
1830 Some(ContextMenu::build(window, cx, {
1831 let focus_handle = focus_handle.clone();
1832 move |menu, _, _| {
1833 menu.context(focus_handle.clone())
1834 .header("Filter Options")
1835 .toggleable_entry(
1836 "Include Ignored Files",
1837 include_ignored.unwrap_or(false),
1838 ui::IconPosition::End,
1839 Some(ToggleIncludeIgnored.boxed_clone()),
1840 move |window, cx| {
1841 window.focus(&focus_handle, cx);
1842 window.dispatch_action(
1843 ToggleIncludeIgnored.boxed_clone(),
1844 cx,
1845 );
1846 },
1847 )
1848 }
1849 }))
1850 }
1851 }),
1852 )
1853 .child(
1854 h_flex()
1855 .gap_0p5()
1856 .child(
1857 PopoverMenu::new("split-menu-popover")
1858 .with_handle(self.split_popover_menu_handle.clone())
1859 .attach(gpui::Corner::BottomRight)
1860 .anchor(gpui::Corner::BottomLeft)
1861 .offset(gpui::Point {
1862 x: px(1.0),
1863 y: px(1.0),
1864 })
1865 .trigger(
1866 ButtonLike::new("split-trigger")
1867 .child(Label::new("Split…"))
1868 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1869 .child(
1870 KeyBinding::for_action_in(
1871 &ToggleSplitMenu,
1872 &focus_handle,
1873 cx,
1874 )
1875 .size(rems_from_px(12.)),
1876 ),
1877 )
1878 .menu({
1879 let focus_handle = focus_handle.clone();
1880
1881 move |window, cx| {
1882 Some(ContextMenu::build(window, cx, {
1883 let focus_handle = focus_handle.clone();
1884 move |menu, _, _| {
1885 menu.context(focus_handle)
1886 .action(
1887 "Split Left",
1888 pane::SplitLeft::default().boxed_clone(),
1889 )
1890 .action(
1891 "Split Right",
1892 pane::SplitRight::default().boxed_clone(),
1893 )
1894 .action(
1895 "Split Up",
1896 pane::SplitUp::default().boxed_clone(),
1897 )
1898 .action(
1899 "Split Down",
1900 pane::SplitDown::default().boxed_clone(),
1901 )
1902 }
1903 }))
1904 }
1905 }),
1906 )
1907 .child(
1908 Button::new("open-selection", "Open")
1909 .key_binding(
1910 KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
1911 .map(|kb| kb.size(rems_from_px(12.))),
1912 )
1913 .on_click(|_, window, cx| {
1914 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1915 }),
1916 ),
1917 )
1918 .into_any(),
1919 )
1920 }
1921}
1922
1923#[derive(Clone, Debug, PartialEq, Eq)]
1924struct PathComponentSlice<'a> {
1925 path: Cow<'a, Path>,
1926 path_str: Cow<'a, str>,
1927 component_ranges: Vec<(Component<'a>, Range<usize>)>,
1928}
1929
1930impl<'a> PathComponentSlice<'a> {
1931 fn new(path: &'a str) -> Self {
1932 let trimmed_path = Path::new(path).components().as_path().as_os_str();
1933 let mut component_ranges = Vec::new();
1934 let mut components = Path::new(trimmed_path).components();
1935 let len = trimmed_path.as_encoded_bytes().len();
1936 let mut pos = 0;
1937 while let Some(component) = components.next() {
1938 component_ranges.push((component, pos..0));
1939 pos = len - components.as_path().as_os_str().as_encoded_bytes().len();
1940 }
1941 for ((_, range), ancestor) in component_ranges
1942 .iter_mut()
1943 .rev()
1944 .zip(Path::new(trimmed_path).ancestors())
1945 {
1946 range.end = ancestor.as_os_str().as_encoded_bytes().len();
1947 }
1948 Self {
1949 path: Cow::Borrowed(Path::new(path)),
1950 path_str: Cow::Borrowed(path),
1951 component_ranges,
1952 }
1953 }
1954
1955 fn elision_range(&self, budget: usize, matches: &[usize]) -> Option<Range<usize>> {
1956 let eligible_range = {
1957 assert!(matches.windows(2).all(|w| w[0] <= w[1]));
1958 let mut matches = matches.iter().copied().peekable();
1959 let mut longest: Option<Range<usize>> = None;
1960 let mut cur = 0..0;
1961 let mut seen_normal = false;
1962 for (i, (component, range)) in self.component_ranges.iter().enumerate() {
1963 let is_normal = matches!(component, Component::Normal(_));
1964 let is_first_normal = is_normal && !seen_normal;
1965 seen_normal |= is_normal;
1966 let is_last = i == self.component_ranges.len() - 1;
1967 let contains_match = matches.peek().is_some_and(|mat| range.contains(mat));
1968 if contains_match {
1969 matches.next();
1970 }
1971 if is_first_normal || is_last || !is_normal || contains_match {
1972 if longest
1973 .as_ref()
1974 .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1975 {
1976 longest = Some(cur);
1977 }
1978 cur = i + 1..i + 1;
1979 } else {
1980 cur.end = i + 1;
1981 }
1982 }
1983 if longest
1984 .as_ref()
1985 .is_none_or(|old| old.end - old.start <= cur.end - cur.start)
1986 {
1987 longest = Some(cur);
1988 }
1989 longest
1990 };
1991
1992 let eligible_range = eligible_range?;
1993 assert!(eligible_range.start <= eligible_range.end);
1994 if eligible_range.is_empty() {
1995 return None;
1996 }
1997
1998 let elided_range: Range<usize> = {
1999 let byte_range = self.component_ranges[eligible_range.start].1.start
2000 ..self.component_ranges[eligible_range.end - 1].1.end;
2001 let midpoint = self.path_str.len() / 2;
2002 let distance_from_start = byte_range.start.abs_diff(midpoint);
2003 let distance_from_end = byte_range.end.abs_diff(midpoint);
2004 let pick_from_end = distance_from_start > distance_from_end;
2005 let mut len_with_elision = self.path_str.len();
2006 let mut i = eligible_range.start;
2007 while i < eligible_range.end {
2008 let x = if pick_from_end {
2009 eligible_range.end - i + eligible_range.start - 1
2010 } else {
2011 i
2012 };
2013 len_with_elision -= self.component_ranges[x]
2014 .0
2015 .as_os_str()
2016 .as_encoded_bytes()
2017 .len()
2018 + 1;
2019 if len_with_elision <= budget {
2020 break;
2021 }
2022 i += 1;
2023 }
2024 if len_with_elision > budget {
2025 return None;
2026 } else if pick_from_end {
2027 let x = eligible_range.end - i + eligible_range.start - 1;
2028 x..eligible_range.end
2029 } else {
2030 let x = i;
2031 eligible_range.start..x + 1
2032 }
2033 };
2034
2035 let byte_range = self.component_ranges[elided_range.start].1.start
2036 ..self.component_ranges[elided_range.end - 1].1.end;
2037 Some(byte_range)
2038 }
2039}