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: if self.render_paths { paths } else { Vec::new() },
329        };
330        Some(
331            ListItem::new(ix)
332                .inset(true)
333                .spacing(ListItemSpacing::Sparse)
334                .selected(selected)
335                .child(highlighted_match.clone().render(cx))
336                .when(!is_current_workspace, |el| {
337                    let delete_button = div()
338                        .child(
339                            IconButton::new("delete", IconName::Close)
340                                .icon_size(IconSize::Small)
341                                .on_click(cx.listener(move |this, _event, cx| {
342                                    cx.stop_propagation();
343                                    cx.prevent_default();
344
345                                    this.delegate.delete_recent_project(ix, cx)
346                                }))
347                                .tooltip(|cx| Tooltip::text("Delete From Recent Projects...", cx)),
348                        )
349                        .into_any_element();
350
351                    if self.selected_index() == ix {
352                        el.end_slot::<AnyElement>(delete_button)
353                    } else {
354                        el.end_hover_slot::<AnyElement>(delete_button)
355                    }
356                })
357                .tooltip(move |cx| {
358                    let tooltip_highlighted_location = highlighted_match.clone();
359                    cx.new_view(move |_| MatchTooltip {
360                        highlighted_location: tooltip_highlighted_location,
361                    })
362                    .into()
363                }),
364        )
365    }
366}
367
368// Compute the highlighted text for the name and path
369fn highlights_for_path(
370    path: &Path,
371    match_positions: &Vec<usize>,
372    path_start_offset: usize,
373) -> (Option<HighlightedText>, HighlightedText) {
374    let path_string = path.to_string_lossy();
375    let path_char_count = path_string.chars().count();
376    // Get the subset of match highlight positions that line up with the given path.
377    // Also adjusts them to start at the path start
378    let path_positions = match_positions
379        .iter()
380        .copied()
381        .skip_while(|position| *position < path_start_offset)
382        .take_while(|position| *position < path_start_offset + path_char_count)
383        .map(|position| position - path_start_offset)
384        .collect::<Vec<_>>();
385
386    // Again subset the highlight positions to just those that line up with the file_name
387    // again adjusted to the start of the file_name
388    let file_name_text_and_positions = path.file_name().map(|file_name| {
389        let text = file_name.to_string_lossy();
390        let char_count = text.chars().count();
391        let file_name_start = path_char_count - char_count;
392        let highlight_positions = path_positions
393            .iter()
394            .copied()
395            .skip_while(|position| *position < file_name_start)
396            .take_while(|position| *position < file_name_start + char_count)
397            .map(|position| position - file_name_start)
398            .collect::<Vec<_>>();
399        HighlightedText {
400            text: text.to_string(),
401            highlight_positions,
402            char_count,
403        }
404    });
405
406    (
407        file_name_text_and_positions,
408        HighlightedText {
409            text: path_string.to_string(),
410            highlight_positions: path_positions,
411            char_count: path_char_count,
412        },
413    )
414}
415
416impl RecentProjectsDelegate {
417    fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
418        if let Some(selected_match) = self.matches.get(ix) {
419            let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
420            cx.spawn(move |this, mut cx| async move {
421                let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
422                let workspaces = WORKSPACE_DB
423                    .recent_workspaces_on_disk()
424                    .await
425                    .unwrap_or_default();
426                this.update(&mut cx, move |picker, cx| {
427                    picker.delegate.workspaces = workspaces;
428                    picker.delegate.set_selected_index(ix - 1, cx);
429                    picker.delegate.reset_selected_match_index = false;
430                    picker.update_matches(picker.query(cx), cx)
431                })
432            })
433            .detach();
434        }
435    }
436
437    fn is_current_workspace(
438        &self,
439        workspace_id: WorkspaceId,
440        cx: &mut ViewContext<Picker<Self>>,
441    ) -> bool {
442        if let Some(workspace) = self.workspace.upgrade() {
443            let workspace = workspace.read(cx);
444            if workspace_id == workspace.database_id() {
445                return true;
446            }
447        }
448
449        false
450    }
451}
452struct MatchTooltip {
453    highlighted_location: HighlightedMatchWithPaths,
454}
455
456impl Render for MatchTooltip {
457    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
458        tooltip_container(cx, |div, _| {
459            self.highlighted_location.render_paths_children(div)
460        })
461    }
462}
463
464#[cfg(test)]
465mod tests {
466    use std::path::PathBuf;
467
468    use editor::Editor;
469    use gpui::{TestAppContext, WindowHandle};
470    use project::Project;
471    use serde_json::json;
472    use workspace::{open_paths, AppState};
473
474    use super::*;
475
476    #[gpui::test]
477    async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
478        let app_state = init_test(cx);
479        app_state
480            .fs
481            .as_fake()
482            .insert_tree(
483                "/dir",
484                json!({
485                    "main.ts": "a"
486                }),
487            )
488            .await;
489        cx.update(|cx| open_paths(&[PathBuf::from("/dir/main.ts")], app_state, None, cx))
490            .await
491            .unwrap();
492        assert_eq!(cx.update(|cx| cx.windows().len()), 1);
493
494        let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
495        workspace
496            .update(cx, |workspace, _| assert!(!workspace.is_edited()))
497            .unwrap();
498
499        let editor = workspace
500            .read_with(cx, |workspace, cx| {
501                workspace
502                    .active_item(cx)
503                    .unwrap()
504                    .downcast::<Editor>()
505                    .unwrap()
506            })
507            .unwrap();
508        workspace
509            .update(cx, |_, cx| {
510                editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
511            })
512            .unwrap();
513        workspace
514            .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
515            .unwrap();
516
517        let recent_projects_picker = open_recent_projects(&workspace, cx);
518        workspace
519            .update(cx, |_, cx| {
520                recent_projects_picker.update(cx, |picker, cx| {
521                    assert_eq!(picker.query(cx), "");
522                    let delegate = &mut picker.delegate;
523                    delegate.matches = vec![StringMatch {
524                        candidate_id: 0,
525                        score: 1.0,
526                        positions: Vec::new(),
527                        string: "fake candidate".to_string(),
528                    }];
529                    delegate.workspaces = vec![(0, WorkspaceLocation::new(vec!["/test/path/"]))];
530                });
531            })
532            .unwrap();
533
534        assert!(
535            !cx.has_pending_prompt(),
536            "Should have no pending prompt on dirty project before opening the new recent project"
537        );
538        cx.dispatch_action(*workspace, menu::Confirm);
539        workspace
540            .update(cx, |workspace, cx| {
541                assert!(
542                    workspace.active_modal::<RecentProjects>(cx).is_none(),
543                    "Should remove the modal after selecting new recent project"
544                )
545            })
546            .unwrap();
547        assert!(
548            cx.has_pending_prompt(),
549            "Dirty workspace should prompt before opening the new recent project"
550        );
551        // Cancel
552        cx.simulate_prompt_answer(0);
553        assert!(
554            !cx.has_pending_prompt(),
555            "Should have no pending prompt after cancelling"
556        );
557        workspace
558            .update(cx, |workspace, _| {
559                assert!(
560                    workspace.is_edited(),
561                    "Should be in the same dirty project after cancelling"
562                )
563            })
564            .unwrap();
565    }
566
567    fn open_recent_projects(
568        workspace: &WindowHandle<Workspace>,
569        cx: &mut TestAppContext,
570    ) -> View<Picker<RecentProjectsDelegate>> {
571        cx.dispatch_action(
572            (*workspace).into(),
573            OpenRecent {
574                create_new_window: false,
575            },
576        );
577        workspace
578            .update(cx, |workspace, cx| {
579                workspace
580                    .active_modal::<RecentProjects>(cx)
581                    .unwrap()
582                    .read(cx)
583                    .picker
584                    .clone()
585            })
586            .unwrap()
587    }
588
589    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
590        cx.update(|cx| {
591            let state = AppState::test(cx);
592            language::init(cx);
593            crate::init(cx);
594            editor::init(cx);
595            workspace::init_settings(cx);
596            Project::init_settings(cx);
597            state
598        })
599    }
600}