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