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