recent_projects.rs

  1pub mod disconnected_overlay;
  2mod remote_servers;
  3mod ssh_connections;
  4pub use ssh_connections::{is_connecting_over_ssh, open_ssh_project};
  5
  6use disconnected_overlay::DisconnectedOverlay;
  7use fuzzy::{StringMatch, StringMatchCandidate};
  8use gpui::{
  9    Action, AnyElement, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
 10    Subscription, Task, View, ViewContext, WeakView,
 11};
 12use ordered_float::OrderedFloat;
 13use picker::{
 14    highlighted_match_with_paths::{HighlightedMatchWithPaths, HighlightedText},
 15    Picker, PickerDelegate,
 16};
 17pub use remote_servers::RemoteServerProjects;
 18use settings::Settings;
 19pub use ssh_connections::SshSettings;
 20use std::{
 21    path::{Path, PathBuf},
 22    sync::Arc,
 23};
 24use ui::{prelude::*, tooltip_container, KeyBinding, ListItem, ListItemSpacing, Tooltip};
 25use util::{paths::PathExt, ResultExt};
 26use workspace::{
 27    CloseIntent, ModalView, OpenOptions, SerializedWorkspaceLocation, Workspace, WorkspaceId,
 28    WORKSPACE_DB,
 29};
 30use zed_actions::{OpenRecent, OpenRemote};
 31
 32pub fn init(cx: &mut AppContext) {
 33    SshSettings::register(cx);
 34    cx.observe_new_views(RecentProjects::register).detach();
 35    cx.observe_new_views(RemoteServerProjects::register)
 36        .detach();
 37    cx.observe_new_views(DisconnectedOverlay::register).detach();
 38}
 39
 40pub struct RecentProjects {
 41    pub picker: View<Picker<RecentProjectsDelegate>>,
 42    rem_width: f32,
 43    _subscription: Subscription,
 44}
 45
 46impl ModalView for RecentProjects {}
 47
 48impl RecentProjects {
 49    fn new(delegate: RecentProjectsDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
 50        let picker = cx.new_view(|cx| {
 51            // We want to use a list when we render paths, because the items can have different heights (multiple paths).
 52            if delegate.render_paths {
 53                Picker::list(delegate, cx)
 54            } else {
 55                Picker::uniform_list(delegate, cx)
 56            }
 57        });
 58        let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
 59        // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
 60        // out workspace locations once the future runs to completion.
 61        cx.spawn(|this, mut cx| async move {
 62            let workspaces = WORKSPACE_DB
 63                .recent_workspaces_on_disk()
 64                .await
 65                .log_err()
 66                .unwrap_or_default();
 67            this.update(&mut cx, move |this, cx| {
 68                this.picker.update(cx, move |picker, cx| {
 69                    picker.delegate.set_workspaces(workspaces);
 70                    picker.update_matches(picker.query(cx), cx)
 71                })
 72            })
 73            .ok()
 74        })
 75        .detach();
 76        Self {
 77            picker,
 78            rem_width,
 79            _subscription,
 80        }
 81    }
 82
 83    fn register(workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>) {
 84        workspace.register_action(|workspace, open_recent: &OpenRecent, cx| {
 85            let Some(recent_projects) = workspace.active_modal::<Self>(cx) else {
 86                Self::open(workspace, open_recent.create_new_window, cx);
 87                return;
 88            };
 89
 90            recent_projects.update(cx, |recent_projects, cx| {
 91                recent_projects
 92                    .picker
 93                    .update(cx, |picker, cx| picker.cycle_selection(cx))
 94            });
 95        });
 96    }
 97
 98    pub fn open(
 99        workspace: &mut Workspace,
100        create_new_window: bool,
101        cx: &mut ViewContext<Workspace>,
102    ) {
103        let weak = cx.view().downgrade();
104        workspace.toggle_modal(cx, |cx| {
105            let delegate = RecentProjectsDelegate::new(weak, create_new_window, true);
106
107            Self::new(delegate, 34., cx)
108        })
109    }
110}
111
112impl EventEmitter<DismissEvent> for RecentProjects {}
113
114impl FocusableView for RecentProjects {
115    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
116        self.picker.focus_handle(cx)
117    }
118}
119
120impl Render for RecentProjects {
121    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
122        v_flex()
123            .w(rems(self.rem_width))
124            .child(self.picker.clone())
125            .on_mouse_down_out(cx.listener(|this, _, cx| {
126                this.picker.update(cx, |this, cx| {
127                    this.cancel(&Default::default(), cx);
128                })
129            }))
130    }
131}
132
133pub struct RecentProjectsDelegate {
134    workspace: WeakView<Workspace>,
135    workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation)>,
136    selected_match_index: usize,
137    matches: Vec<StringMatch>,
138    render_paths: bool,
139    create_new_window: bool,
140    // Flag to reset index when there is a new query vs not reset index when user delete an item
141    reset_selected_match_index: bool,
142    has_any_non_local_projects: bool,
143}
144
145impl RecentProjectsDelegate {
146    fn new(workspace: WeakView<Workspace>, create_new_window: bool, render_paths: bool) -> Self {
147        Self {
148            workspace,
149            workspaces: Vec::new(),
150            selected_match_index: 0,
151            matches: Default::default(),
152            create_new_window,
153            render_paths,
154            reset_selected_match_index: true,
155            has_any_non_local_projects: false,
156        }
157    }
158
159    pub fn set_workspaces(&mut self, workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation)>) {
160        self.workspaces = workspaces;
161        self.has_any_non_local_projects = !self
162            .workspaces
163            .iter()
164            .all(|(_, location)| matches!(location, SerializedWorkspaceLocation::Local(_, _)));
165    }
166}
167impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
168impl PickerDelegate for RecentProjectsDelegate {
169    type ListItem = ListItem;
170
171    fn placeholder_text(&self, cx: &mut WindowContext) -> Arc<str> {
172        let (create_window, reuse_window) = if self.create_new_window {
173            (
174                cx.keystroke_text_for(&menu::Confirm),
175                cx.keystroke_text_for(&menu::SecondaryConfirm),
176            )
177        } else {
178            (
179                cx.keystroke_text_for(&menu::SecondaryConfirm),
180                cx.keystroke_text_for(&menu::Confirm),
181            )
182        };
183        Arc::from(format!(
184            "{reuse_window} reuses this window, {create_window} opens a new one",
185        ))
186    }
187
188    fn match_count(&self) -> usize {
189        self.matches.len()
190    }
191
192    fn selected_index(&self) -> usize {
193        self.selected_match_index
194    }
195
196    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
197        self.selected_match_index = ix;
198    }
199
200    fn update_matches(
201        &mut self,
202        query: String,
203        cx: &mut ViewContext<Picker<Self>>,
204    ) -> gpui::Task<()> {
205        let query = query.trim_start();
206        let smart_case = query.chars().any(|c| c.is_uppercase());
207        let candidates = self
208            .workspaces
209            .iter()
210            .enumerate()
211            .filter(|(_, (id, _))| !self.is_current_workspace(*id, cx))
212            .map(|(id, (_, location))| {
213                let combined_string = location
214                    .sorted_paths()
215                    .iter()
216                    .map(|path| path.compact().to_string_lossy().into_owned())
217                    .collect::<Vec<_>>()
218                    .join("");
219
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() == Some(*candidate_workspace_id) {
263                        Task::ready(Ok(()))
264                    } else {
265                        match candidate_workspace_location {
266                            SerializedWorkspaceLocation::Local(paths, _) => {
267                                let paths = paths.paths().to_vec();
268                                if replace_current_window {
269                                    cx.spawn(move |workspace, mut cx| async move {
270                                        let continue_replacing = workspace
271                                            .update(&mut cx, |workspace, cx| {
272                                                workspace.prepare_to_close(
273                                                    CloseIntent::ReplaceWindow,
274                                                    cx,
275                                                )
276                                            })?
277                                            .await?;
278                                        if continue_replacing {
279                                            workspace
280                                                .update(&mut cx, |workspace, cx| {
281                                                    workspace
282                                                        .open_workspace_for_paths(true, paths, cx)
283                                                })?
284                                                .await
285                                        } else {
286                                            Ok(())
287                                        }
288                                    })
289                                } else {
290                                    workspace.open_workspace_for_paths(false, paths, cx)
291                                }
292                            }
293                            SerializedWorkspaceLocation::Ssh(ssh_project) => {
294                                let app_state = workspace.app_state().clone();
295
296                                let replace_window = if replace_current_window {
297                                    cx.window_handle().downcast::<Workspace>()
298                                } else {
299                                    None
300                                };
301
302                                let open_options = OpenOptions {
303                                    replace_window,
304                                    ..Default::default()
305                                };
306
307                                let connection_options = SshSettings::get_global(cx)
308                                    .connection_options_for(
309                                        ssh_project.host.clone(),
310                                        ssh_project.port,
311                                        ssh_project.user.clone(),
312                                    );
313
314                                let paths = ssh_project.paths.iter().map(PathBuf::from).collect();
315
316                                cx.spawn(|_, mut cx| async move {
317                                    open_ssh_project(
318                                        connection_options,
319                                        paths,
320                                        app_state,
321                                        open_options,
322                                        &mut cx,
323                                    )
324                                    .await
325                                })
326                            }
327                        }
328                    }
329                })
330                .detach_and_log_err(cx);
331            cx.emit(DismissEvent);
332        }
333    }
334
335    fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
336
337    fn no_matches_text(&self, _cx: &mut WindowContext) -> SharedString {
338        if self.workspaces.is_empty() {
339            "Recently opened projects will show up here".into()
340        } else {
341            "No matches".into()
342        }
343    }
344
345    fn render_match(
346        &self,
347        ix: usize,
348        selected: bool,
349        cx: &mut ViewContext<Picker<Self>>,
350    ) -> Option<Self::ListItem> {
351        let hit = self.matches.get(ix)?;
352
353        let (_, location) = self.workspaces.get(hit.candidate_id)?;
354
355        let mut path_start_offset = 0;
356
357        let (match_labels, paths): (Vec<_>, Vec<_>) = location
358            .sorted_paths()
359            .iter()
360            .map(|p| p.compact())
361            .map(|path| {
362                let highlighted_text =
363                    highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
364
365                path_start_offset += highlighted_text.1.char_count;
366                highlighted_text
367            })
368            .unzip();
369
370        let highlighted_match = HighlightedMatchWithPaths {
371            match_label: HighlightedText::join(match_labels.into_iter().flatten(), ", "),
372            paths,
373        };
374
375        Some(
376            ListItem::new(ix)
377                .toggle_state(selected)
378                .inset(true)
379                .spacing(ListItemSpacing::Sparse)
380                .child(
381                    h_flex()
382                        .flex_grow()
383                        .gap_3()
384                        .when(self.has_any_non_local_projects, |this| {
385                            this.child(match location {
386                                SerializedWorkspaceLocation::Local(_, _) => {
387                                    Icon::new(IconName::Screen)
388                                        .color(Color::Muted)
389                                        .into_any_element()
390                                }
391                                SerializedWorkspaceLocation::Ssh(_) => Icon::new(IconName::Server)
392                                    .color(Color::Muted)
393                                    .into_any_element(),
394                            })
395                        })
396                        .child({
397                            let mut highlighted = highlighted_match.clone();
398                            if !self.render_paths {
399                                highlighted.paths.clear();
400                            }
401                            highlighted.render(cx)
402                        }),
403                )
404                .map(|el| {
405                    let delete_button = div()
406                        .child(
407                            IconButton::new("delete", IconName::Close)
408                                .icon_size(IconSize::Small)
409                                .on_click(cx.listener(move |this, _event, cx| {
410                                    cx.stop_propagation();
411                                    cx.prevent_default();
412
413                                    this.delegate.delete_recent_project(ix, cx)
414                                }))
415                                .tooltip(|cx| Tooltip::text("Delete from Recent Projects...", cx)),
416                        )
417                        .into_any_element();
418
419                    if self.selected_index() == ix {
420                        el.end_slot::<AnyElement>(delete_button)
421                    } else {
422                        el.end_hover_slot::<AnyElement>(delete_button)
423                    }
424                })
425                .tooltip(move |cx| {
426                    let tooltip_highlighted_location = highlighted_match.clone();
427                    cx.new_view(move |_| MatchTooltip {
428                        highlighted_location: tooltip_highlighted_location,
429                    })
430                    .into()
431                }),
432        )
433    }
434
435    fn render_footer(&self, cx: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
436        Some(
437            h_flex()
438                .w_full()
439                .p_2()
440                .gap_2()
441                .justify_end()
442                .border_t_1()
443                .border_color(cx.theme().colors().border_variant)
444                .child(
445                    Button::new("remote", "Open Remote Folder")
446                        .key_binding(KeyBinding::for_action(&OpenRemote, cx))
447                        .on_click(|_, cx| cx.dispatch_action(OpenRemote.boxed_clone())),
448                )
449                .child(
450                    Button::new("local", "Open Local Folder")
451                        .key_binding(KeyBinding::for_action(&workspace::Open, cx))
452                        .on_click(|_, cx| cx.dispatch_action(workspace::Open.boxed_clone())),
453                )
454                .into_any(),
455        )
456    }
457}
458
459// Compute the highlighted text for the name and path
460fn highlights_for_path(
461    path: &Path,
462    match_positions: &Vec<usize>,
463    path_start_offset: usize,
464) -> (Option<HighlightedText>, HighlightedText) {
465    let path_string = path.to_string_lossy();
466    let path_char_count = path_string.chars().count();
467    // Get the subset of match highlight positions that line up with the given path.
468    // Also adjusts them to start at the path start
469    let path_positions = match_positions
470        .iter()
471        .copied()
472        .skip_while(|position| *position < path_start_offset)
473        .take_while(|position| *position < path_start_offset + path_char_count)
474        .map(|position| position - path_start_offset)
475        .collect::<Vec<_>>();
476
477    // Again subset the highlight positions to just those that line up with the file_name
478    // again adjusted to the start of the file_name
479    let file_name_text_and_positions = path.file_name().map(|file_name| {
480        let text = file_name.to_string_lossy();
481        let char_count = text.chars().count();
482        let file_name_start = path_char_count - char_count;
483        let highlight_positions = path_positions
484            .iter()
485            .copied()
486            .skip_while(|position| *position < file_name_start)
487            .take_while(|position| *position < file_name_start + char_count)
488            .map(|position| position - file_name_start)
489            .collect::<Vec<_>>();
490        HighlightedText {
491            text: text.to_string(),
492            highlight_positions,
493            char_count,
494            color: Color::Default,
495        }
496    });
497
498    (
499        file_name_text_and_positions,
500        HighlightedText {
501            text: path_string.to_string(),
502            highlight_positions: path_positions,
503            char_count: path_char_count,
504            color: Color::Default,
505        },
506    )
507}
508impl RecentProjectsDelegate {
509    fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
510        if let Some(selected_match) = self.matches.get(ix) {
511            let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
512            cx.spawn(move |this, mut cx| async move {
513                let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
514                let workspaces = WORKSPACE_DB
515                    .recent_workspaces_on_disk()
516                    .await
517                    .unwrap_or_default();
518                this.update(&mut cx, move |picker, cx| {
519                    picker.delegate.set_workspaces(workspaces);
520                    picker.delegate.set_selected_index(ix.saturating_sub(1), cx);
521                    picker.delegate.reset_selected_match_index = false;
522                    picker.update_matches(picker.query(cx), cx)
523                })
524            })
525            .detach();
526        }
527    }
528
529    fn is_current_workspace(
530        &self,
531        workspace_id: WorkspaceId,
532        cx: &mut ViewContext<Picker<Self>>,
533    ) -> bool {
534        if let Some(workspace) = self.workspace.upgrade() {
535            let workspace = workspace.read(cx);
536            if Some(workspace_id) == workspace.database_id() {
537                return true;
538            }
539        }
540
541        false
542    }
543}
544struct MatchTooltip {
545    highlighted_location: HighlightedMatchWithPaths,
546}
547
548impl Render for MatchTooltip {
549    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
550        tooltip_container(cx, |div, _| {
551            self.highlighted_location.render_paths_children(div)
552        })
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use std::path::PathBuf;
559
560    use editor::Editor;
561    use gpui::{TestAppContext, UpdateGlobal, WindowHandle};
562    use project::{project_settings::ProjectSettings, Project};
563    use serde_json::json;
564    use settings::SettingsStore;
565    use workspace::{open_paths, AppState};
566
567    use super::*;
568
569    #[gpui::test]
570    async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
571        let app_state = init_test(cx);
572
573        cx.update(|cx| {
574            SettingsStore::update_global(cx, |store, cx| {
575                store.update_user_settings::<ProjectSettings>(cx, |settings| {
576                    settings.session.restore_unsaved_buffers = false
577                });
578            });
579        });
580
581        app_state
582            .fs
583            .as_fake()
584            .insert_tree(
585                "/dir",
586                json!({
587                    "main.ts": "a"
588                }),
589            )
590            .await;
591        cx.update(|cx| {
592            open_paths(
593                &[PathBuf::from("/dir/main.ts")],
594                app_state,
595                workspace::OpenOptions::default(),
596                cx,
597            )
598        })
599        .await
600        .unwrap();
601        assert_eq!(cx.update(|cx| cx.windows().len()), 1);
602
603        let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
604        workspace
605            .update(cx, |workspace, _| assert!(!workspace.is_edited()))
606            .unwrap();
607
608        let editor = workspace
609            .read_with(cx, |workspace, cx| {
610                workspace
611                    .active_item(cx)
612                    .unwrap()
613                    .downcast::<Editor>()
614                    .unwrap()
615            })
616            .unwrap();
617        workspace
618            .update(cx, |_, cx| {
619                editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
620            })
621            .unwrap();
622        workspace
623            .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
624            .unwrap();
625
626        let recent_projects_picker = open_recent_projects(&workspace, cx);
627        workspace
628            .update(cx, |_, cx| {
629                recent_projects_picker.update(cx, |picker, cx| {
630                    assert_eq!(picker.query(cx), "");
631                    let delegate = &mut picker.delegate;
632                    delegate.matches = vec![StringMatch {
633                        candidate_id: 0,
634                        score: 1.0,
635                        positions: Vec::new(),
636                        string: "fake candidate".to_string(),
637                    }];
638                    delegate.set_workspaces(vec![(
639                        WorkspaceId::default(),
640                        SerializedWorkspaceLocation::from_local_paths(vec!["/test/path/"]),
641                    )]);
642                });
643            })
644            .unwrap();
645
646        assert!(
647            !cx.has_pending_prompt(),
648            "Should have no pending prompt on dirty project before opening the new recent project"
649        );
650        cx.dispatch_action(*workspace, menu::Confirm);
651        workspace
652            .update(cx, |workspace, cx| {
653                assert!(
654                    workspace.active_modal::<RecentProjects>(cx).is_none(),
655                    "Should remove the modal after selecting new recent project"
656                )
657            })
658            .unwrap();
659        assert!(
660            cx.has_pending_prompt(),
661            "Dirty workspace should prompt before opening the new recent project"
662        );
663        // Cancel
664        cx.simulate_prompt_answer(0);
665        assert!(
666            !cx.has_pending_prompt(),
667            "Should have no pending prompt after cancelling"
668        );
669        workspace
670            .update(cx, |workspace, _| {
671                assert!(
672                    workspace.is_edited(),
673                    "Should be in the same dirty project after cancelling"
674                )
675            })
676            .unwrap();
677    }
678
679    fn open_recent_projects(
680        workspace: &WindowHandle<Workspace>,
681        cx: &mut TestAppContext,
682    ) -> View<Picker<RecentProjectsDelegate>> {
683        cx.dispatch_action(
684            (*workspace).into(),
685            OpenRecent {
686                create_new_window: false,
687            },
688        );
689        workspace
690            .update(cx, |workspace, cx| {
691                workspace
692                    .active_modal::<RecentProjects>(cx)
693                    .unwrap()
694                    .read(cx)
695                    .picker
696                    .clone()
697            })
698            .unwrap()
699    }
700
701    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
702        cx.update(|cx| {
703            let state = AppState::test(cx);
704            language::init(cx);
705            crate::init(cx);
706            editor::init(cx);
707            workspace::init_settings(cx);
708            Project::init_settings(cx);
709            state
710        })
711    }
712}