1use fuzzy::PathMatch;
2use gpui::{
3 actions, elements::*, AnyViewHandle, AppContext, Entity, ModelHandle, MouseState,
4 MutableAppContext, RenderContext, Task, View, ViewContext, ViewHandle,
5};
6use picker::{Picker, PickerDelegate};
7use project::{PathMatchCandidateSet, Project, ProjectPath, WorktreeId};
8use settings::Settings;
9use std::{
10 path::Path,
11 sync::{
12 atomic::{self, AtomicBool},
13 Arc,
14 },
15};
16use util::post_inc;
17use workspace::Workspace;
18
19pub struct FileFinder {
20 project: ModelHandle<Project>,
21 picker: ViewHandle<Picker<Self>>,
22 search_count: usize,
23 latest_search_id: usize,
24 latest_search_did_cancel: bool,
25 latest_search_query: String,
26 relative_to: Option<Arc<Path>>,
27 matches: Vec<PathMatch>,
28 selected: Option<(usize, Arc<Path>)>,
29 cancel_flag: Arc<AtomicBool>,
30}
31
32actions!(file_finder, [Toggle]);
33
34pub fn init(cx: &mut MutableAppContext) {
35 cx.add_action(FileFinder::toggle);
36 Picker::<FileFinder>::init(cx);
37}
38
39pub enum Event {
40 Selected(ProjectPath),
41 Dismissed,
42}
43
44impl Entity for FileFinder {
45 type Event = Event;
46}
47
48impl View for FileFinder {
49 fn ui_name() -> &'static str {
50 "FileFinder"
51 }
52
53 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
54 ChildView::new(self.picker.clone(), cx).boxed()
55 }
56
57 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
58 if cx.is_self_focused() {
59 cx.focus(&self.picker);
60 }
61 }
62}
63
64impl FileFinder {
65 fn labels_for_match(&self, path_match: &PathMatch) -> (String, Vec<usize>, String, Vec<usize>) {
66 let path = &path_match.path;
67 let path_string = path.to_string_lossy();
68 let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
69 let path_positions = path_match.positions.clone();
70
71 let file_name = path.file_name().map_or_else(
72 || path_match.path_prefix.to_string(),
73 |file_name| file_name.to_string_lossy().to_string(),
74 );
75 let file_name_start = path_match.path_prefix.chars().count() + path_string.chars().count()
76 - file_name.chars().count();
77 let file_name_positions = path_positions
78 .iter()
79 .filter_map(|pos| {
80 if pos >= &file_name_start {
81 Some(pos - file_name_start)
82 } else {
83 None
84 }
85 })
86 .collect();
87
88 (file_name, file_name_positions, full_path, path_positions)
89 }
90
91 fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
92 workspace.toggle_modal(cx, |workspace, cx| {
93 let project = workspace.project().clone();
94 let relative_to = workspace
95 .active_item(cx)
96 .and_then(|item| item.project_path(cx))
97 .map(|project_path| project_path.path.clone());
98 let finder = cx.add_view(|cx| Self::new(project, relative_to, cx));
99 cx.subscribe(&finder, Self::on_event).detach();
100 finder
101 });
102 }
103
104 fn on_event(
105 workspace: &mut Workspace,
106 _: ViewHandle<FileFinder>,
107 event: &Event,
108 cx: &mut ViewContext<Workspace>,
109 ) {
110 match event {
111 Event::Selected(project_path) => {
112 workspace
113 .open_path(project_path.clone(), None, true, cx)
114 .detach_and_log_err(cx);
115 workspace.dismiss_modal(cx);
116 }
117 Event::Dismissed => {
118 workspace.dismiss_modal(cx);
119 }
120 }
121 }
122
123 pub fn new(
124 project: ModelHandle<Project>,
125 relative_to: Option<Arc<Path>>,
126 cx: &mut ViewContext<Self>,
127 ) -> Self {
128 let handle = cx.weak_handle();
129 cx.observe(&project, Self::project_updated).detach();
130 Self {
131 project,
132 picker: cx.add_view(|cx| Picker::new("Search project files...", handle, cx)),
133 search_count: 0,
134 latest_search_id: 0,
135 latest_search_did_cancel: false,
136 latest_search_query: String::new(),
137 relative_to,
138 matches: Vec::new(),
139 selected: None,
140 cancel_flag: Arc::new(AtomicBool::new(false)),
141 }
142 }
143
144 fn project_updated(&mut self, _: ModelHandle<Project>, cx: &mut ViewContext<Self>) {
145 self.spawn_search(self.picker.read(cx).query(cx), cx)
146 .detach();
147 }
148
149 fn spawn_search(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
150 let relative_to = self.relative_to.clone();
151 let worktrees = self
152 .project
153 .read(cx)
154 .visible_worktrees(cx)
155 .collect::<Vec<_>>();
156 let include_root_name = worktrees.len() > 1;
157 let candidate_sets = worktrees
158 .into_iter()
159 .map(|worktree| {
160 let worktree = worktree.read(cx);
161 PathMatchCandidateSet {
162 snapshot: worktree.snapshot(),
163 include_ignored: worktree
164 .root_entry()
165 .map_or(false, |entry| entry.is_ignored),
166 include_root_name,
167 }
168 })
169 .collect::<Vec<_>>();
170
171 let search_id = util::post_inc(&mut self.search_count);
172 self.cancel_flag.store(true, atomic::Ordering::Relaxed);
173 self.cancel_flag = Arc::new(AtomicBool::new(false));
174 let cancel_flag = self.cancel_flag.clone();
175 cx.spawn(|this, mut cx| async move {
176 let matches = fuzzy::match_path_sets(
177 candidate_sets.as_slice(),
178 &query,
179 relative_to,
180 false,
181 100,
182 &cancel_flag,
183 cx.background(),
184 )
185 .await;
186 let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
187 this.update(&mut cx, |this, cx| {
188 this.set_matches(search_id, did_cancel, query, matches, cx)
189 });
190 })
191 }
192
193 fn set_matches(
194 &mut self,
195 search_id: usize,
196 did_cancel: bool,
197 query: String,
198 matches: Vec<PathMatch>,
199 cx: &mut ViewContext<Self>,
200 ) {
201 if search_id >= self.latest_search_id {
202 self.latest_search_id = search_id;
203 if self.latest_search_did_cancel && query == self.latest_search_query {
204 util::extend_sorted(&mut self.matches, matches.into_iter(), 100, |a, b| b.cmp(a));
205 } else {
206 self.matches = matches;
207 }
208 self.latest_search_query = query;
209 self.latest_search_did_cancel = did_cancel;
210 cx.notify();
211 self.picker.update(cx, |_, cx| cx.notify());
212 }
213 }
214}
215
216impl PickerDelegate for FileFinder {
217 fn match_count(&self) -> usize {
218 self.matches.len()
219 }
220
221 fn selected_index(&self) -> usize {
222 if let Some(selected) = self.selected.as_ref() {
223 for (ix, path_match) in self.matches.iter().enumerate() {
224 if (path_match.worktree_id, path_match.path.as_ref())
225 == (selected.0, selected.1.as_ref())
226 {
227 return ix;
228 }
229 }
230 }
231 0
232 }
233
234 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>) {
235 let mat = &self.matches[ix];
236 self.selected = Some((mat.worktree_id, mat.path.clone()));
237 cx.notify();
238 }
239
240 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
241 if query.is_empty() {
242 self.latest_search_id = post_inc(&mut self.search_count);
243 self.matches.clear();
244 cx.notify();
245 Task::ready(())
246 } else {
247 self.spawn_search(query, cx)
248 }
249 }
250
251 fn confirm(&mut self, cx: &mut ViewContext<Self>) {
252 if let Some(m) = self.matches.get(self.selected_index()) {
253 cx.emit(Event::Selected(ProjectPath {
254 worktree_id: WorktreeId::from_usize(m.worktree_id),
255 path: m.path.clone(),
256 }));
257 }
258 }
259
260 fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
261 cx.emit(Event::Dismissed);
262 }
263
264 fn render_match(
265 &self,
266 ix: usize,
267 mouse_state: &mut MouseState,
268 selected: bool,
269 cx: &AppContext,
270 ) -> ElementBox {
271 let path_match = &self.matches[ix];
272 let settings = cx.global::<Settings>();
273 let style = settings.theme.picker.item.style_for(mouse_state, selected);
274 let (file_name, file_name_positions, full_path, full_path_positions) =
275 self.labels_for_match(path_match);
276 Flex::column()
277 .with_child(
278 Label::new(file_name, style.label.clone())
279 .with_highlights(file_name_positions)
280 .boxed(),
281 )
282 .with_child(
283 Label::new(full_path, style.label.clone())
284 .with_highlights(full_path_positions)
285 .boxed(),
286 )
287 .flex(1., false)
288 .contained()
289 .with_style(style.container)
290 .named("match")
291 }
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297 use editor::Editor;
298 use menu::{Confirm, SelectNext};
299 use serde_json::json;
300 use workspace::{AppState, Workspace};
301
302 #[ctor::ctor]
303 fn init_logger() {
304 if std::env::var("RUST_LOG").is_ok() {
305 env_logger::init();
306 }
307 }
308
309 #[gpui::test]
310 async fn test_matching_paths(cx: &mut gpui::TestAppContext) {
311 let app_state = cx.update(|cx| {
312 super::init(cx);
313 editor::init(cx);
314 AppState::test(cx)
315 });
316
317 app_state
318 .fs
319 .as_fake()
320 .insert_tree(
321 "/root",
322 json!({
323 "a": {
324 "banana": "",
325 "bandana": "",
326 }
327 }),
328 )
329 .await;
330
331 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
332 let (window_id, workspace) = cx.add_window(|cx| {
333 Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
334 });
335 cx.dispatch_action(window_id, Toggle);
336
337 let finder = cx.read(|cx| workspace.read(cx).modal::<FileFinder>().unwrap());
338 finder
339 .update(cx, |finder, cx| {
340 finder.update_matches("bna".to_string(), cx)
341 })
342 .await;
343 finder.read_with(cx, |finder, _| {
344 assert_eq!(finder.matches.len(), 2);
345 });
346
347 let active_pane = cx.read(|cx| workspace.read(cx).active_pane().clone());
348 cx.dispatch_action(window_id, SelectNext);
349 cx.dispatch_action(window_id, Confirm);
350 active_pane
351 .condition(cx, |pane, _| pane.active_item().is_some())
352 .await;
353 cx.read(|cx| {
354 let active_item = active_pane.read(cx).active_item().unwrap();
355 assert_eq!(
356 active_item
357 .to_any()
358 .downcast::<Editor>()
359 .unwrap()
360 .read(cx)
361 .title(cx),
362 "bandana"
363 );
364 });
365 }
366
367 #[gpui::test]
368 async fn test_matching_cancellation(cx: &mut gpui::TestAppContext) {
369 let app_state = cx.update(AppState::test);
370 app_state
371 .fs
372 .as_fake()
373 .insert_tree(
374 "/dir",
375 json!({
376 "hello": "",
377 "goodbye": "",
378 "halogen-light": "",
379 "happiness": "",
380 "height": "",
381 "hi": "",
382 "hiccup": "",
383 }),
384 )
385 .await;
386
387 let project = Project::test(app_state.fs.clone(), ["/dir".as_ref()], cx).await;
388 let (_, workspace) = cx.add_window(|cx| {
389 Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
390 });
391 let (_, finder) =
392 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
393
394 let query = "hi".to_string();
395 finder
396 .update(cx, |f, cx| f.spawn_search(query.clone(), cx))
397 .await;
398 finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 5));
399
400 finder.update(cx, |finder, cx| {
401 let matches = finder.matches.clone();
402
403 // Simulate a search being cancelled after the time limit,
404 // returning only a subset of the matches that would have been found.
405 drop(finder.spawn_search(query.clone(), cx));
406 finder.set_matches(
407 finder.latest_search_id,
408 true, // did-cancel
409 query.clone(),
410 vec![matches[1].clone(), matches[3].clone()],
411 cx,
412 );
413
414 // Simulate another cancellation.
415 drop(finder.spawn_search(query.clone(), cx));
416 finder.set_matches(
417 finder.latest_search_id,
418 true, // did-cancel
419 query.clone(),
420 vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
421 cx,
422 );
423
424 assert_eq!(finder.matches, matches[0..4])
425 });
426 }
427
428 #[gpui::test]
429 async fn test_ignored_files(cx: &mut gpui::TestAppContext) {
430 let app_state = cx.update(AppState::test);
431 app_state
432 .fs
433 .as_fake()
434 .insert_tree(
435 "/ancestor",
436 json!({
437 ".gitignore": "ignored-root",
438 "ignored-root": {
439 "happiness": "",
440 "height": "",
441 "hi": "",
442 "hiccup": "",
443 },
444 "tracked-root": {
445 ".gitignore": "height",
446 "happiness": "",
447 "height": "",
448 "hi": "",
449 "hiccup": "",
450 },
451 }),
452 )
453 .await;
454
455 let project = Project::test(
456 app_state.fs.clone(),
457 [
458 "/ancestor/tracked-root".as_ref(),
459 "/ancestor/ignored-root".as_ref(),
460 ],
461 cx,
462 )
463 .await;
464 let (_, workspace) = cx.add_window(|cx| {
465 Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
466 });
467 let (_, finder) =
468 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
469 finder
470 .update(cx, |f, cx| f.spawn_search("hi".into(), cx))
471 .await;
472 finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 7));
473 }
474
475 #[gpui::test]
476 async fn test_single_file_worktrees(cx: &mut gpui::TestAppContext) {
477 let app_state = cx.update(AppState::test);
478 app_state
479 .fs
480 .as_fake()
481 .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
482 .await;
483
484 let project = Project::test(
485 app_state.fs.clone(),
486 ["/root/the-parent-dir/the-file".as_ref()],
487 cx,
488 )
489 .await;
490 let (_, workspace) = cx.add_window(|cx| {
491 Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
492 });
493 let (_, finder) =
494 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
495
496 // Even though there is only one worktree, that worktree's filename
497 // is included in the matching, because the worktree is a single file.
498 finder
499 .update(cx, |f, cx| f.spawn_search("thf".into(), cx))
500 .await;
501 cx.read(|cx| {
502 let finder = finder.read(cx);
503 assert_eq!(finder.matches.len(), 1);
504
505 let (file_name, file_name_positions, full_path, full_path_positions) =
506 finder.labels_for_match(&finder.matches[0]);
507 assert_eq!(file_name, "the-file");
508 assert_eq!(file_name_positions, &[0, 1, 4]);
509 assert_eq!(full_path, "the-file");
510 assert_eq!(full_path_positions, &[0, 1, 4]);
511 });
512
513 // Since the worktree root is a file, searching for its name followed by a slash does
514 // not match anything.
515 finder
516 .update(cx, |f, cx| f.spawn_search("thf/".into(), cx))
517 .await;
518 finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 0));
519 }
520
521 #[gpui::test]
522 async fn test_multiple_matches_with_same_relative_path(cx: &mut gpui::TestAppContext) {
523 cx.foreground().forbid_parking();
524
525 let app_state = cx.update(AppState::test);
526 app_state
527 .fs
528 .as_fake()
529 .insert_tree(
530 "/root",
531 json!({
532 "dir1": { "a.txt": "" },
533 "dir2": { "a.txt": "" }
534 }),
535 )
536 .await;
537
538 let project = Project::test(
539 app_state.fs.clone(),
540 ["/root/dir1".as_ref(), "/root/dir2".as_ref()],
541 cx,
542 )
543 .await;
544 let (_, workspace) = cx.add_window(|cx| {
545 Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
546 });
547
548 let (_, finder) =
549 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
550
551 // Run a search that matches two files with the same relative path.
552 finder
553 .update(cx, |f, cx| f.spawn_search("a.t".into(), cx))
554 .await;
555
556 // Can switch between different matches with the same relative path.
557 finder.update(cx, |f, cx| {
558 assert_eq!(f.matches.len(), 2);
559 assert_eq!(f.selected_index(), 0);
560 f.set_selected_index(1, cx);
561 assert_eq!(f.selected_index(), 1);
562 f.set_selected_index(0, cx);
563 assert_eq!(f.selected_index(), 0);
564 });
565 }
566
567 #[gpui::test]
568 async fn test_path_distance_ordering(cx: &mut gpui::TestAppContext) {
569 cx.foreground().forbid_parking();
570
571 let app_state = cx.update(AppState::test);
572 app_state
573 .fs
574 .as_fake()
575 .insert_tree(
576 "/root",
577 json!({
578 "dir1": { "a.txt": "" },
579 "dir2": {
580 "a.txt": "",
581 "b.txt": ""
582 }
583 }),
584 )
585 .await;
586
587 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
588 let (_, workspace) = cx.add_window(|cx| {
589 Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
590 });
591
592 // When workspace has an active item, sort items which are closer to that item
593 // first when they have the same name. In this case, b.txt is closer to dir2's a.txt
594 // so that one should be sorted earlier
595 let b_path = Some(Arc::from(Path::new("/root/dir2/b.txt")));
596 let (_, finder) =
597 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), b_path, cx));
598
599 finder
600 .update(cx, |f, cx| f.spawn_search("a.txt".into(), cx))
601 .await;
602
603 finder.read_with(cx, |f, _| {
604 assert_eq!(f.matches[0].path.as_ref(), Path::new("dir2/a.txt"));
605 assert_eq!(f.matches[1].path.as_ref(), Path::new("dir1/a.txt"));
606 });
607 }
608
609 #[gpui::test]
610 async fn test_search_worktree_without_files(cx: &mut gpui::TestAppContext) {
611 let app_state = cx.update(AppState::test);
612 app_state
613 .fs
614 .as_fake()
615 .insert_tree(
616 "/root",
617 json!({
618 "dir1": {},
619 "dir2": {
620 "dir3": {}
621 }
622 }),
623 )
624 .await;
625
626 let project = Project::test(app_state.fs.clone(), ["/root".as_ref()], cx).await;
627 let (_, workspace) = cx.add_window(|cx| {
628 Workspace::new(Default::default(), 0, project, |_, _| unimplemented!(), cx)
629 });
630 let (_, finder) =
631 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), None, cx));
632 finder
633 .update(cx, |f, cx| f.spawn_search("dir".into(), cx))
634 .await;
635 cx.read(|cx| {
636 let finder = finder.read(cx);
637 assert_eq!(finder.matches.len(), 0);
638 });
639 }
640}