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 params = cx.update(WorkspaceParams::test);
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 cx.update(|cx| {
447 super::init(cx);
448 editor::init(cx);
449 });
450
451 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
452 workspace
453 .update(&mut cx, |workspace, cx| {
454 workspace.add_worktree(Path::new("/root"), cx)
455 })
456 .await
457 .unwrap();
458 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
459 .await;
460 cx.dispatch_action(window_id, vec![workspace.id()], Toggle);
461
462 let finder = cx.read(|cx| {
463 workspace
464 .read(cx)
465 .modal()
466 .cloned()
467 .unwrap()
468 .downcast::<FileFinder>()
469 .unwrap()
470 });
471 let query_buffer = cx.read(|cx| finder.read(cx).query_editor.clone());
472
473 let chain = vec![finder.id(), query_buffer.id()];
474 cx.dispatch_action(window_id, chain.clone(), Input("b".into()));
475 cx.dispatch_action(window_id, chain.clone(), Input("n".into()));
476 cx.dispatch_action(window_id, chain.clone(), Input("a".into()));
477 finder
478 .condition(&cx, |finder, _| finder.matches.len() == 2)
479 .await;
480
481 let active_pane = cx.read(|cx| workspace.read(cx).active_pane().clone());
482 cx.dispatch_action(window_id, vec![workspace.id(), finder.id()], SelectNext);
483 cx.dispatch_action(window_id, vec![workspace.id(), finder.id()], Confirm);
484 active_pane
485 .condition(&cx, |pane, _| pane.active_item().is_some())
486 .await;
487 cx.read(|cx| {
488 let active_item = active_pane.read(cx).active_item().unwrap();
489 assert_eq!(active_item.title(cx), "bandana");
490 });
491 }
492
493 #[gpui::test]
494 async fn test_matching_cancellation(mut cx: gpui::TestAppContext) {
495 let params = cx.update(WorkspaceParams::test);
496 let fs = params.fs.as_fake();
497 fs.insert_tree(
498 "/dir",
499 json!({
500 "hello": "",
501 "goodbye": "",
502 "halogen-light": "",
503 "happiness": "",
504 "height": "",
505 "hi": "",
506 "hiccup": "",
507 }),
508 )
509 .await;
510
511 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
512 workspace
513 .update(&mut cx, |workspace, cx| {
514 workspace.add_worktree("/dir".as_ref(), cx)
515 })
516 .await
517 .unwrap();
518 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
519 .await;
520 let (_, finder) = cx.add_window(|cx| {
521 FileFinder::new(
522 params.settings.clone(),
523 workspace.read(cx).project().clone(),
524 cx,
525 )
526 });
527
528 let query = "hi".to_string();
529 finder
530 .update(&mut cx, |f, cx| f.spawn_search(query.clone(), cx))
531 .unwrap()
532 .await;
533 finder.read_with(&cx, |f, _| assert_eq!(f.matches.len(), 5));
534
535 finder.update(&mut cx, |finder, cx| {
536 let matches = finder.matches.clone();
537
538 // Simulate a search being cancelled after the time limit,
539 // returning only a subset of the matches that would have been found.
540 finder.spawn_search(query.clone(), cx).unwrap().detach();
541 finder.update_matches(
542 (
543 finder.latest_search_id,
544 true, // did-cancel
545 query.clone(),
546 vec![matches[1].clone(), matches[3].clone()],
547 ),
548 cx,
549 );
550
551 // Simulate another cancellation.
552 finder.spawn_search(query.clone(), cx).unwrap().detach();
553 finder.update_matches(
554 (
555 finder.latest_search_id,
556 true, // did-cancel
557 query.clone(),
558 vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
559 ),
560 cx,
561 );
562
563 assert_eq!(finder.matches, matches[0..4])
564 });
565 }
566
567 #[gpui::test]
568 async fn test_single_file_worktrees(mut cx: gpui::TestAppContext) {
569 let params = cx.update(WorkspaceParams::test);
570 params
571 .fs
572 .as_fake()
573 .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
574 .await;
575
576 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
577 workspace
578 .update(&mut cx, |workspace, cx| {
579 workspace.add_worktree(Path::new("/root/the-parent-dir/the-file"), cx)
580 })
581 .await
582 .unwrap();
583 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
584 .await;
585 let (_, finder) = cx.add_window(|cx| {
586 FileFinder::new(
587 params.settings.clone(),
588 workspace.read(cx).project().clone(),
589 cx,
590 )
591 });
592
593 // Even though there is only one worktree, that worktree's filename
594 // is included in the matching, because the worktree is a single file.
595 finder
596 .update(&mut cx, |f, cx| f.spawn_search("thf".into(), cx))
597 .unwrap()
598 .await;
599 cx.read(|cx| {
600 let finder = finder.read(cx);
601 assert_eq!(finder.matches.len(), 1);
602
603 let (file_name, file_name_positions, full_path, full_path_positions) =
604 finder.labels_for_match(&finder.matches[0]);
605 assert_eq!(file_name, "the-file");
606 assert_eq!(file_name_positions, &[0, 1, 4]);
607 assert_eq!(full_path, "the-file");
608 assert_eq!(full_path_positions, &[0, 1, 4]);
609 });
610
611 // Since the worktree root is a file, searching for its name followed by a slash does
612 // not match anything.
613 finder
614 .update(&mut cx, |f, cx| f.spawn_search("thf/".into(), cx))
615 .unwrap()
616 .await;
617 finder.read_with(&cx, |f, _| assert_eq!(f.matches.len(), 0));
618 }
619
620 #[gpui::test(retries = 5)]
621 async fn test_multiple_matches_with_same_relative_path(mut cx: gpui::TestAppContext) {
622 let params = cx.update(WorkspaceParams::test);
623 params
624 .fs
625 .as_fake()
626 .insert_tree(
627 "/root",
628 json!({
629 "dir1": { "a.txt": "" },
630 "dir2": { "a.txt": "" }
631 }),
632 )
633 .await;
634
635 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
636
637 workspace
638 .update(&mut cx, |workspace, cx| {
639 workspace.open_paths(
640 &[PathBuf::from("/root/dir1"), PathBuf::from("/root/dir2")],
641 cx,
642 )
643 })
644 .await;
645 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
646 .await;
647
648 let (_, finder) = cx.add_window(|cx| {
649 FileFinder::new(
650 params.settings.clone(),
651 workspace.read(cx).project().clone(),
652 cx,
653 )
654 });
655
656 // Run a search that matches two files with the same relative path.
657 finder
658 .update(&mut cx, |f, cx| f.spawn_search("a.t".into(), cx))
659 .unwrap()
660 .await;
661
662 // Can switch between different matches with the same relative path.
663 finder.update(&mut cx, |f, cx| {
664 assert_eq!(f.matches.len(), 2);
665 assert_eq!(f.selected_index(), 0);
666 f.select_next(&SelectNext, cx);
667 assert_eq!(f.selected_index(), 1);
668 f.select_prev(&SelectPrev, cx);
669 assert_eq!(f.selected_index(), 0);
670 });
671 }
672}