recent_projects.rs

  1mod highlighted_workspace_location;
  2
  3use fuzzy::{StringMatch, StringMatchCandidate};
  4use gpui::{
  5    AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView, Result,
  6    Subscription, Task, View, ViewContext, WeakView,
  7};
  8use highlighted_workspace_location::HighlightedWorkspaceLocation;
  9use ordered_float::OrderedFloat;
 10use picker::{Picker, PickerDelegate};
 11use serde::Deserialize;
 12use std::sync::Arc;
 13use ui::{prelude::*, tooltip_container, HighlightedLabel, 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 the 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(r#match) = self.matches.get(ix) else {
306            return None;
307        };
308
309        let (workspace_id, location) = &self.workspaces[r#match.candidate_id];
310        let highlighted_location: HighlightedWorkspaceLocation =
311            HighlightedWorkspaceLocation::new(&r#match, location);
312        let tooltip_highlighted_location = highlighted_location.clone();
313
314        let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
315        Some(
316            ListItem::new(ix)
317                .inset(true)
318                .spacing(ListItemSpacing::Sparse)
319                .selected(selected)
320                .child(
321                    v_flex()
322                        .child(highlighted_location.names)
323                        .when(self.render_paths, |this| {
324                            this.children(highlighted_location.paths.into_iter().map(|path| {
325                                HighlightedLabel::new(path.text, path.highlight_positions)
326                                    .size(LabelSize::Small)
327                                    .color(Color::Muted)
328                            }))
329                        }),
330                )
331                .when(!is_current_workspace, |el| {
332                    let delete_button = div()
333                        .child(
334                            IconButton::new("delete", IconName::Close)
335                                .icon_size(IconSize::Small)
336                                .on_click(cx.listener(move |this, _event, cx| {
337                                    cx.stop_propagation();
338                                    cx.prevent_default();
339
340                                    this.delegate.delete_recent_project(ix, cx)
341                                }))
342                                .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
343                        )
344                        .into_any_element();
345
346                    if self.selected_index() == ix {
347                        el.end_slot::<AnyElement>(delete_button)
348                    } else {
349                        el.end_hover_slot::<AnyElement>(delete_button)
350                    }
351                })
352                .tooltip(move |cx| {
353                    let tooltip_highlighted_location = tooltip_highlighted_location.clone();
354                    cx.new_view(move |_| MatchTooltip {
355                        highlighted_location: tooltip_highlighted_location,
356                    })
357                    .into()
358                }),
359        )
360    }
361}
362
363impl RecentProjectsDelegate {
364    fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
365        if let Some(selected_match) = self.matches.get(ix) {
366            let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
367            cx.spawn(move |this, mut cx| async move {
368                let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
369                let workspaces = WORKSPACE_DB
370                    .recent_workspaces_on_disk()
371                    .await
372                    .unwrap_or_default();
373                this.update(&mut cx, move |picker, cx| {
374                    picker.delegate.workspaces = workspaces;
375                    picker.delegate.set_selected_index(ix - 1, cx);
376                    picker.delegate.reset_selected_match_index = false;
377                    picker.update_matches(picker.query(cx), cx)
378                })
379            })
380            .detach();
381        }
382    }
383
384    fn is_current_workspace(
385        &self,
386        workspace_id: WorkspaceId,
387        cx: &mut ViewContext<Picker<Self>>,
388    ) -> bool {
389        if let Some(workspace) = self.workspace.upgrade() {
390            let workspace = workspace.read(cx);
391            if workspace_id == workspace.database_id() {
392                return true;
393            }
394        }
395
396        false
397    }
398}
399struct MatchTooltip {
400    highlighted_location: HighlightedWorkspaceLocation,
401}
402
403impl Render for MatchTooltip {
404    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
405        tooltip_container(cx, |div, _| {
406            div.children(
407                self.highlighted_location
408                    .paths
409                    .clone()
410                    .into_iter()
411                    .map(|path| {
412                        HighlightedLabel::new(path.text, path.highlight_positions)
413                            .size(LabelSize::Small)
414                            .color(Color::Muted)
415                    }),
416            )
417        })
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use std::path::PathBuf;
424
425    use editor::Editor;
426    use gpui::{TestAppContext, WindowHandle};
427    use project::Project;
428    use serde_json::json;
429    use workspace::{open_paths, AppState};
430
431    use super::*;
432
433    #[gpui::test]
434    async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
435        let app_state = init_test(cx);
436        app_state
437            .fs
438            .as_fake()
439            .insert_tree(
440                "/dir",
441                json!({
442                    "main.ts": "a"
443                }),
444            )
445            .await;
446        cx.update(|cx| open_paths(&[PathBuf::from("/dir/main.ts")], &app_state, None, cx))
447            .await
448            .unwrap();
449        assert_eq!(cx.update(|cx| cx.windows().len()), 1);
450
451        let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
452        workspace
453            .update(cx, |workspace, _| assert!(!workspace.is_edited()))
454            .unwrap();
455
456        let editor = workspace
457            .read_with(cx, |workspace, cx| {
458                workspace
459                    .active_item(cx)
460                    .unwrap()
461                    .downcast::<Editor>()
462                    .unwrap()
463            })
464            .unwrap();
465        workspace
466            .update(cx, |_, cx| {
467                editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
468            })
469            .unwrap();
470        workspace
471            .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
472            .unwrap();
473
474        let recent_projects_picker = open_recent_projects(&workspace, cx);
475        workspace
476            .update(cx, |_, cx| {
477                recent_projects_picker.update(cx, |picker, cx| {
478                    assert_eq!(picker.query(cx), "");
479                    let delegate = &mut picker.delegate;
480                    delegate.matches = vec![StringMatch {
481                        candidate_id: 0,
482                        score: 1.0,
483                        positions: Vec::new(),
484                        string: "fake candidate".to_string(),
485                    }];
486                    delegate.workspaces = vec![(0, WorkspaceLocation::new(vec!["/test/path/"]))];
487                });
488            })
489            .unwrap();
490
491        assert!(
492            !cx.has_pending_prompt(),
493            "Should have no pending prompt on dirty project before opening the new recent project"
494        );
495        cx.dispatch_action((*workspace).into(), menu::Confirm);
496        workspace
497            .update(cx, |workspace, cx| {
498                assert!(
499                    workspace.active_modal::<RecentProjects>(cx).is_none(),
500                    "Should remove the modal after selecting new recent project"
501                )
502            })
503            .unwrap();
504        assert!(
505            cx.has_pending_prompt(),
506            "Dirty workspace should prompt before opening the new recent project"
507        );
508        // Cancel
509        cx.simulate_prompt_answer(0);
510        assert!(
511            !cx.has_pending_prompt(),
512            "Should have no pending prompt after cancelling"
513        );
514        workspace
515            .update(cx, |workspace, _| {
516                assert!(
517                    workspace.is_edited(),
518                    "Should be in the same dirty project after cancelling"
519                )
520            })
521            .unwrap();
522    }
523
524    fn open_recent_projects(
525        workspace: &WindowHandle<Workspace>,
526        cx: &mut TestAppContext,
527    ) -> View<Picker<RecentProjectsDelegate>> {
528        cx.dispatch_action(
529            (*workspace).into(),
530            OpenRecent {
531                create_new_window: false,
532            },
533        );
534        workspace
535            .update(cx, |workspace, cx| {
536                workspace
537                    .active_modal::<RecentProjects>(cx)
538                    .unwrap()
539                    .read(cx)
540                    .picker
541                    .clone()
542            })
543            .unwrap()
544    }
545
546    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
547        cx.update(|cx| {
548            let state = AppState::test(cx);
549            language::init(cx);
550            crate::init(cx);
551            editor::init(cx);
552            workspace::init_settings(cx);
553            Project::init_settings(cx);
554            state
555        })
556    }
557}