1use fuzzy::{StringMatch, StringMatchCandidate};
2use gpui::{
3 AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Result,
4 Subscription, Task, View, ViewContext, WeakView,
5};
6use ordered_float::OrderedFloat;
7use picker::{
8 highlighted_match_with_paths::{HighlightedMatchWithPaths, HighlightedText},
9 Picker, PickerDelegate,
10};
11use serde::Deserialize;
12use std::{path::Path, sync::Arc};
13use ui::{prelude::*, tooltip_container, ListItem, ListItemSpacing, Tooltip};
14use util::paths::PathExt;
15use workspace::{ModalView, Workspace, WorkspaceId, WorkspaceLocation, WORKSPACE_DB};
16
17#[derive(PartialEq, Clone, Deserialize, Default)]
18pub struct OpenRecent {
19 #[serde(default)]
20 pub create_new_window: bool,
21}
22
23gpui::impl_actions!(projects, [OpenRecent]);
24
25pub fn init(cx: &mut AppContext) {
26 cx.observe_new_views(RecentProjects::register).detach();
27}
28
29pub struct RecentProjects {
30 pub picker: View<Picker<RecentProjectsDelegate>>,
31 rem_width: f32,
32 _subscription: Subscription,
33}
34
35impl ModalView for RecentProjects {}
36
37impl RecentProjects {
38 fn new(delegate: RecentProjectsDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
39 let picker = cx.new_view(|cx| {
40 // We want to use a list when we render paths, because the items can have different heights (multiple paths).
41 if delegate.render_paths {
42 Picker::list(delegate, cx)
43 } else {
44 Picker::uniform_list(delegate, cx)
45 }
46 });
47 let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
48 // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
49 // out workspace locations once the future runs to completion.
50 cx.spawn(|this, mut cx| async move {
51 let workspaces = WORKSPACE_DB
52 .recent_workspaces_on_disk()
53 .await
54 .unwrap_or_default();
55
56 this.update(&mut cx, move |this, cx| {
57 this.picker.update(cx, move |picker, cx| {
58 picker.delegate.workspaces = workspaces;
59 picker.update_matches(picker.query(cx), cx)
60 })
61 })
62 .ok()
63 })
64 .detach();
65 Self {
66 picker,
67 rem_width,
68 _subscription,
69 }
70 }
71
72 fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
73 workspace.register_action(|workspace, open_recent: &OpenRecent, cx| {
74 let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {
75 if let Some(handler) = Self::open(workspace, open_recent.create_new_window, cx) {
76 handler.detach_and_log_err(cx);
77 }
78 return;
79 };
80
81 recent_projects.update(cx, |recent_projects, cx| {
82 recent_projects
83 .picker
84 .update(cx, |picker, cx| picker.cycle_selection(cx))
85 });
86 });
87 }
88
89 fn open(
90 _: &mut Workspace,
91 create_new_window: bool,
92 cx: &mut ViewContext<Workspace>,
93 ) -> Option<Task<Result<()>>> {
94 Some(cx.spawn(|workspace, mut cx| async move {
95 workspace.update(&mut cx, |workspace, cx| {
96 let weak_workspace = cx.view().downgrade();
97 workspace.toggle_modal(cx, |cx| {
98 let delegate =
99 RecentProjectsDelegate::new(weak_workspace, create_new_window, true);
100
101 let modal = Self::new(delegate, 34., cx);
102 modal
103 });
104 })?;
105 Ok(())
106 }))
107 }
108
109 pub fn open_popover(workspace: WeakView<Workspace>, cx: &mut WindowContext<'_>) -> View<Self> {
110 cx.new_view(|cx| {
111 Self::new(
112 RecentProjectsDelegate::new(workspace, false, false),
113 20.,
114 cx,
115 )
116 })
117 }
118}
119
120impl EventEmitter<DismissEvent> for RecentProjects {}
121
122impl FocusableView for RecentProjects {
123 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
124 self.picker.focus_handle(cx)
125 }
126}
127
128impl Render for RecentProjects {
129 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
130 v_flex()
131 .w(rems(self.rem_width))
132 .cursor_pointer()
133 .child(self.picker.clone())
134 .on_mouse_down_out(cx.listener(|this, _, cx| {
135 this.picker.update(cx, |this, cx| {
136 this.cancel(&Default::default(), cx);
137 })
138 }))
139 }
140}
141
142pub struct RecentProjectsDelegate {
143 workspace: WeakView<Workspace>,
144 workspaces: Vec<(WorkspaceId, WorkspaceLocation)>,
145 selected_match_index: usize,
146 matches: Vec<StringMatch>,
147 render_paths: bool,
148 create_new_window: bool,
149 // Flag to reset index when there is a new query vs not reset index when user delete an item
150 reset_selected_match_index: bool,
151}
152
153impl RecentProjectsDelegate {
154 fn new(workspace: WeakView<Workspace>, create_new_window: bool, render_paths: bool) -> Self {
155 Self {
156 workspace,
157 workspaces: vec![],
158 selected_match_index: 0,
159 matches: Default::default(),
160 create_new_window,
161 render_paths,
162 reset_selected_match_index: true,
163 }
164 }
165}
166impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
167impl PickerDelegate for RecentProjectsDelegate {
168 type ListItem = ListItem;
169
170 fn placeholder_text(&self, cx: &mut WindowContext) -> Arc<str> {
171 let (create_window, reuse_window) = if self.create_new_window {
172 (
173 cx.keystroke_text_for(&menu::Confirm),
174 cx.keystroke_text_for(&menu::SecondaryConfirm),
175 )
176 } else {
177 (
178 cx.keystroke_text_for(&menu::SecondaryConfirm),
179 cx.keystroke_text_for(&menu::Confirm),
180 )
181 };
182 Arc::from(format!(
183 "{reuse_window} reuses the window, {create_window} opens a new one",
184 ))
185 }
186
187 fn match_count(&self) -> usize {
188 self.matches.len()
189 }
190
191 fn selected_index(&self) -> usize {
192 self.selected_match_index
193 }
194
195 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
196 self.selected_match_index = ix;
197 }
198
199 fn update_matches(
200 &mut self,
201 query: String,
202 cx: &mut ViewContext<Picker<Self>>,
203 ) -> gpui::Task<()> {
204 let query = query.trim_start();
205 let smart_case = query.chars().any(|c| c.is_uppercase());
206 let candidates = self
207 .workspaces
208 .iter()
209 .enumerate()
210 .map(|(id, (_, location))| {
211 let combined_string = location
212 .paths()
213 .iter()
214 .map(|path| path.compact().to_string_lossy().into_owned())
215 .collect::<Vec<_>>()
216 .join("");
217 StringMatchCandidate::new(id, combined_string)
218 })
219 .collect::<Vec<_>>();
220 self.matches = smol::block_on(fuzzy::match_strings(
221 candidates.as_slice(),
222 query,
223 smart_case,
224 100,
225 &Default::default(),
226 cx.background_executor().clone(),
227 ));
228 self.matches.sort_unstable_by_key(|m| m.candidate_id);
229
230 if self.reset_selected_match_index {
231 self.selected_match_index = self
232 .matches
233 .iter()
234 .enumerate()
235 .rev()
236 .max_by_key(|(_, m)| OrderedFloat(m.score))
237 .map(|(ix, _)| ix)
238 .unwrap_or(0);
239 }
240 self.reset_selected_match_index = true;
241 Task::ready(())
242 }
243
244 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
245 if let Some((selected_match, workspace)) = self
246 .matches
247 .get(self.selected_index())
248 .zip(self.workspace.upgrade())
249 {
250 let (candidate_workspace_id, candidate_workspace_location) =
251 &self.workspaces[selected_match.candidate_id];
252 let replace_current_window = if self.create_new_window {
253 secondary
254 } else {
255 !secondary
256 };
257 workspace
258 .update(cx, |workspace, cx| {
259 if workspace.database_id() != *candidate_workspace_id {
260 let candidate_paths = candidate_workspace_location.paths().as_ref().clone();
261 if replace_current_window {
262 cx.spawn(move |workspace, mut cx| async move {
263 let continue_replacing = workspace
264 .update(&mut cx, |workspace, cx| {
265 workspace.prepare_to_close(true, cx)
266 })?
267 .await?;
268 if continue_replacing {
269 workspace
270 .update(&mut cx, |workspace, cx| {
271 workspace.open_workspace_for_paths(
272 replace_current_window,
273 candidate_paths,
274 cx,
275 )
276 })?
277 .await
278 } else {
279 Ok(())
280 }
281 })
282 } else {
283 workspace.open_workspace_for_paths(
284 replace_current_window,
285 candidate_paths,
286 cx,
287 )
288 }
289 } else {
290 Task::ready(Ok(()))
291 }
292 })
293 .detach_and_log_err(cx);
294 cx.emit(DismissEvent);
295 }
296 }
297
298 fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
299
300 fn render_match(
301 &self,
302 ix: usize,
303 selected: bool,
304 cx: &mut ViewContext<Picker<Self>>,
305 ) -> Option<Self::ListItem> {
306 let Some(hit) = self.matches.get(ix) else {
307 return None;
308 };
309
310 let (workspace_id, location) = &self.workspaces[hit.candidate_id];
311 let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
312
313 let mut path_start_offset = 0;
314 let (match_labels, paths): (Vec<_>, Vec<_>) = location
315 .paths()
316 .iter()
317 .map(|path| {
318 let path = path.compact();
319 let highlighted_text =
320 highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
321
322 path_start_offset += highlighted_text.1.char_count;
323 highlighted_text
324 })
325 .unzip();
326
327 let highlighted_match = HighlightedMatchWithPaths {
328 match_label: HighlightedText::join(
329 match_labels.into_iter().filter_map(|name| name),
330 ", ",
331 ),
332 paths: if self.render_paths { paths } else { Vec::new() },
333 };
334 Some(
335 ListItem::new(ix)
336 .inset(true)
337 .spacing(ListItemSpacing::Sparse)
338 .selected(selected)
339 .child(highlighted_match.clone().render(cx))
340 .when(!is_current_workspace, |el| {
341 let delete_button = div()
342 .child(
343 IconButton::new("delete", IconName::Close)
344 .icon_size(IconSize::Small)
345 .on_click(cx.listener(move |this, _event, cx| {
346 cx.stop_propagation();
347 cx.prevent_default();
348
349 this.delegate.delete_recent_project(ix, cx)
350 }))
351 .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
352 )
353 .into_any_element();
354
355 if self.selected_index() == ix {
356 el.end_slot::<AnyElement>(delete_button)
357 } else {
358 el.end_hover_slot::<AnyElement>(delete_button)
359 }
360 })
361 .tooltip(move |cx| {
362 let tooltip_highlighted_location = highlighted_match.clone();
363 cx.new_view(move |_| MatchTooltip {
364 highlighted_location: tooltip_highlighted_location,
365 })
366 .into()
367 }),
368 )
369 }
370}
371
372// Compute the highlighted text for the name and path
373fn highlights_for_path(
374 path: &Path,
375 match_positions: &Vec<usize>,
376 path_start_offset: usize,
377) -> (Option<HighlightedText>, HighlightedText) {
378 let path_string = path.to_string_lossy();
379 let path_char_count = path_string.chars().count();
380 // Get the subset of match highlight positions that line up with the given path.
381 // Also adjusts them to start at the path start
382 let path_positions = match_positions
383 .iter()
384 .copied()
385 .skip_while(|position| *position < path_start_offset)
386 .take_while(|position| *position < path_start_offset + path_char_count)
387 .map(|position| position - path_start_offset)
388 .collect::<Vec<_>>();
389
390 // Again subset the highlight positions to just those that line up with the file_name
391 // again adjusted to the start of the file_name
392 let file_name_text_and_positions = path.file_name().map(|file_name| {
393 let text = file_name.to_string_lossy();
394 let char_count = text.chars().count();
395 let file_name_start = path_char_count - char_count;
396 let highlight_positions = path_positions
397 .iter()
398 .copied()
399 .skip_while(|position| *position < file_name_start)
400 .take_while(|position| *position < file_name_start + char_count)
401 .map(|position| position - file_name_start)
402 .collect::<Vec<_>>();
403 HighlightedText {
404 text: text.to_string(),
405 highlight_positions,
406 char_count,
407 }
408 });
409
410 (
411 file_name_text_and_positions,
412 HighlightedText {
413 text: path_string.to_string(),
414 highlight_positions: path_positions,
415 char_count: path_char_count,
416 },
417 )
418}
419
420impl RecentProjectsDelegate {
421 fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
422 if let Some(selected_match) = self.matches.get(ix) {
423 let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
424 cx.spawn(move |this, mut cx| async move {
425 let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
426 let workspaces = WORKSPACE_DB
427 .recent_workspaces_on_disk()
428 .await
429 .unwrap_or_default();
430 this.update(&mut cx, move |picker, cx| {
431 picker.delegate.workspaces = workspaces;
432 picker.delegate.set_selected_index(ix - 1, cx);
433 picker.delegate.reset_selected_match_index = false;
434 picker.update_matches(picker.query(cx), cx)
435 })
436 })
437 .detach();
438 }
439 }
440
441 fn is_current_workspace(
442 &self,
443 workspace_id: WorkspaceId,
444 cx: &mut ViewContext<Picker<Self>>,
445 ) -> bool {
446 if let Some(workspace) = self.workspace.upgrade() {
447 let workspace = workspace.read(cx);
448 if workspace_id == workspace.database_id() {
449 return true;
450 }
451 }
452
453 false
454 }
455}
456struct MatchTooltip {
457 highlighted_location: HighlightedMatchWithPaths,
458}
459
460impl Render for MatchTooltip {
461 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
462 tooltip_container(cx, |div, _| {
463 self.highlighted_location.render_paths_children(div)
464 })
465 }
466}
467
468#[cfg(test)]
469mod tests {
470 use std::path::PathBuf;
471
472 use editor::Editor;
473 use gpui::{TestAppContext, WindowHandle};
474 use project::Project;
475 use serde_json::json;
476 use workspace::{open_paths, AppState};
477
478 use super::*;
479
480 #[gpui::test]
481 async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
482 let app_state = init_test(cx);
483 app_state
484 .fs
485 .as_fake()
486 .insert_tree(
487 "/dir",
488 json!({
489 "main.ts": "a"
490 }),
491 )
492 .await;
493 cx.update(|cx| open_paths(&[PathBuf::from("/dir/main.ts")], &app_state, None, cx))
494 .await
495 .unwrap();
496 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
497
498 let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
499 workspace
500 .update(cx, |workspace, _| assert!(!workspace.is_edited()))
501 .unwrap();
502
503 let editor = workspace
504 .read_with(cx, |workspace, cx| {
505 workspace
506 .active_item(cx)
507 .unwrap()
508 .downcast::<Editor>()
509 .unwrap()
510 })
511 .unwrap();
512 workspace
513 .update(cx, |_, cx| {
514 editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
515 })
516 .unwrap();
517 workspace
518 .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
519 .unwrap();
520
521 let recent_projects_picker = open_recent_projects(&workspace, cx);
522 workspace
523 .update(cx, |_, cx| {
524 recent_projects_picker.update(cx, |picker, cx| {
525 assert_eq!(picker.query(cx), "");
526 let delegate = &mut picker.delegate;
527 delegate.matches = vec![StringMatch {
528 candidate_id: 0,
529 score: 1.0,
530 positions: Vec::new(),
531 string: "fake candidate".to_string(),
532 }];
533 delegate.workspaces = vec![(0, WorkspaceLocation::new(vec!["/test/path/"]))];
534 });
535 })
536 .unwrap();
537
538 assert!(
539 !cx.has_pending_prompt(),
540 "Should have no pending prompt on dirty project before opening the new recent project"
541 );
542 cx.dispatch_action((*workspace).into(), menu::Confirm);
543 workspace
544 .update(cx, |workspace, cx| {
545 assert!(
546 workspace.active_modal::<RecentProjects>(cx).is_none(),
547 "Should remove the modal after selecting new recent project"
548 )
549 })
550 .unwrap();
551 assert!(
552 cx.has_pending_prompt(),
553 "Dirty workspace should prompt before opening the new recent project"
554 );
555 // Cancel
556 cx.simulate_prompt_answer(0);
557 assert!(
558 !cx.has_pending_prompt(),
559 "Should have no pending prompt after cancelling"
560 );
561 workspace
562 .update(cx, |workspace, _| {
563 assert!(
564 workspace.is_edited(),
565 "Should be in the same dirty project after cancelling"
566 )
567 })
568 .unwrap();
569 }
570
571 fn open_recent_projects(
572 workspace: &WindowHandle<Workspace>,
573 cx: &mut TestAppContext,
574 ) -> View<Picker<RecentProjectsDelegate>> {
575 cx.dispatch_action(
576 (*workspace).into(),
577 OpenRecent {
578 create_new_window: false,
579 },
580 );
581 workspace
582 .update(cx, |workspace, cx| {
583 workspace
584 .active_modal::<RecentProjects>(cx)
585 .unwrap()
586 .read(cx)
587 .picker
588 .clone()
589 })
590 .unwrap()
591 }
592
593 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
594 cx.update(|cx| {
595 let state = AppState::test(cx);
596 language::init(cx);
597 crate::init(cx);
598 editor::init(cx);
599 workspace::init_settings(cx);
600 Project::init_settings(cx);
601 state
602 })
603 }
604}