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