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