recent_projects.rs

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