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