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