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                                                workspace.toggle_modal(cx, |cx| DevServerProjects::new(cx))
332                                            })?;
333                                        } else {
334                                            workspace.update(&mut cx, |workspace, cx| {
335                                                RecentProjects::open(workspace, true, cx);
336                                            })?;
337                                        }
338                                        Ok(())
339                                    })
340                                };
341                                if let Some(app_state) = AppState::global(cx).upgrade() {
342                                    let handle = if replace_current_window {
343                                        cx.window_handle().downcast::<Workspace>()
344                                    } else {
345                                        None
346                                    };
347
348                                    if let Some(handle) = handle {
349                                            cx.spawn(move |workspace, mut cx| async move {
350                                                let continue_replacing = workspace
351                                                    .update(&mut cx, |workspace, cx| {
352                                                        workspace.
353                                                            prepare_to_close(true, cx)
354                                                    })?
355                                                    .await?;
356                                                if continue_replacing {
357                                                    workspace
358                                                        .update(&mut cx, |_workspace, cx| {
359                                                            workspace::join_dev_server_project(project_id, app_state, Some(handle), cx)
360                                                        })?
361                                                        .await?;
362                                                }
363                                                Ok(())
364                                            })
365                                        }
366                                    else {
367                                        let task =
368                                            workspace::join_dev_server_project(project_id, app_state, None, cx);
369                                        cx.spawn(|_, _| async move {
370                                            task.await?;
371                                            Ok(())
372                                        })
373                                    }
374                                } else {
375                                    Task::ready(Err(anyhow::anyhow!("App state not found")))
376                                }
377                            }
378                        }
379                    }
380                })
381                .detach_and_log_err(cx);
382            cx.emit(DismissEvent);
383        }
384    }
385
386    fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
387
388    fn no_matches_text(&self, _cx: &mut WindowContext) -> SharedString {
389        if self.workspaces.is_empty() {
390            "Recently opened projects will show up here".into()
391        } else {
392            "No matches".into()
393        }
394    }
395
396    fn render_match(
397        &self,
398        ix: usize,
399        selected: bool,
400        cx: &mut ViewContext<Picker<Self>>,
401    ) -> Option<Self::ListItem> {
402        let Some(hit) = self.matches.get(ix) else {
403            return None;
404        };
405
406        let (workspace_id, location) = &self.workspaces[hit.candidate_id];
407        let is_current_workspace = self.is_current_workspace(*workspace_id, cx);
408
409        let is_remote = matches!(location, SerializedWorkspaceLocation::DevServer(_));
410        let dev_server_status =
411            if let SerializedWorkspaceLocation::DevServer(dev_server_project) = location {
412                let store = dev_server_projects::Store::global(cx).read(cx);
413                Some(
414                    store
415                        .dev_server_project(dev_server_project.id)
416                        .and_then(|p| store.dev_server(p.dev_server_id))
417                        .map(|s| s.status)
418                        .unwrap_or_default(),
419                )
420            } else {
421                None
422            };
423
424        let mut path_start_offset = 0;
425        let paths = match location {
426            SerializedWorkspaceLocation::Local(paths) => paths.paths(),
427            SerializedWorkspaceLocation::DevServer(dev_server_project) => {
428                Arc::new(vec![PathBuf::from(format!(
429                    "{}:{}",
430                    dev_server_project.dev_server_name, dev_server_project.path
431                ))])
432            }
433        };
434
435        let (match_labels, paths): (Vec<_>, Vec<_>) = paths
436            .iter()
437            .map(|path| {
438                let path = path.compact();
439                let highlighted_text =
440                    highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
441
442                path_start_offset += highlighted_text.1.char_count;
443                highlighted_text
444            })
445            .unzip();
446
447        let highlighted_match = HighlightedMatchWithPaths {
448            match_label: HighlightedText::join(match_labels.into_iter().flatten(), ", ").color(
449                if matches!(dev_server_status, Some(DevServerStatus::Offline)) {
450                    Color::Disabled
451                } else {
452                    Color::Default
453                },
454            ),
455            paths,
456        };
457
458        Some(
459            ListItem::new(ix)
460                .selected(selected)
461                .inset(true)
462                .spacing(ListItemSpacing::Sparse)
463                .child(
464                    h_flex()
465                        .flex_grow()
466                        .gap_3()
467                        .when(self.has_any_dev_server_projects, |this| {
468                            this.child(if is_remote {
469                                // if disabled, Color::Disabled
470                                let indicator_color = match dev_server_status {
471                                    Some(DevServerStatus::Online) => Color::Created,
472                                    Some(DevServerStatus::Offline) => Color::Hidden,
473                                    _ => unreachable!(),
474                                };
475                                IconWithIndicator::new(
476                                    Icon::new(IconName::Server).color(Color::Muted),
477                                    Some(Indicator::dot()),
478                                )
479                                .indicator_color(indicator_color)
480                                .indicator_border_color(if selected {
481                                    Some(cx.theme().colors().element_selected)
482                                } else {
483                                    None
484                                })
485                                .into_any_element()
486                            } else {
487                                Icon::new(IconName::Screen)
488                                    .color(Color::Muted)
489                                    .into_any_element()
490                            })
491                        })
492                        .child({
493                            let mut highlighted = highlighted_match.clone();
494                            if !self.render_paths {
495                                highlighted.paths.clear();
496                            }
497                            highlighted.render(cx)
498                        }),
499                )
500                .when(!is_current_workspace, |el| {
501                    let delete_button = div()
502                        .child(
503                            IconButton::new("delete", IconName::Close)
504                                .icon_size(IconSize::Small)
505                                .on_click(cx.listener(move |this, _event, cx| {
506                                    cx.stop_propagation();
507                                    cx.prevent_default();
508
509                                    this.delegate.delete_recent_project(ix, cx)
510                                }))
511                                .tooltip(|cx| Tooltip::text("Delete from Recent Projects...", cx)),
512                        )
513                        .into_any_element();
514
515                    if self.selected_index() == ix {
516                        el.end_slot::<AnyElement>(delete_button)
517                    } else {
518                        el.end_hover_slot::<AnyElement>(delete_button)
519                    }
520                })
521                .tooltip(move |cx| {
522                    let tooltip_highlighted_location = highlighted_match.clone();
523                    cx.new_view(move |_| MatchTooltip {
524                        highlighted_location: tooltip_highlighted_location,
525                    })
526                    .into()
527                }),
528        )
529    }
530
531    fn render_footer(&self, cx: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
532        if !cx.has_flag::<feature_flags::Remoting>() {
533            return None;
534        }
535        Some(
536            h_flex()
537                .border_t_1()
538                .py_2()
539                .pr_2()
540                .border_color(cx.theme().colors().border)
541                .justify_end()
542                .gap_4()
543                .child(
544                    ButtonLike::new("remote")
545                        .when_some(KeyBinding::for_action(&OpenRemote, cx), |button, key| {
546                            button.child(key)
547                        })
548                        .child(Label::new("Connect…").color(Color::Muted))
549                        .on_click(|_, cx| cx.dispatch_action(OpenRemote.boxed_clone())),
550                )
551                .child(
552                    ButtonLike::new("local")
553                        .when_some(
554                            KeyBinding::for_action(&workspace::Open, cx),
555                            |button, key| button.child(key),
556                        )
557                        .child(Label::new("Open folder…").color(Color::Muted))
558                        .on_click(|_, cx| cx.dispatch_action(workspace::Open.boxed_clone())),
559                )
560                .into_any(),
561        )
562    }
563}
564
565// Compute the highlighted text for the name and path
566fn highlights_for_path(
567    path: &Path,
568    match_positions: &Vec<usize>,
569    path_start_offset: usize,
570) -> (Option<HighlightedText>, HighlightedText) {
571    let path_string = path.to_string_lossy();
572    let path_char_count = path_string.chars().count();
573    // Get the subset of match highlight positions that line up with the given path.
574    // Also adjusts them to start at the path start
575    let path_positions = match_positions
576        .iter()
577        .copied()
578        .skip_while(|position| *position < path_start_offset)
579        .take_while(|position| *position < path_start_offset + path_char_count)
580        .map(|position| position - path_start_offset)
581        .collect::<Vec<_>>();
582
583    // Again subset the highlight positions to just those that line up with the file_name
584    // again adjusted to the start of the file_name
585    let file_name_text_and_positions = path.file_name().map(|file_name| {
586        let text = file_name.to_string_lossy();
587        let char_count = text.chars().count();
588        let file_name_start = path_char_count - char_count;
589        let highlight_positions = path_positions
590            .iter()
591            .copied()
592            .skip_while(|position| *position < file_name_start)
593            .take_while(|position| *position < file_name_start + char_count)
594            .map(|position| position - file_name_start)
595            .collect::<Vec<_>>();
596        HighlightedText {
597            text: text.to_string(),
598            highlight_positions,
599            char_count,
600            color: Color::Default,
601        }
602    });
603
604    (
605        file_name_text_and_positions,
606        HighlightedText {
607            text: path_string.to_string(),
608            highlight_positions: path_positions,
609            char_count: path_char_count,
610            color: Color::Default,
611        },
612    )
613}
614
615impl RecentProjectsDelegate {
616    fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
617        if let Some(selected_match) = self.matches.get(ix) {
618            let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
619            cx.spawn(move |this, mut cx| async move {
620                let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
621                let workspaces = WORKSPACE_DB
622                    .recent_workspaces_on_disk()
623                    .await
624                    .unwrap_or_default();
625                this.update(&mut cx, move |picker, cx| {
626                    picker.delegate.set_workspaces(workspaces);
627                    picker.delegate.set_selected_index(ix - 1, cx);
628                    picker.delegate.reset_selected_match_index = false;
629                    picker.update_matches(picker.query(cx), cx)
630                })
631            })
632            .detach();
633        }
634    }
635
636    fn is_current_workspace(
637        &self,
638        workspace_id: WorkspaceId,
639        cx: &mut ViewContext<Picker<Self>>,
640    ) -> bool {
641        if let Some(workspace) = self.workspace.upgrade() {
642            let workspace = workspace.read(cx);
643            if workspace_id == workspace.database_id() {
644                return true;
645            }
646        }
647
648        false
649    }
650}
651struct MatchTooltip {
652    highlighted_location: HighlightedMatchWithPaths,
653}
654
655impl Render for MatchTooltip {
656    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
657        tooltip_container(cx, |div, _| {
658            self.highlighted_location.render_paths_children(div)
659        })
660    }
661}
662
663#[cfg(test)]
664mod tests {
665    use std::path::PathBuf;
666
667    use editor::Editor;
668    use gpui::{TestAppContext, WindowHandle};
669    use project::Project;
670    use serde_json::json;
671    use workspace::{open_paths, AppState, LocalPaths};
672
673    use super::*;
674
675    #[gpui::test]
676    async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
677        let app_state = init_test(cx);
678        app_state
679            .fs
680            .as_fake()
681            .insert_tree(
682                "/dir",
683                json!({
684                    "main.ts": "a"
685                }),
686            )
687            .await;
688        cx.update(|cx| {
689            open_paths(
690                &[PathBuf::from("/dir/main.ts")],
691                app_state,
692                workspace::OpenOptions::default(),
693                cx,
694            )
695        })
696        .await
697        .unwrap();
698        assert_eq!(cx.update(|cx| cx.windows().len()), 1);
699
700        let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
701        workspace
702            .update(cx, |workspace, _| assert!(!workspace.is_edited()))
703            .unwrap();
704
705        let editor = workspace
706            .read_with(cx, |workspace, cx| {
707                workspace
708                    .active_item(cx)
709                    .unwrap()
710                    .downcast::<Editor>()
711                    .unwrap()
712            })
713            .unwrap();
714        workspace
715            .update(cx, |_, cx| {
716                editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
717            })
718            .unwrap();
719        workspace
720            .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
721            .unwrap();
722
723        let recent_projects_picker = open_recent_projects(&workspace, cx);
724        workspace
725            .update(cx, |_, cx| {
726                recent_projects_picker.update(cx, |picker, cx| {
727                    assert_eq!(picker.query(cx), "");
728                    let delegate = &mut picker.delegate;
729                    delegate.matches = vec![StringMatch {
730                        candidate_id: 0,
731                        score: 1.0,
732                        positions: Vec::new(),
733                        string: "fake candidate".to_string(),
734                    }];
735                    delegate.set_workspaces(vec![(
736                        WorkspaceId::default(),
737                        LocalPaths::new(vec!["/test/path/"]).into(),
738                    )]);
739                });
740            })
741            .unwrap();
742
743        assert!(
744            !cx.has_pending_prompt(),
745            "Should have no pending prompt on dirty project before opening the new recent project"
746        );
747        cx.dispatch_action(*workspace, menu::Confirm);
748        workspace
749            .update(cx, |workspace, cx| {
750                assert!(
751                    workspace.active_modal::<RecentProjects>(cx).is_none(),
752                    "Should remove the modal after selecting new recent project"
753                )
754            })
755            .unwrap();
756        assert!(
757            cx.has_pending_prompt(),
758            "Dirty workspace should prompt before opening the new recent project"
759        );
760        // Cancel
761        cx.simulate_prompt_answer(0);
762        assert!(
763            !cx.has_pending_prompt(),
764            "Should have no pending prompt after cancelling"
765        );
766        workspace
767            .update(cx, |workspace, _| {
768                assert!(
769                    workspace.is_edited(),
770                    "Should be in the same dirty project after cancelling"
771                )
772            })
773            .unwrap();
774    }
775
776    fn open_recent_projects(
777        workspace: &WindowHandle<Workspace>,
778        cx: &mut TestAppContext,
779    ) -> View<Picker<RecentProjectsDelegate>> {
780        cx.dispatch_action(
781            (*workspace).into(),
782            OpenRecent {
783                create_new_window: false,
784            },
785        );
786        workspace
787            .update(cx, |workspace, cx| {
788                workspace
789                    .active_modal::<RecentProjects>(cx)
790                    .unwrap()
791                    .read(cx)
792                    .picker
793                    .clone()
794            })
795            .unwrap()
796    }
797
798    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
799        cx.update(|cx| {
800            let state = AppState::test(cx);
801            language::init(cx);
802            crate::init(cx);
803            editor::init(cx);
804            workspace::init_settings(cx);
805            Project::init_settings(cx);
806            state
807        })
808    }
809}