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