recent_projects.rs

  1pub mod disconnected_overlay;
  2mod remote_connections;
  3mod remote_servers;
  4mod ssh_config;
  5
  6#[cfg(target_os = "windows")]
  7mod wsl_picker;
  8
  9use remote::RemoteConnectionOptions;
 10pub use remote_connections::{RemoteConnectionModal, connect, open_remote_project};
 11
 12use disconnected_overlay::DisconnectedOverlay;
 13use fuzzy::{StringMatch, StringMatchCandidate};
 14use gpui::{
 15    Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
 16    Subscription, Task, WeakEntity, Window,
 17};
 18use ordered_float::OrderedFloat;
 19use picker::{
 20    Picker, PickerDelegate,
 21    highlighted_match_with_paths::{HighlightedMatch, HighlightedMatchWithPaths},
 22};
 23pub use remote_connections::SshSettings;
 24pub use remote_servers::RemoteServerProjects;
 25use settings::Settings;
 26use std::{path::Path, sync::Arc};
 27use ui::{KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*, tooltip_container};
 28use util::{ResultExt, paths::PathExt};
 29use workspace::{
 30    CloseIntent, HistoryManager, ModalView, OpenOptions, PathList, SerializedWorkspaceLocation,
 31    WORKSPACE_DB, Workspace, WorkspaceId, notifications::DetachAndPromptErr,
 32    with_active_or_new_workspace,
 33};
 34use zed_actions::{OpenRecent, OpenRemote};
 35
 36pub fn init(cx: &mut App) {
 37    #[cfg(target_os = "windows")]
 38    cx.on_action(|open_wsl: &zed_actions::wsl_actions::OpenFolderInWsl, cx| {
 39        let create_new_window = open_wsl.create_new_window;
 40        with_active_or_new_workspace(cx, move |workspace, window, cx| {
 41            use gpui::PathPromptOptions;
 42            use project::DirectoryLister;
 43
 44            let paths = workspace.prompt_for_open_path(
 45                PathPromptOptions {
 46                    files: true,
 47                    directories: true,
 48                    multiple: false,
 49                    prompt: None,
 50                },
 51                DirectoryLister::Local(
 52                    workspace.project().clone(),
 53                    workspace.app_state().fs.clone(),
 54                ),
 55                window,
 56                cx,
 57            );
 58
 59            cx.spawn_in(window, async move |workspace, cx| {
 60                use util::paths::SanitizedPath;
 61
 62                let Some(paths) = paths.await.log_err().flatten() else {
 63                    return;
 64                };
 65
 66                let paths = paths
 67                    .into_iter()
 68                    .filter_map(|path| SanitizedPath::new(&path).local_to_wsl())
 69                    .collect::<Vec<_>>();
 70
 71                if paths.is_empty() {
 72                    let message = indoc::indoc! { r#"
 73                        Invalid path specified when trying to open a folder inside WSL.
 74
 75                        Please note that Zed currently does not support opening network share folders inside wsl.
 76                    "#};
 77
 78                    let _ = cx.prompt(gpui::PromptLevel::Critical, "Invalid path", Some(&message), &["Ok"]).await;
 79                    return;
 80                }
 81
 82                workspace.update_in(cx, |workspace, window, cx| {
 83                    workspace.toggle_modal(window, cx, |window, cx| {
 84                        crate::wsl_picker::WslOpenModal::new(paths, create_new_window, window, cx)
 85                    });
 86                }).log_err();
 87            })
 88            .detach();
 89        });
 90    });
 91
 92    #[cfg(target_os = "windows")]
 93    cx.on_action(|open_wsl: &zed_actions::wsl_actions::OpenWsl, cx| {
 94        let create_new_window = open_wsl.create_new_window;
 95        with_active_or_new_workspace(cx, move |workspace, window, cx| {
 96            let handle = cx.entity().downgrade();
 97            let fs = workspace.project().read(cx).fs().clone();
 98            workspace.toggle_modal(window, cx, |window, cx| {
 99                RemoteServerProjects::wsl(create_new_window, fs, window, handle, cx)
100            });
101        });
102    });
103
104    #[cfg(target_os = "windows")]
105    cx.on_action(|open_wsl: &remote::OpenWslPath, cx| {
106        let open_wsl = open_wsl.clone();
107        with_active_or_new_workspace(cx, move |workspace, window, cx| {
108            let fs = workspace.project().read(cx).fs().clone();
109            add_wsl_distro(fs, &open_wsl.distro, cx);
110            let open_options = OpenOptions {
111                replace_window: window.window_handle().downcast::<Workspace>(),
112                ..Default::default()
113            };
114
115            let app_state = workspace.app_state().clone();
116
117            cx.spawn_in(window, async move |_, cx| {
118                open_remote_project(
119                    RemoteConnectionOptions::Wsl(open_wsl.distro.clone()),
120                    open_wsl.paths,
121                    app_state,
122                    open_options,
123                    cx,
124                )
125                .await
126            })
127            .detach();
128        });
129    });
130
131    cx.on_action(|open_recent: &OpenRecent, cx| {
132        let create_new_window = open_recent.create_new_window;
133        with_active_or_new_workspace(cx, move |workspace, window, cx| {
134            let Some(recent_projects) = workspace.active_modal::<RecentProjects>(cx) else {
135                RecentProjects::open(workspace, create_new_window, window, cx);
136                return;
137            };
138
139            recent_projects.update(cx, |recent_projects, cx| {
140                recent_projects
141                    .picker
142                    .update(cx, |picker, cx| picker.cycle_selection(window, cx))
143            });
144        });
145    });
146    cx.on_action(|open_remote: &OpenRemote, cx| {
147        let from_existing_connection = open_remote.from_existing_connection;
148        let create_new_window = open_remote.create_new_window;
149        with_active_or_new_workspace(cx, move |workspace, window, cx| {
150            if from_existing_connection {
151                cx.propagate();
152                return;
153            }
154            let handle = cx.entity().downgrade();
155            let fs = workspace.project().read(cx).fs().clone();
156            workspace.toggle_modal(window, cx, |window, cx| {
157                RemoteServerProjects::new(create_new_window, fs, window, handle, cx)
158            })
159        });
160    });
161
162    cx.observe_new(DisconnectedOverlay::register).detach();
163}
164
165#[cfg(target_os = "windows")]
166pub fn add_wsl_distro(
167    fs: Arc<dyn project::Fs>,
168    connection_options: &remote::WslConnectionOptions,
169    cx: &App,
170) {
171    use gpui::ReadGlobal;
172    use settings::SettingsStore;
173
174    let distro_name = SharedString::from(&connection_options.distro_name);
175    let user = connection_options.user.clone();
176    SettingsStore::global(cx).update_settings_file(fs, move |setting, _| {
177        let connections = setting
178            .remote
179            .wsl_connections
180            .get_or_insert(Default::default());
181
182        if !connections
183            .iter()
184            .any(|conn| conn.distro_name == distro_name && conn.user == user)
185        {
186            use std::collections::BTreeSet;
187
188            connections.push(settings::WslConnection {
189                distro_name,
190                user,
191                projects: BTreeSet::new(),
192            })
193        }
194    });
195}
196
197pub struct RecentProjects {
198    pub picker: Entity<Picker<RecentProjectsDelegate>>,
199    rem_width: f32,
200    _subscription: Subscription,
201}
202
203impl ModalView for RecentProjects {}
204
205impl RecentProjects {
206    fn new(
207        delegate: RecentProjectsDelegate,
208        rem_width: f32,
209        window: &mut Window,
210        cx: &mut Context<Self>,
211    ) -> Self {
212        let picker = cx.new(|cx| {
213            // We want to use a list when we render paths, because the items can have different heights (multiple paths).
214            if delegate.render_paths {
215                Picker::list(delegate, window, cx)
216            } else {
217                Picker::uniform_list(delegate, window, cx)
218            }
219        });
220        let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
221        // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
222        // out workspace locations once the future runs to completion.
223        cx.spawn_in(window, async move |this, cx| {
224            let workspaces = WORKSPACE_DB
225                .recent_workspaces_on_disk()
226                .await
227                .log_err()
228                .unwrap_or_default();
229            this.update_in(cx, move |this, window, cx| {
230                this.picker.update(cx, move |picker, cx| {
231                    picker.delegate.set_workspaces(workspaces);
232                    picker.update_matches(picker.query(cx), window, cx)
233                })
234            })
235            .ok()
236        })
237        .detach();
238        Self {
239            picker,
240            rem_width,
241            _subscription,
242        }
243    }
244
245    pub fn open(
246        workspace: &mut Workspace,
247        create_new_window: bool,
248        window: &mut Window,
249        cx: &mut Context<Workspace>,
250    ) {
251        let weak = cx.entity().downgrade();
252        workspace.toggle_modal(window, cx, |window, cx| {
253            let delegate = RecentProjectsDelegate::new(weak, create_new_window, true);
254
255            Self::new(delegate, 34., window, cx)
256        })
257    }
258}
259
260impl EventEmitter<DismissEvent> for RecentProjects {}
261
262impl Focusable for RecentProjects {
263    fn focus_handle(&self, cx: &App) -> FocusHandle {
264        self.picker.focus_handle(cx)
265    }
266}
267
268impl Render for RecentProjects {
269    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
270        v_flex()
271            .key_context("RecentProjects")
272            .w(rems(self.rem_width))
273            .child(self.picker.clone())
274            .on_mouse_down_out(cx.listener(|this, _, window, cx| {
275                this.picker.update(cx, |this, cx| {
276                    this.cancel(&Default::default(), window, cx);
277                })
278            }))
279    }
280}
281
282pub struct RecentProjectsDelegate {
283    workspace: WeakEntity<Workspace>,
284    workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation, PathList)>,
285    selected_match_index: usize,
286    matches: Vec<StringMatch>,
287    render_paths: bool,
288    create_new_window: bool,
289    // Flag to reset index when there is a new query vs not reset index when user delete an item
290    reset_selected_match_index: bool,
291    has_any_non_local_projects: bool,
292}
293
294impl RecentProjectsDelegate {
295    fn new(workspace: WeakEntity<Workspace>, create_new_window: bool, render_paths: bool) -> Self {
296        Self {
297            workspace,
298            workspaces: Vec::new(),
299            selected_match_index: 0,
300            matches: Default::default(),
301            create_new_window,
302            render_paths,
303            reset_selected_match_index: true,
304            has_any_non_local_projects: false,
305        }
306    }
307
308    pub fn set_workspaces(
309        &mut self,
310        workspaces: Vec<(WorkspaceId, SerializedWorkspaceLocation, PathList)>,
311    ) {
312        self.workspaces = workspaces;
313        self.has_any_non_local_projects = !self
314            .workspaces
315            .iter()
316            .all(|(_, location, _)| matches!(location, SerializedWorkspaceLocation::Local));
317    }
318}
319impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
320impl PickerDelegate for RecentProjectsDelegate {
321    type ListItem = ListItem;
322
323    fn placeholder_text(&self, window: &mut Window, _: &mut App) -> Arc<str> {
324        let (create_window, reuse_window) = if self.create_new_window {
325            (
326                window.keystroke_text_for(&menu::Confirm),
327                window.keystroke_text_for(&menu::SecondaryConfirm),
328            )
329        } else {
330            (
331                window.keystroke_text_for(&menu::SecondaryConfirm),
332                window.keystroke_text_for(&menu::Confirm),
333            )
334        };
335        Arc::from(format!(
336            "{reuse_window} reuses this window, {create_window} opens a new one",
337        ))
338    }
339
340    fn match_count(&self) -> usize {
341        self.matches.len()
342    }
343
344    fn selected_index(&self) -> usize {
345        self.selected_match_index
346    }
347
348    fn set_selected_index(
349        &mut self,
350        ix: usize,
351        _window: &mut Window,
352        _cx: &mut Context<Picker<Self>>,
353    ) {
354        self.selected_match_index = ix;
355    }
356
357    fn update_matches(
358        &mut self,
359        query: String,
360        _: &mut Window,
361        cx: &mut Context<Picker<Self>>,
362    ) -> gpui::Task<()> {
363        let query = query.trim_start();
364        let smart_case = query.chars().any(|c| c.is_uppercase());
365        let candidates = self
366            .workspaces
367            .iter()
368            .enumerate()
369            .filter(|(_, (id, _, _))| !self.is_current_workspace(*id, cx))
370            .map(|(id, (_, _, paths))| {
371                let combined_string = paths
372                    .ordered_paths()
373                    .map(|path| path.compact().to_string_lossy().into_owned())
374                    .collect::<Vec<_>>()
375                    .join("");
376                StringMatchCandidate::new(id, &combined_string)
377            })
378            .collect::<Vec<_>>();
379        self.matches = smol::block_on(fuzzy::match_strings(
380            candidates.as_slice(),
381            query,
382            smart_case,
383            true,
384            100,
385            &Default::default(),
386            cx.background_executor().clone(),
387        ));
388        self.matches.sort_unstable_by(|a, b| {
389            b.score
390                .partial_cmp(&a.score) // Descending score
391                .unwrap_or(std::cmp::Ordering::Equal)
392                .then_with(|| a.candidate_id.cmp(&b.candidate_id)) // Ascending candidate_id for ties
393        });
394
395        if self.reset_selected_match_index {
396            self.selected_match_index = self
397                .matches
398                .iter()
399                .enumerate()
400                .rev()
401                .max_by_key(|(_, m)| OrderedFloat(m.score))
402                .map(|(ix, _)| ix)
403                .unwrap_or(0);
404        }
405        self.reset_selected_match_index = true;
406        Task::ready(())
407    }
408
409    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
410        if let Some((selected_match, workspace)) = self
411            .matches
412            .get(self.selected_index())
413            .zip(self.workspace.upgrade())
414        {
415            let (candidate_workspace_id, candidate_workspace_location, candidate_workspace_paths) =
416                &self.workspaces[selected_match.candidate_id];
417            let replace_current_window = if self.create_new_window {
418                secondary
419            } else {
420                !secondary
421            };
422            workspace.update(cx, |workspace, cx| {
423                if workspace.database_id() == Some(*candidate_workspace_id) {
424                    return;
425                }
426                match candidate_workspace_location.clone() {
427                    SerializedWorkspaceLocation::Local => {
428                        let paths = candidate_workspace_paths.paths().to_vec();
429                        if replace_current_window {
430                            cx.spawn_in(window, async move |workspace, cx| {
431                                let continue_replacing = workspace
432                                    .update_in(cx, |workspace, window, cx| {
433                                        workspace.prepare_to_close(
434                                            CloseIntent::ReplaceWindow,
435                                            window,
436                                            cx,
437                                        )
438                                    })?
439                                    .await?;
440                                if continue_replacing {
441                                    workspace
442                                        .update_in(cx, |workspace, window, cx| {
443                                            workspace
444                                                .open_workspace_for_paths(true, paths, window, cx)
445                                        })?
446                                        .await
447                                } else {
448                                    Ok(())
449                                }
450                            })
451                        } else {
452                            workspace.open_workspace_for_paths(false, paths, window, cx)
453                        }
454                    }
455                    SerializedWorkspaceLocation::Remote(mut connection) => {
456                        let app_state = workspace.app_state().clone();
457
458                        let replace_window = if replace_current_window {
459                            window.window_handle().downcast::<Workspace>()
460                        } else {
461                            None
462                        };
463
464                        let open_options = OpenOptions {
465                            replace_window,
466                            ..Default::default()
467                        };
468
469                        if let RemoteConnectionOptions::Ssh(connection) = &mut connection {
470                            SshSettings::get_global(cx)
471                                .fill_connection_options_from_settings(connection);
472                        };
473
474                        let paths = candidate_workspace_paths.paths().to_vec();
475
476                        cx.spawn_in(window, async move |_, cx| {
477                            open_remote_project(
478                                connection.clone(),
479                                paths,
480                                app_state,
481                                open_options,
482                                cx,
483                            )
484                            .await
485                        })
486                    }
487                }
488                .detach_and_prompt_err(
489                    "Failed to open project",
490                    window,
491                    cx,
492                    |_, _, _| None,
493                );
494            });
495            cx.emit(DismissEvent);
496        }
497    }
498
499    fn dismissed(&mut self, _window: &mut Window, _: &mut Context<Picker<Self>>) {}
500
501    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
502        let text = if self.workspaces.is_empty() {
503            "Recently opened projects will show up here".into()
504        } else {
505            "No matches".into()
506        };
507        Some(text)
508    }
509
510    fn render_match(
511        &self,
512        ix: usize,
513        selected: bool,
514        window: &mut Window,
515        cx: &mut Context<Picker<Self>>,
516    ) -> Option<Self::ListItem> {
517        let hit = self.matches.get(ix)?;
518
519        let (_, location, paths) = self.workspaces.get(hit.candidate_id)?;
520
521        let mut path_start_offset = 0;
522
523        let (match_labels, paths): (Vec<_>, Vec<_>) = paths
524            .ordered_paths()
525            .map(|p| p.compact())
526            .map(|path| {
527                let highlighted_text =
528                    highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
529                path_start_offset += highlighted_text.1.text.len();
530                highlighted_text
531            })
532            .unzip();
533
534        let prefix = match &location {
535            SerializedWorkspaceLocation::Remote(RemoteConnectionOptions::Wsl(wsl)) => {
536                Some(SharedString::from(&wsl.distro_name))
537            }
538            _ => None,
539        };
540
541        let highlighted_match = HighlightedMatchWithPaths {
542            prefix,
543            match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "),
544            paths,
545        };
546
547        let secondary_actions = h_flex()
548            .gap_px()
549            .child(
550                IconButton::new("open_new_window", IconName::ArrowUpRight)
551                    .icon_size(IconSize::XSmall)
552                    .tooltip(Tooltip::text("Open Project in New Window"))
553                    .on_click(cx.listener(move |this, _event, window, cx| {
554                        cx.stop_propagation();
555                        window.prevent_default();
556                        this.delegate.set_selected_index(ix, window, cx);
557                        this.delegate.confirm(true, window, cx);
558                    })),
559            )
560            .child(
561                IconButton::new("delete", IconName::Close)
562                    .icon_size(IconSize::Small)
563                    .tooltip(Tooltip::text("Delete from Recent Projects"))
564                    .on_click(cx.listener(move |this, _event, window, cx| {
565                        cx.stop_propagation();
566                        window.prevent_default();
567
568                        this.delegate.delete_recent_project(ix, window, cx)
569                    })),
570            )
571            .into_any_element();
572
573        Some(
574            ListItem::new(ix)
575                .toggle_state(selected)
576                .inset(true)
577                .spacing(ListItemSpacing::Sparse)
578                .child(
579                    h_flex()
580                        .flex_grow()
581                        .gap_3()
582                        .when(self.has_any_non_local_projects, |this| {
583                            this.child(match location {
584                                SerializedWorkspaceLocation::Local => Icon::new(IconName::Screen)
585                                    .color(Color::Muted)
586                                    .into_any_element(),
587                                SerializedWorkspaceLocation::Remote(options) => {
588                                    Icon::new(match options {
589                                        RemoteConnectionOptions::Ssh { .. } => IconName::Server,
590                                        RemoteConnectionOptions::Wsl { .. } => IconName::Linux,
591                                    })
592                                    .color(Color::Muted)
593                                    .into_any_element()
594                                }
595                            })
596                        })
597                        .child({
598                            let mut highlighted = highlighted_match.clone();
599                            if !self.render_paths {
600                                highlighted.paths.clear();
601                            }
602                            highlighted.render(window, cx)
603                        }),
604                )
605                .map(|el| {
606                    if self.selected_index() == ix {
607                        el.end_slot(secondary_actions)
608                    } else {
609                        el.end_hover_slot(secondary_actions)
610                    }
611                })
612                .tooltip(move |_, cx| {
613                    let tooltip_highlighted_location = highlighted_match.clone();
614                    cx.new(|_| MatchTooltip {
615                        highlighted_location: tooltip_highlighted_location,
616                    })
617                    .into()
618                }),
619        )
620    }
621
622    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
623        Some(
624            h_flex()
625                .w_full()
626                .p_2()
627                .gap_2()
628                .justify_end()
629                .border_t_1()
630                .border_color(cx.theme().colors().border_variant)
631                .child(
632                    Button::new("remote", "Open Remote Folder")
633                        .key_binding(KeyBinding::for_action(
634                            &OpenRemote {
635                                from_existing_connection: false,
636                                create_new_window: false,
637                            },
638                            cx,
639                        ))
640                        .on_click(|_, window, cx| {
641                            window.dispatch_action(
642                                OpenRemote {
643                                    from_existing_connection: false,
644                                    create_new_window: false,
645                                }
646                                .boxed_clone(),
647                                cx,
648                            )
649                        }),
650                )
651                .child(
652                    Button::new("local", "Open Local Folder")
653                        .key_binding(KeyBinding::for_action(&workspace::Open, cx))
654                        .on_click(|_, window, cx| {
655                            window.dispatch_action(workspace::Open.boxed_clone(), cx)
656                        }),
657                )
658                .into_any(),
659        )
660    }
661}
662
663// Compute the highlighted text for the name and path
664fn highlights_for_path(
665    path: &Path,
666    match_positions: &Vec<usize>,
667    path_start_offset: usize,
668) -> (Option<HighlightedMatch>, HighlightedMatch) {
669    let path_string = path.to_string_lossy();
670    let path_text = path_string.to_string();
671    let path_byte_len = path_text.len();
672    // Get the subset of match highlight positions that line up with the given path.
673    // Also adjusts them to start at the path start
674    let path_positions = match_positions
675        .iter()
676        .copied()
677        .skip_while(|position| *position < path_start_offset)
678        .take_while(|position| *position < path_start_offset + path_byte_len)
679        .map(|position| position - path_start_offset)
680        .collect::<Vec<_>>();
681
682    // Again subset the highlight positions to just those that line up with the file_name
683    // again adjusted to the start of the file_name
684    let file_name_text_and_positions = path.file_name().map(|file_name| {
685        let file_name_text = file_name.to_string_lossy().into_owned();
686        let file_name_start_byte = path_byte_len - file_name_text.len();
687        let highlight_positions = path_positions
688            .iter()
689            .copied()
690            .skip_while(|position| *position < file_name_start_byte)
691            .take_while(|position| *position < file_name_start_byte + file_name_text.len())
692            .map(|position| position - file_name_start_byte)
693            .collect::<Vec<_>>();
694        HighlightedMatch {
695            text: file_name_text,
696            highlight_positions,
697            color: Color::Default,
698        }
699    });
700
701    (
702        file_name_text_and_positions,
703        HighlightedMatch {
704            text: path_text,
705            highlight_positions: path_positions,
706            color: Color::Default,
707        },
708    )
709}
710impl RecentProjectsDelegate {
711    fn delete_recent_project(
712        &self,
713        ix: usize,
714        window: &mut Window,
715        cx: &mut Context<Picker<Self>>,
716    ) {
717        if let Some(selected_match) = self.matches.get(ix) {
718            let (workspace_id, _, _) = self.workspaces[selected_match.candidate_id];
719            cx.spawn_in(window, async move |this, cx| {
720                let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
721                let workspaces = WORKSPACE_DB
722                    .recent_workspaces_on_disk()
723                    .await
724                    .unwrap_or_default();
725                this.update_in(cx, move |picker, window, cx| {
726                    picker.delegate.set_workspaces(workspaces);
727                    picker
728                        .delegate
729                        .set_selected_index(ix.saturating_sub(1), window, cx);
730                    picker.delegate.reset_selected_match_index = false;
731                    picker.update_matches(picker.query(cx), window, cx);
732                    // After deleting a project, we want to update the history manager to reflect the change.
733                    // But we do not emit a update event when user opens a project, because it's handled in `workspace::load_workspace`.
734                    if let Some(history_manager) = HistoryManager::global(cx) {
735                        history_manager
736                            .update(cx, |this, cx| this.delete_history(workspace_id, cx));
737                    }
738                })
739            })
740            .detach();
741        }
742    }
743
744    fn is_current_workspace(
745        &self,
746        workspace_id: WorkspaceId,
747        cx: &mut Context<Picker<Self>>,
748    ) -> bool {
749        if let Some(workspace) = self.workspace.upgrade() {
750            let workspace = workspace.read(cx);
751            if Some(workspace_id) == workspace.database_id() {
752                return true;
753            }
754        }
755
756        false
757    }
758}
759struct MatchTooltip {
760    highlighted_location: HighlightedMatchWithPaths,
761}
762
763impl Render for MatchTooltip {
764    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
765        tooltip_container(cx, |div, _| {
766            self.highlighted_location.render_paths_children(div)
767        })
768    }
769}
770
771#[cfg(test)]
772mod tests {
773    use std::path::PathBuf;
774
775    use editor::Editor;
776    use gpui::{TestAppContext, UpdateGlobal, WindowHandle};
777
778    use serde_json::json;
779    use settings::SettingsStore;
780    use util::path;
781    use workspace::{AppState, open_paths};
782
783    use super::*;
784
785    #[gpui::test]
786    async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
787        let app_state = init_test(cx);
788
789        cx.update(|cx| {
790            SettingsStore::update_global(cx, |store, cx| {
791                store.update_user_settings(cx, |settings| {
792                    settings
793                        .session
794                        .get_or_insert_default()
795                        .restore_unsaved_buffers = Some(false)
796                });
797            });
798        });
799
800        app_state
801            .fs
802            .as_fake()
803            .insert_tree(
804                path!("/dir"),
805                json!({
806                    "main.ts": "a"
807                }),
808            )
809            .await;
810        cx.update(|cx| {
811            open_paths(
812                &[PathBuf::from(path!("/dir/main.ts"))],
813                app_state,
814                workspace::OpenOptions::default(),
815                cx,
816            )
817        })
818        .await
819        .unwrap();
820        assert_eq!(cx.update(|cx| cx.windows().len()), 1);
821
822        let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
823        workspace
824            .update(cx, |workspace, _, _| assert!(!workspace.is_edited()))
825            .unwrap();
826
827        let editor = workspace
828            .read_with(cx, |workspace, cx| {
829                workspace
830                    .active_item(cx)
831                    .unwrap()
832                    .downcast::<Editor>()
833                    .unwrap()
834            })
835            .unwrap();
836        workspace
837            .update(cx, |_, window, cx| {
838                editor.update(cx, |editor, cx| editor.insert("EDIT", window, cx));
839            })
840            .unwrap();
841        workspace
842            .update(cx, |workspace, _, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
843            .unwrap();
844
845        let recent_projects_picker = open_recent_projects(&workspace, cx);
846        workspace
847            .update(cx, |_, _, cx| {
848                recent_projects_picker.update(cx, |picker, cx| {
849                    assert_eq!(picker.query(cx), "");
850                    let delegate = &mut picker.delegate;
851                    delegate.matches = vec![StringMatch {
852                        candidate_id: 0,
853                        score: 1.0,
854                        positions: Vec::new(),
855                        string: "fake candidate".to_string(),
856                    }];
857                    delegate.set_workspaces(vec![(
858                        WorkspaceId::default(),
859                        SerializedWorkspaceLocation::Local,
860                        PathList::new(&[path!("/test/path")]),
861                    )]);
862                });
863            })
864            .unwrap();
865
866        assert!(
867            !cx.has_pending_prompt(),
868            "Should have no pending prompt on dirty project before opening the new recent project"
869        );
870        cx.dispatch_action(*workspace, menu::Confirm);
871        workspace
872            .update(cx, |workspace, _, cx| {
873                assert!(
874                    workspace.active_modal::<RecentProjects>(cx).is_none(),
875                    "Should remove the modal after selecting new recent project"
876                )
877            })
878            .unwrap();
879        assert!(
880            cx.has_pending_prompt(),
881            "Dirty workspace should prompt before opening the new recent project"
882        );
883        cx.simulate_prompt_answer("Cancel");
884        assert!(
885            !cx.has_pending_prompt(),
886            "Should have no pending prompt after cancelling"
887        );
888        workspace
889            .update(cx, |workspace, _, _| {
890                assert!(
891                    workspace.is_edited(),
892                    "Should be in the same dirty project after cancelling"
893                )
894            })
895            .unwrap();
896    }
897
898    fn open_recent_projects(
899        workspace: &WindowHandle<Workspace>,
900        cx: &mut TestAppContext,
901    ) -> Entity<Picker<RecentProjectsDelegate>> {
902        cx.dispatch_action(
903            (*workspace).into(),
904            OpenRecent {
905                create_new_window: false,
906            },
907        );
908        workspace
909            .update(cx, |workspace, _, cx| {
910                workspace
911                    .active_modal::<RecentProjects>(cx)
912                    .unwrap()
913                    .read(cx)
914                    .picker
915                    .clone()
916            })
917            .unwrap()
918    }
919
920    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
921        cx.update(|cx| {
922            let state = AppState::test(cx);
923            crate::init(cx);
924            editor::init(cx);
925            state
926        })
927    }
928}