1use fuzzy::PathMatch;
2use gpui::{
3 actions, elements::*, AppContext, Entity, ModelHandle, MutableAppContext, RenderContext, Task,
4 View, ViewContext, ViewHandle,
5};
6use picker::{Picker, PickerDelegate};
7use project::{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 matches: Vec<PathMatch>,
27 selected: Option<(usize, Arc<Path>)>,
28 cancel_flag: Arc<AtomicBool>,
29}
30
31actions!(file_finder, [Toggle]);
32
33pub fn init(cx: &mut MutableAppContext) {
34 cx.add_action(FileFinder::toggle);
35 Picker::<FileFinder>::init(cx);
36}
37
38pub enum Event {
39 Selected(ProjectPath),
40 Dismissed,
41}
42
43impl Entity for FileFinder {
44 type Event = Event;
45}
46
47impl View for FileFinder {
48 fn ui_name() -> &'static str {
49 "FileFinder"
50 }
51
52 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
53 ChildView::new(self.picker.clone()).boxed()
54 }
55
56 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
57 cx.focus(&self.picker);
58 }
59}
60
61impl FileFinder {
62 fn labels_for_match(&self, path_match: &PathMatch) -> (String, Vec<usize>, String, Vec<usize>) {
63 let path_string = path_match.path.to_string_lossy();
64 let full_path = [path_match.path_prefix.as_ref(), path_string.as_ref()].join("");
65 let path_positions = path_match.positions.clone();
66
67 let file_name = path_match.path.file_name().map_or_else(
68 || path_match.path_prefix.to_string(),
69 |file_name| file_name.to_string_lossy().to_string(),
70 );
71 let file_name_start = path_match.path_prefix.chars().count() + path_string.chars().count()
72 - file_name.chars().count();
73 let file_name_positions = path_positions
74 .iter()
75 .filter_map(|pos| {
76 if pos >= &file_name_start {
77 Some(pos - file_name_start)
78 } else {
79 None
80 }
81 })
82 .collect();
83
84 (file_name, file_name_positions, full_path, path_positions)
85 }
86
87 fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
88 workspace.toggle_modal(cx, |cx, workspace| {
89 let project = workspace.project().clone();
90 let finder = cx.add_view(|cx| Self::new(project, cx));
91 cx.subscribe(&finder, Self::on_event).detach();
92 finder
93 });
94 }
95
96 fn on_event(
97 workspace: &mut Workspace,
98 _: ViewHandle<FileFinder>,
99 event: &Event,
100 cx: &mut ViewContext<Workspace>,
101 ) {
102 match event {
103 Event::Selected(project_path) => {
104 workspace
105 .open_path(project_path.clone(), cx)
106 .detach_and_log_err(cx);
107 workspace.dismiss_modal(cx);
108 }
109 Event::Dismissed => {
110 workspace.dismiss_modal(cx);
111 }
112 }
113 }
114
115 pub fn new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
116 let handle = cx.weak_handle();
117 cx.observe(&project, Self::project_updated).detach();
118 Self {
119 project,
120 picker: cx.add_view(|cx| Picker::new(handle, cx)),
121 search_count: 0,
122 latest_search_id: 0,
123 latest_search_did_cancel: false,
124 latest_search_query: String::new(),
125 matches: Vec::new(),
126 selected: None,
127 cancel_flag: Arc::new(AtomicBool::new(false)),
128 }
129 }
130
131 fn project_updated(&mut self, _: ModelHandle<Project>, cx: &mut ViewContext<Self>) {
132 self.spawn_search(self.latest_search_query.clone(), cx)
133 .detach();
134 }
135
136 fn spawn_search(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
137 let search_id = util::post_inc(&mut self.search_count);
138 self.cancel_flag.store(true, atomic::Ordering::Relaxed);
139 self.cancel_flag = Arc::new(AtomicBool::new(false));
140 let cancel_flag = self.cancel_flag.clone();
141 let project = self.project.clone();
142 cx.spawn(|this, mut cx| async move {
143 let matches = project
144 .read_with(&cx, |project, cx| {
145 project.match_paths(&query, false, false, 100, cancel_flag.as_ref(), cx)
146 })
147 .await;
148 let did_cancel = cancel_flag.load(atomic::Ordering::Relaxed);
149 this.update(&mut cx, |this, cx| {
150 this.set_matches(search_id, did_cancel, query, matches, cx)
151 });
152 })
153 }
154
155 fn set_matches(
156 &mut self,
157 search_id: usize,
158 did_cancel: bool,
159 query: String,
160 matches: Vec<PathMatch>,
161 cx: &mut ViewContext<Self>,
162 ) {
163 if search_id >= self.latest_search_id {
164 self.latest_search_id = search_id;
165 if self.latest_search_did_cancel && query == self.latest_search_query {
166 util::extend_sorted(&mut self.matches, matches.into_iter(), 100, |a, b| b.cmp(a));
167 } else {
168 self.matches = matches;
169 }
170 self.latest_search_query = query;
171 self.latest_search_did_cancel = did_cancel;
172 cx.notify();
173 self.picker.update(cx, |_, cx| cx.notify());
174 }
175 }
176}
177
178impl PickerDelegate for FileFinder {
179 fn match_count(&self) -> usize {
180 self.matches.len()
181 }
182
183 fn selected_index(&self) -> usize {
184 if let Some(selected) = self.selected.as_ref() {
185 for (ix, path_match) in self.matches.iter().enumerate() {
186 if (path_match.worktree_id, path_match.path.as_ref())
187 == (selected.0, selected.1.as_ref())
188 {
189 return ix;
190 }
191 }
192 }
193 0
194 }
195
196 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Self>) {
197 let mat = &self.matches[ix];
198 self.selected = Some((mat.worktree_id, mat.path.clone()));
199 cx.notify();
200 }
201
202 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Self>) -> Task<()> {
203 if query.is_empty() {
204 self.latest_search_id = post_inc(&mut self.search_count);
205 self.matches.clear();
206 cx.notify();
207 Task::ready(())
208 } else {
209 self.spawn_search(query, cx)
210 }
211 }
212
213 fn confirm(&mut self, cx: &mut ViewContext<Self>) {
214 if let Some(m) = self.matches.get(self.selected_index()) {
215 cx.emit(Event::Selected(ProjectPath {
216 worktree_id: WorktreeId::from_usize(m.worktree_id),
217 path: m.path.clone(),
218 }));
219 }
220 }
221
222 fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
223 cx.emit(Event::Dismissed);
224 }
225
226 fn render_match(&self, ix: usize, selected: bool, cx: &AppContext) -> ElementBox {
227 let path_match = &self.matches[ix];
228 let settings = cx.global::<Settings>();
229 let style = if selected {
230 &settings.theme.selector.active_item
231 } else {
232 &settings.theme.selector.item
233 };
234 let (file_name, file_name_positions, full_path, full_path_positions) =
235 self.labels_for_match(path_match);
236 Flex::column()
237 .with_child(
238 Label::new(file_name.to_string(), style.label.clone())
239 .with_highlights(file_name_positions)
240 .boxed(),
241 )
242 .with_child(
243 Label::new(full_path, style.label.clone())
244 .with_highlights(full_path_positions)
245 .boxed(),
246 )
247 .flex(1., false)
248 .contained()
249 .with_style(style.container)
250 .named("match")
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257 use editor::{Editor, Input};
258 use serde_json::json;
259 use std::path::PathBuf;
260 use workspace::menu::{Confirm, SelectNext};
261 use workspace::{Workspace, WorkspaceParams};
262
263 #[ctor::ctor]
264 fn init_logger() {
265 if std::env::var("RUST_LOG").is_ok() {
266 env_logger::init();
267 }
268 }
269
270 #[gpui::test]
271 async fn test_matching_paths(cx: &mut gpui::TestAppContext) {
272 cx.update(|cx| {
273 super::init(cx);
274 editor::init(cx);
275 });
276
277 let params = cx.update(WorkspaceParams::test);
278 params
279 .fs
280 .as_fake()
281 .insert_tree(
282 "/root",
283 json!({
284 "a": {
285 "banana": "",
286 "bandana": "",
287 }
288 }),
289 )
290 .await;
291
292 let (window_id, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
293 params
294 .project
295 .update(cx, |project, cx| {
296 project.find_or_create_local_worktree("/root", true, cx)
297 })
298 .await
299 .unwrap();
300 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
301 .await;
302 cx.dispatch_action(window_id, Toggle);
303
304 let finder = cx.read(|cx| {
305 workspace
306 .read(cx)
307 .modal()
308 .cloned()
309 .unwrap()
310 .downcast::<FileFinder>()
311 .unwrap()
312 });
313 cx.dispatch_action(window_id, Input("b".into()));
314 cx.dispatch_action(window_id, Input("n".into()));
315 cx.dispatch_action(window_id, Input("a".into()));
316 finder
317 .condition(&cx, |finder, _| finder.matches.len() == 2)
318 .await;
319
320 let active_pane = cx.read(|cx| workspace.read(cx).active_pane().clone());
321 cx.dispatch_action(window_id, SelectNext);
322 cx.dispatch_action(window_id, Confirm);
323 active_pane
324 .condition(&cx, |pane, _| pane.active_item().is_some())
325 .await;
326 cx.read(|cx| {
327 let active_item = active_pane.read(cx).active_item().unwrap();
328 assert_eq!(
329 active_item
330 .to_any()
331 .downcast::<Editor>()
332 .unwrap()
333 .read(cx)
334 .title(cx),
335 "bandana"
336 );
337 });
338 }
339
340 #[gpui::test]
341 async fn test_matching_cancellation(cx: &mut gpui::TestAppContext) {
342 let params = cx.update(WorkspaceParams::test);
343 let fs = params.fs.as_fake();
344 fs.insert_tree(
345 "/dir",
346 json!({
347 "hello": "",
348 "goodbye": "",
349 "halogen-light": "",
350 "happiness": "",
351 "height": "",
352 "hi": "",
353 "hiccup": "",
354 }),
355 )
356 .await;
357
358 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
359 params
360 .project
361 .update(cx, |project, cx| {
362 project.find_or_create_local_worktree("/dir", true, cx)
363 })
364 .await
365 .unwrap();
366 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
367 .await;
368 let (_, finder) =
369 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), cx));
370
371 let query = "hi".to_string();
372 finder
373 .update(cx, |f, cx| f.spawn_search(query.clone(), cx))
374 .await;
375 finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 5));
376
377 finder.update(cx, |finder, cx| {
378 let matches = finder.matches.clone();
379
380 // Simulate a search being cancelled after the time limit,
381 // returning only a subset of the matches that would have been found.
382 finder.spawn_search(query.clone(), cx).detach();
383 finder.set_matches(
384 finder.latest_search_id,
385 true, // did-cancel
386 query.clone(),
387 vec![matches[1].clone(), matches[3].clone()],
388 cx,
389 );
390
391 // Simulate another cancellation.
392 finder.spawn_search(query.clone(), cx).detach();
393 finder.set_matches(
394 finder.latest_search_id,
395 true, // did-cancel
396 query.clone(),
397 vec![matches[0].clone(), matches[2].clone(), matches[3].clone()],
398 cx,
399 );
400
401 assert_eq!(finder.matches, matches[0..4])
402 });
403 }
404
405 #[gpui::test]
406 async fn test_single_file_worktrees(cx: &mut gpui::TestAppContext) {
407 let params = cx.update(WorkspaceParams::test);
408 params
409 .fs
410 .as_fake()
411 .insert_tree("/root", json!({ "the-parent-dir": { "the-file": "" } }))
412 .await;
413
414 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
415 params
416 .project
417 .update(cx, |project, cx| {
418 project.find_or_create_local_worktree("/root/the-parent-dir/the-file", true, cx)
419 })
420 .await
421 .unwrap();
422 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
423 .await;
424 let (_, finder) =
425 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), cx));
426
427 // Even though there is only one worktree, that worktree's filename
428 // is included in the matching, because the worktree is a single file.
429 finder
430 .update(cx, |f, cx| f.spawn_search("thf".into(), cx))
431 .await;
432 cx.read(|cx| {
433 let finder = finder.read(cx);
434 assert_eq!(finder.matches.len(), 1);
435
436 let (file_name, file_name_positions, full_path, full_path_positions) =
437 finder.labels_for_match(&finder.matches[0]);
438 assert_eq!(file_name, "the-file");
439 assert_eq!(file_name_positions, &[0, 1, 4]);
440 assert_eq!(full_path, "the-file");
441 assert_eq!(full_path_positions, &[0, 1, 4]);
442 });
443
444 // Since the worktree root is a file, searching for its name followed by a slash does
445 // not match anything.
446 finder
447 .update(cx, |f, cx| f.spawn_search("thf/".into(), cx))
448 .await;
449 finder.read_with(cx, |f, _| assert_eq!(f.matches.len(), 0));
450 }
451
452 #[gpui::test(retries = 5)]
453 async fn test_multiple_matches_with_same_relative_path(cx: &mut gpui::TestAppContext) {
454 let params = cx.update(WorkspaceParams::test);
455 params
456 .fs
457 .as_fake()
458 .insert_tree(
459 "/root",
460 json!({
461 "dir1": { "a.txt": "" },
462 "dir2": { "a.txt": "" }
463 }),
464 )
465 .await;
466
467 let (_, workspace) = cx.add_window(|cx| Workspace::new(¶ms, cx));
468
469 workspace
470 .update(cx, |workspace, cx| {
471 workspace.open_paths(
472 &[PathBuf::from("/root/dir1"), PathBuf::from("/root/dir2")],
473 cx,
474 )
475 })
476 .await;
477 cx.read(|cx| workspace.read(cx).worktree_scans_complete(cx))
478 .await;
479
480 let (_, finder) =
481 cx.add_window(|cx| FileFinder::new(workspace.read(cx).project().clone(), cx));
482
483 // Run a search that matches two files with the same relative path.
484 finder
485 .update(cx, |f, cx| f.spawn_search("a.t".into(), cx))
486 .await;
487
488 // Can switch between different matches with the same relative path.
489 finder.update(cx, |f, cx| {
490 assert_eq!(f.matches.len(), 2);
491 assert_eq!(f.selected_index(), 0);
492 f.set_selected_index(1, cx);
493 assert_eq!(f.selected_index(), 1);
494 f.set_selected_index(0, cx);
495 assert_eq!(f.selected_index(), 0);
496 });
497 }
498}