recent_projects.rs

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