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