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)]
 20    pub create_new_window: bool,
 21}
 22
 23gpui::impl_actions!(projects, [OpenRecent]);
 24
 25pub fn init(cx: &mut AppContext) {
 26    cx.observe_new_views(RecentProjects::register).detach();
 27}
 28
 29pub struct RecentProjects {
 30    pub picker: View<Picker<RecentProjectsDelegate>>,
 31    rem_width: f32,
 32    _subscription: Subscription,
 33}
 34
 35impl ModalView for RecentProjects {}
 36
 37impl RecentProjects {
 38    fn new(delegate: RecentProjectsDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
 39        let picker = cx.new_view(|cx| {
 40            // We want to use a list when we render paths, because the items can have different heights (multiple paths).
 41            if delegate.render_paths {
 42                Picker::list(delegate, cx)
 43            } else {
 44                Picker::uniform_list(delegate, cx)
 45            }
 46        });
 47        let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
 48        // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
 49        // out workspace locations once the future runs to completion.
 50        cx.spawn(|this, mut cx| async move {
 51            let workspaces = WORKSPACE_DB
 52                .recent_workspaces_on_disk()
 53                .await
 54                .unwrap_or_default();
 55
 56            this.update(&mut cx, move |this, cx| {
 57                this.picker.update(cx, move |picker, cx| {
 58                    picker.delegate.workspaces = workspaces;
 59                    picker.update_matches(picker.query(cx), cx)
 60                })
 61            })
 62            .ok()
 63        })
 64        .detach();
 65        Self {
 66            picker,
 67            rem_width,
 68            _subscription,
 69        }
 70    }
 71
 72    fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
 73        workspace.register_action(|workspace, open_recent: &OpenRecent, cx| {
 74            let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {
 75                if let Some(handler) = Self::open(workspace, open_recent.create_new_window, cx) {
 76                    handler.detach_and_log_err(cx);
 77                }
 78                return;
 79            };
 80
 81            recent_projects.update(cx, |recent_projects, cx| {
 82                recent_projects
 83                    .picker
 84                    .update(cx, |picker, cx| picker.cycle_selection(cx))
 85            });
 86        });
 87    }
 88
 89    fn open(
 90        _: &mut Workspace,
 91        create_new_window: bool,
 92        cx: &mut ViewContext<Workspace>,
 93    ) -> Option<Task<Result<()>>> {
 94        Some(cx.spawn(|workspace, mut cx| async move {
 95            workspace.update(&mut cx, |workspace, cx| {
 96                let weak_workspace = cx.view().downgrade();
 97                workspace.toggle_modal(cx, |cx| {
 98                    let delegate =
 99                        RecentProjectsDelegate::new(weak_workspace, create_new_window, true);
100
101                    let modal = Self::new(delegate, 34., cx);
102                    modal
103                });
104            })?;
105            Ok(())
106        }))
107    }
108
109    pub fn open_popover(workspace: WeakView<Workspace>, cx: &mut WindowContext<'_>) -> View<Self> {
110        cx.new_view(|cx| {
111            Self::new(
112                RecentProjectsDelegate::new(workspace, false, false),
113                20.,
114                cx,
115            )
116        })
117    }
118}
119
120impl EventEmitter<DismissEvent> for RecentProjects {}
121
122impl FocusableView for RecentProjects {
123    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
124        self.picker.focus_handle(cx)
125    }
126}
127
128impl Render for RecentProjects {
129    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
130        v_flex()
131            .w(rems(self.rem_width))
132            .cursor_pointer()
133            .child(self.picker.clone())
134            .on_mouse_down_out(cx.listener(|this, _, cx| {
135                this.picker.update(cx, |this, cx| {
136                    this.cancel(&Default::default(), cx);
137                })
138            }))
139    }
140}
141
142pub struct RecentProjectsDelegate {
143    workspace: WeakView<Workspace>,
144    workspaces: Vec<(WorkspaceId, WorkspaceLocation)>,
145    selected_match_index: usize,
146    matches: Vec<StringMatch>,
147    render_paths: bool,
148    create_new_window: bool,
149    // Flag to reset index when there is a new query vs not reset index when user delete an item
150    reset_selected_match_index: bool,
151}
152
153impl RecentProjectsDelegate {
154    fn new(workspace: WeakView<Workspace>, create_new_window: bool, render_paths: bool) -> Self {
155        Self {
156            workspace,
157            workspaces: vec![],
158            selected_match_index: 0,
159            matches: Default::default(),
160            create_new_window,
161            render_paths,
162            reset_selected_match_index: true,
163        }
164    }
165}
166impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
167impl PickerDelegate for RecentProjectsDelegate {
168    type ListItem = ListItem;
169
170    fn placeholder_text(&self, cx: &mut WindowContext) -> Arc<str> {
171        let (create_window, reuse_window) = if self.create_new_window {
172            (
173                cx.keystroke_text_for(&menu::Confirm),
174                cx.keystroke_text_for(&menu::SecondaryConfirm),
175            )
176        } else {
177            (
178                cx.keystroke_text_for(&menu::SecondaryConfirm),
179                cx.keystroke_text_for(&menu::Confirm),
180            )
181        };
182        Arc::from(format!(
183            "{reuse_window} reuses the window, {create_window} opens a new one",
184        ))
185    }
186
187    fn match_count(&self) -> usize {
188        self.matches.len()
189    }
190
191    fn selected_index(&self) -> usize {
192        self.selected_match_index
193    }
194
195    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
196        self.selected_match_index = ix;
197    }
198
199    fn update_matches(
200        &mut self,
201        query: String,
202        cx: &mut ViewContext<Picker<Self>>,
203    ) -> gpui::Task<()> {
204        let query = query.trim_start();
205        let smart_case = query.chars().any(|c| c.is_uppercase());
206        let candidates = self
207            .workspaces
208            .iter()
209            .enumerate()
210            .map(|(id, (_, location))| {
211                let combined_string = location
212                    .paths()
213                    .iter()
214                    .map(|path| path.compact().to_string_lossy().into_owned())
215                    .collect::<Vec<_>>()
216                    .join("");
217                StringMatchCandidate::new(id, combined_string)
218            })
219            .collect::<Vec<_>>();
220        self.matches = smol::block_on(fuzzy::match_strings(
221            candidates.as_slice(),
222            query,
223            smart_case,
224            100,
225            &Default::default(),
226            cx.background_executor().clone(),
227        ));
228        self.matches.sort_unstable_by_key(|m| m.candidate_id);
229
230        if self.reset_selected_match_index {
231            self.selected_match_index = self
232                .matches
233                .iter()
234                .enumerate()
235                .rev()
236                .max_by_key(|(_, m)| OrderedFloat(m.score))
237                .map(|(ix, _)| ix)
238                .unwrap_or(0);
239        }
240        self.reset_selected_match_index = true;
241        Task::ready(())
242    }
243
244    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
245        if let Some((selected_match, workspace)) = self
246            .matches
247            .get(self.selected_index())
248            .zip(self.workspace.upgrade())
249        {
250            let (candidate_workspace_id, candidate_workspace_location) =
251                &self.workspaces[selected_match.candidate_id];
252            let replace_current_window = if self.create_new_window {
253                secondary
254            } else {
255                !secondary
256            };
257            workspace
258                .update(cx, |workspace, cx| {
259                    if workspace.database_id() != *candidate_workspace_id {
260                        let candidate_paths = candidate_workspace_location.paths().as_ref().clone();
261                        if replace_current_window {
262                            cx.spawn(move |workspace, mut cx| async move {
263                                let continue_replacing = workspace
264                                    .update(&mut cx, |workspace, cx| {
265                                        workspace.prepare_to_close(true, cx)
266                                    })?
267                                    .await?;
268                                if continue_replacing {
269                                    workspace
270                                        .update(&mut cx, |workspace, cx| {
271                                            workspace.open_workspace_for_paths(
272                                                replace_current_window,
273                                                candidate_paths,
274                                                cx,
275                                            )
276                                        })?
277                                        .await
278                                } else {
279                                    Ok(())
280                                }
281                            })
282                        } else {
283                            workspace.open_workspace_for_paths(
284                                replace_current_window,
285                                candidate_paths,
286                                cx,
287                            )
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}