recent_projects.rs

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