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