recent_projects.rs

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