1mod dev_servers;
2pub mod disconnected_overlay;
3mod ssh_connections;
4use remote::SshConnectionOptions;
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 itertools::Itertools;
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;
25pub use 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 .zip(paths.paths().iter())
252 .sorted_by_key(|(i, _)| *i)
253 .map(|(_, path)| path.compact().to_string_lossy().into_owned())
254 .collect::<Vec<_>>()
255 .join(""),
256 SerializedWorkspaceLocation::DevServer(dev_server_project) => {
257 format!(
258 "{}{}",
259 dev_server_project.dev_server_name,
260 dev_server_project.paths.join("")
261 )
262 }
263 SerializedWorkspaceLocation::Ssh(ssh_project) => ssh_project
264 .ssh_urls()
265 .iter()
266 .map(|path| path.to_string_lossy().to_string())
267 .collect::<Vec<_>>()
268 .join(""),
269 };
270
271 StringMatchCandidate::new(id, combined_string)
272 })
273 .collect::<Vec<_>>();
274 self.matches = smol::block_on(fuzzy::match_strings(
275 candidates.as_slice(),
276 query,
277 smart_case,
278 100,
279 &Default::default(),
280 cx.background_executor().clone(),
281 ));
282 self.matches.sort_unstable_by_key(|m| m.candidate_id);
283
284 if self.reset_selected_match_index {
285 self.selected_match_index = self
286 .matches
287 .iter()
288 .enumerate()
289 .rev()
290 .max_by_key(|(_, m)| OrderedFloat(m.score))
291 .map(|(ix, _)| ix)
292 .unwrap_or(0);
293 }
294 self.reset_selected_match_index = true;
295 Task::ready(())
296 }
297
298 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
299 if let Some((selected_match, workspace)) = self
300 .matches
301 .get(self.selected_index())
302 .zip(self.workspace.upgrade())
303 {
304 let (candidate_workspace_id, candidate_workspace_location) =
305 &self.workspaces[selected_match.candidate_id];
306 let replace_current_window = if self.create_new_window {
307 secondary
308 } else {
309 !secondary
310 };
311 workspace
312 .update(cx, |workspace, cx| {
313 if workspace.database_id() == Some(*candidate_workspace_id) {
314 Task::ready(Ok(()))
315 } else {
316 match candidate_workspace_location {
317 SerializedWorkspaceLocation::Local(paths, _) => {
318 let paths = paths.paths().to_vec();
319 if replace_current_window {
320 cx.spawn(move |workspace, mut cx| async move {
321 let continue_replacing = workspace
322 .update(&mut cx, |workspace, cx| {
323 workspace.prepare_to_close(CloseIntent::ReplaceWindow, cx)
324 })?
325 .await?;
326 if continue_replacing {
327 workspace
328 .update(&mut cx, |workspace, cx| {
329 workspace
330 .open_workspace_for_paths(true, paths, cx)
331 })?
332 .await
333 } else {
334 Ok(())
335 }
336 })
337 } else {
338 workspace.open_workspace_for_paths(false, paths, cx)
339 }
340 }
341 SerializedWorkspaceLocation::DevServer(dev_server_project) => {
342 let store = dev_server_projects::Store::global(cx);
343 let Some(project_id) = store.read(cx)
344 .dev_server_project(dev_server_project.id)
345 .and_then(|p| p.project_id)
346 else {
347 let server = store.read(cx).dev_server_for_project(dev_server_project.id);
348 if server.is_some_and(|server| server.ssh_connection_string.is_some()) {
349 return reconnect_to_dev_server_project(cx.view().clone(), server.unwrap().clone(), dev_server_project.id, replace_current_window, cx);
350 } else {
351 let dev_server_name = dev_server_project.dev_server_name.clone();
352 return cx.spawn(|workspace, mut cx| async move {
353 let response =
354 cx.prompt(gpui::PromptLevel::Warning,
355 "Dev Server is offline",
356 Some(format!("Cannot connect to {}. To debug open the remote project settings.", dev_server_name).as_str()),
357 &["Ok", "Open Settings"]
358 ).await?;
359 if response == 1 {
360 workspace.update(&mut cx, |workspace, cx| {
361 let handle = cx.view().downgrade();
362 workspace.toggle_modal(cx, |cx| DevServerProjects::new(cx, handle))
363 })?;
364 } else {
365 workspace.update(&mut cx, |workspace, cx| {
366 RecentProjects::open(workspace, true, cx);
367 })?;
368 }
369 Ok(())
370 })
371 }
372 };
373 open_dev_server_project(replace_current_window, dev_server_project.id, project_id, cx)
374 }
375 SerializedWorkspaceLocation::Ssh(ssh_project) => {
376 let app_state = workspace.app_state().clone();
377
378 let replace_window = if replace_current_window {
379 cx.window_handle().downcast::<Workspace>()
380 } else {
381 None
382 };
383
384 let open_options = OpenOptions {
385 replace_window,
386 ..Default::default()
387 };
388
389 let args = SshSettings::get_global(cx).args_for(&ssh_project.host, ssh_project.port, &ssh_project.user);
390 let connection_options = SshConnectionOptions {
391 host: ssh_project.host.clone(),
392 username: ssh_project.user.clone(),
393 port: ssh_project.port,
394 password: None,
395 args,
396 };
397
398 let paths = ssh_project.paths.iter().map(PathBuf::from).collect();
399
400 cx.spawn(|_, mut cx| async move {
401 open_ssh_project(connection_options, paths, app_state, open_options, &mut cx).await
402 })
403 }
404 }
405 }
406 })
407 .detach_and_log_err(cx);
408 cx.emit(DismissEvent);
409 }
410 }
411
412 fn dismissed(&mut self, _: &mut ViewContext<Picker<Self>>) {}
413
414 fn no_matches_text(&self, _cx: &mut WindowContext) -> SharedString {
415 if self.workspaces.is_empty() {
416 "Recently opened projects will show up here".into()
417 } else {
418 "No matches".into()
419 }
420 }
421
422 fn render_match(
423 &self,
424 ix: usize,
425 selected: bool,
426 cx: &mut ViewContext<Picker<Self>>,
427 ) -> Option<Self::ListItem> {
428 let hit = self.matches.get(ix)?;
429
430 let (_, location) = self.workspaces.get(hit.candidate_id)?;
431
432 let dev_server_status =
433 if let SerializedWorkspaceLocation::DevServer(dev_server_project) = location {
434 let store = dev_server_projects::Store::global(cx).read(cx);
435 Some(
436 store
437 .dev_server_project(dev_server_project.id)
438 .and_then(|p| store.dev_server(p.dev_server_id))
439 .map(|s| s.status)
440 .unwrap_or_default(),
441 )
442 } else {
443 None
444 };
445
446 let mut path_start_offset = 0;
447 let paths = match location {
448 SerializedWorkspaceLocation::Local(paths, order) => Arc::new(
449 order
450 .order()
451 .iter()
452 .zip(paths.paths().iter())
453 .sorted_by_key(|(i, _)| **i)
454 .map(|(_, path)| path.compact())
455 .collect(),
456 ),
457 SerializedWorkspaceLocation::Ssh(ssh_project) => Arc::new(ssh_project.ssh_urls()),
458 SerializedWorkspaceLocation::DevServer(dev_server_project) => {
459 Arc::new(vec![PathBuf::from(format!(
460 "{}:{}",
461 dev_server_project.dev_server_name,
462 dev_server_project.paths.join(", ")
463 ))])
464 }
465 };
466
467 let (match_labels, paths): (Vec<_>, Vec<_>) = paths
468 .iter()
469 .map(|path| {
470 let highlighted_text =
471 highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
472
473 path_start_offset += highlighted_text.1.char_count;
474 highlighted_text
475 })
476 .unzip();
477
478 let highlighted_match = HighlightedMatchWithPaths {
479 match_label: HighlightedText::join(match_labels.into_iter().flatten(), ", ").color(
480 if matches!(dev_server_status, Some(DevServerStatus::Offline)) {
481 Color::Disabled
482 } else {
483 Color::Default
484 },
485 ),
486 paths,
487 };
488
489 Some(
490 ListItem::new(ix)
491 .selected(selected)
492 .inset(true)
493 .spacing(ListItemSpacing::Sparse)
494 .child(
495 h_flex()
496 .flex_grow()
497 .gap_3()
498 .when(self.has_any_non_local_projects, |this| {
499 this.child(match location {
500 SerializedWorkspaceLocation::Local(_, _) => {
501 Icon::new(IconName::Screen)
502 .color(Color::Muted)
503 .into_any_element()
504 }
505 SerializedWorkspaceLocation::Ssh(_) => Icon::new(IconName::Server)
506 .color(Color::Muted)
507 .into_any_element(),
508 SerializedWorkspaceLocation::DevServer(_) => {
509 let indicator_color = match dev_server_status {
510 Some(DevServerStatus::Online) => Color::Created,
511 Some(DevServerStatus::Offline) => Color::Hidden,
512 _ => unreachable!(),
513 };
514 IconWithIndicator::new(
515 Icon::new(IconName::Server).color(Color::Muted),
516 Some(Indicator::dot()),
517 )
518 .indicator_color(indicator_color)
519 .indicator_border_color(if selected {
520 Some(cx.theme().colors().element_selected)
521 } else {
522 None
523 })
524 .into_any_element()
525 }
526 })
527 })
528 .child({
529 let mut highlighted = highlighted_match.clone();
530 if !self.render_paths {
531 highlighted.paths.clear();
532 }
533 highlighted.render(cx)
534 }),
535 )
536 .map(|el| {
537 let delete_button = div()
538 .child(
539 IconButton::new("delete", IconName::Close)
540 .icon_size(IconSize::Small)
541 .on_click(cx.listener(move |this, _event, cx| {
542 cx.stop_propagation();
543 cx.prevent_default();
544
545 this.delegate.delete_recent_project(ix, cx)
546 }))
547 .tooltip(|cx| Tooltip::text("Delete from Recent Projects...", cx)),
548 )
549 .into_any_element();
550
551 if self.selected_index() == ix {
552 el.end_slot::<AnyElement>(delete_button)
553 } else {
554 el.end_hover_slot::<AnyElement>(delete_button)
555 }
556 })
557 .tooltip(move |cx| {
558 let tooltip_highlighted_location = highlighted_match.clone();
559 cx.new_view(move |_| MatchTooltip {
560 highlighted_location: tooltip_highlighted_location,
561 })
562 .into()
563 }),
564 )
565 }
566
567 fn render_footer(&self, cx: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
568 Some(
569 h_flex()
570 .border_t_1()
571 .py_2()
572 .pr_2()
573 .border_color(cx.theme().colors().border_variant)
574 .justify_end()
575 .gap_4()
576 .child(
577 ButtonLike::new("remote")
578 .when_some(KeyBinding::for_action(&OpenRemote, cx), |button, key| {
579 button.child(key)
580 })
581 .child(Label::new("Open Remote Folder…").color(Color::Muted))
582 .on_click(|_, cx| cx.dispatch_action(OpenRemote.boxed_clone())),
583 )
584 .child(
585 ButtonLike::new("local")
586 .when_some(
587 KeyBinding::for_action(&workspace::Open, cx),
588 |button, key| button.child(key),
589 )
590 .child(Label::new("Open Local Folder…").color(Color::Muted))
591 .on_click(|_, cx| cx.dispatch_action(workspace::Open.boxed_clone())),
592 )
593 .into_any(),
594 )
595 }
596}
597
598fn open_dev_server_project(
599 replace_current_window: bool,
600 dev_server_project_id: DevServerProjectId,
601 project_id: ProjectId,
602 cx: &mut ViewContext<Workspace>,
603) -> Task<anyhow::Result<()>> {
604 if let Some(app_state) = AppState::global(cx).upgrade() {
605 let handle = if replace_current_window {
606 cx.window_handle().downcast::<Workspace>()
607 } else {
608 None
609 };
610
611 if let Some(handle) = handle {
612 cx.spawn(move |workspace, mut cx| async move {
613 let continue_replacing = workspace
614 .update(&mut cx, |workspace, cx| {
615 workspace.prepare_to_close(CloseIntent::ReplaceWindow, cx)
616 })?
617 .await?;
618 if continue_replacing {
619 workspace
620 .update(&mut cx, |_workspace, cx| {
621 workspace::join_dev_server_project(
622 dev_server_project_id,
623 project_id,
624 app_state,
625 Some(handle),
626 cx,
627 )
628 })?
629 .await?;
630 }
631 Ok(())
632 })
633 } else {
634 let task = workspace::join_dev_server_project(
635 dev_server_project_id,
636 project_id,
637 app_state,
638 None,
639 cx,
640 );
641 cx.spawn(|_, _| async move {
642 task.await?;
643 Ok(())
644 })
645 }
646 } else {
647 Task::ready(Err(anyhow::anyhow!("App state not found")))
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<HighlightedText>, HighlightedText) {
657 let path_string = path.to_string_lossy();
658 let path_char_count = path_string.chars().count();
659 // Get the subset of match highlight positions that line up with the given path.
660 // Also adjusts them to start at the path start
661 let path_positions = match_positions
662 .iter()
663 .copied()
664 .skip_while(|position| *position < path_start_offset)
665 .take_while(|position| *position < path_start_offset + path_char_count)
666 .map(|position| position - path_start_offset)
667 .collect::<Vec<_>>();
668
669 // Again subset the highlight positions to just those that line up with the file_name
670 // again adjusted to the start of the file_name
671 let file_name_text_and_positions = path.file_name().map(|file_name| {
672 let text = file_name.to_string_lossy();
673 let char_count = text.chars().count();
674 let file_name_start = path_char_count - char_count;
675 let highlight_positions = path_positions
676 .iter()
677 .copied()
678 .skip_while(|position| *position < file_name_start)
679 .take_while(|position| *position < file_name_start + char_count)
680 .map(|position| position - file_name_start)
681 .collect::<Vec<_>>();
682 HighlightedText {
683 text: text.to_string(),
684 highlight_positions,
685 char_count,
686 color: Color::Default,
687 }
688 });
689
690 (
691 file_name_text_and_positions,
692 HighlightedText {
693 text: path_string.to_string(),
694 highlight_positions: path_positions,
695 char_count: path_char_count,
696 color: Color::Default,
697 },
698 )
699}
700impl RecentProjectsDelegate {
701 fn delete_recent_project(&self, ix: usize, cx: &mut ViewContext<Picker<Self>>) {
702 if let Some(selected_match) = self.matches.get(ix) {
703 let (workspace_id, _) = self.workspaces[selected_match.candidate_id];
704 cx.spawn(move |this, mut cx| async move {
705 let _ = WORKSPACE_DB.delete_workspace_by_id(workspace_id).await;
706 let workspaces = WORKSPACE_DB
707 .recent_workspaces_on_disk()
708 .await
709 .unwrap_or_default();
710 this.update(&mut cx, move |picker, cx| {
711 picker.delegate.set_workspaces(workspaces);
712 picker.delegate.set_selected_index(ix.saturating_sub(1), cx);
713 picker.delegate.reset_selected_match_index = false;
714 picker.update_matches(picker.query(cx), cx)
715 })
716 })
717 .detach();
718 }
719 }
720
721 fn is_current_workspace(
722 &self,
723 workspace_id: WorkspaceId,
724 cx: &mut ViewContext<Picker<Self>>,
725 ) -> bool {
726 if let Some(workspace) = self.workspace.upgrade() {
727 let workspace = workspace.read(cx);
728 if Some(workspace_id) == workspace.database_id() {
729 return true;
730 }
731 }
732
733 false
734 }
735}
736struct MatchTooltip {
737 highlighted_location: HighlightedMatchWithPaths,
738}
739
740impl Render for MatchTooltip {
741 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
742 tooltip_container(cx, |div, _| {
743 self.highlighted_location.render_paths_children(div)
744 })
745 }
746}
747
748#[cfg(test)]
749mod tests {
750 use std::path::PathBuf;
751
752 use editor::Editor;
753 use gpui::{TestAppContext, UpdateGlobal, WindowHandle};
754 use project::{project_settings::ProjectSettings, Project};
755 use serde_json::json;
756 use settings::SettingsStore;
757 use workspace::{open_paths, AppState};
758
759 use super::*;
760
761 #[gpui::test]
762 async fn test_prompts_on_dirty_before_submit(cx: &mut TestAppContext) {
763 let app_state = init_test(cx);
764
765 cx.update(|cx| {
766 SettingsStore::update_global(cx, |store, cx| {
767 store.update_user_settings::<ProjectSettings>(cx, |settings| {
768 settings.session.restore_unsaved_buffers = false
769 });
770 });
771 });
772
773 app_state
774 .fs
775 .as_fake()
776 .insert_tree(
777 "/dir",
778 json!({
779 "main.ts": "a"
780 }),
781 )
782 .await;
783 cx.update(|cx| {
784 open_paths(
785 &[PathBuf::from("/dir/main.ts")],
786 app_state,
787 workspace::OpenOptions::default(),
788 cx,
789 )
790 })
791 .await
792 .unwrap();
793 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
794
795 let workspace = cx.update(|cx| cx.windows()[0].downcast::<Workspace>().unwrap());
796 workspace
797 .update(cx, |workspace, _| assert!(!workspace.is_edited()))
798 .unwrap();
799
800 let editor = workspace
801 .read_with(cx, |workspace, cx| {
802 workspace
803 .active_item(cx)
804 .unwrap()
805 .downcast::<Editor>()
806 .unwrap()
807 })
808 .unwrap();
809 workspace
810 .update(cx, |_, cx| {
811 editor.update(cx, |editor, cx| editor.insert("EDIT", cx));
812 })
813 .unwrap();
814 workspace
815 .update(cx, |workspace, _| assert!(workspace.is_edited(), "After inserting more text into the editor without saving, we should have a dirty project"))
816 .unwrap();
817
818 let recent_projects_picker = open_recent_projects(&workspace, cx);
819 workspace
820 .update(cx, |_, cx| {
821 recent_projects_picker.update(cx, |picker, cx| {
822 assert_eq!(picker.query(cx), "");
823 let delegate = &mut picker.delegate;
824 delegate.matches = vec![StringMatch {
825 candidate_id: 0,
826 score: 1.0,
827 positions: Vec::new(),
828 string: "fake candidate".to_string(),
829 }];
830 delegate.set_workspaces(vec![(
831 WorkspaceId::default(),
832 SerializedWorkspaceLocation::from_local_paths(vec!["/test/path/"]),
833 )]);
834 });
835 })
836 .unwrap();
837
838 assert!(
839 !cx.has_pending_prompt(),
840 "Should have no pending prompt on dirty project before opening the new recent project"
841 );
842 cx.dispatch_action(*workspace, menu::Confirm);
843 workspace
844 .update(cx, |workspace, cx| {
845 assert!(
846 workspace.active_modal::<RecentProjects>(cx).is_none(),
847 "Should remove the modal after selecting new recent project"
848 )
849 })
850 .unwrap();
851 assert!(
852 cx.has_pending_prompt(),
853 "Dirty workspace should prompt before opening the new recent project"
854 );
855 // Cancel
856 cx.simulate_prompt_answer(0);
857 assert!(
858 !cx.has_pending_prompt(),
859 "Should have no pending prompt after cancelling"
860 );
861 workspace
862 .update(cx, |workspace, _| {
863 assert!(
864 workspace.is_edited(),
865 "Should be in the same dirty project after cancelling"
866 )
867 })
868 .unwrap();
869 }
870
871 fn open_recent_projects(
872 workspace: &WindowHandle<Workspace>,
873 cx: &mut TestAppContext,
874 ) -> View<Picker<RecentProjectsDelegate>> {
875 cx.dispatch_action(
876 (*workspace).into(),
877 OpenRecent {
878 create_new_window: false,
879 },
880 );
881 workspace
882 .update(cx, |workspace, cx| {
883 workspace
884 .active_modal::<RecentProjects>(cx)
885 .unwrap()
886 .read(cx)
887 .picker
888 .clone()
889 })
890 .unwrap()
891 }
892
893 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
894 cx.update(|cx| {
895 let state = AppState::test(cx);
896 language::init(cx);
897 crate::init(cx);
898 editor::init(cx);
899 workspace::init_settings(cx);
900 Project::init_settings(cx);
901 state
902 })
903 }
904}