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