1mod dev_container_suggest;
2pub mod disconnected_overlay;
3mod remote_connections;
4mod remote_servers;
5pub mod sidebar_recent_projects;
6mod ssh_config;
7
8use std::{
9 collections::HashSet,
10 path::{Path, PathBuf},
11 sync::Arc,
12};
13
14use chrono::{DateTime, Utc};
15
16use fs::Fs;
17
18#[cfg(target_os = "windows")]
19mod wsl_picker;
20
21use remote::RemoteConnectionOptions;
22pub use remote_connection::{RemoteConnectionModal, connect};
23pub use remote_connections::{navigate_to_positions, open_remote_project};
24
25use disconnected_overlay::DisconnectedOverlay;
26use fuzzy::{StringMatch, StringMatchCandidate};
27use gpui::{
28 Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
29 Subscription, Task, WeakEntity, Window, actions, px,
30};
31
32use picker::{
33 Picker, PickerDelegate,
34 highlighted_match_with_paths::{HighlightedMatch, HighlightedMatchWithPaths},
35};
36use project::{Worktree, git_store::Repository};
37pub use remote_connections::RemoteSettings;
38pub use remote_servers::RemoteServerProjects;
39use settings::{Settings, WorktreeId};
40use ui_input::ErasedEditor;
41
42use dev_container::{DevContainerContext, find_devcontainer_configs};
43use ui::{
44 ContextMenu, Divider, KeyBinding, ListItem, ListItemSpacing, ListSubHeader, PopoverMenu,
45 PopoverMenuHandle, TintColor, Tooltip, prelude::*,
46};
47use util::{ResultExt, paths::PathExt};
48use workspace::{
49 HistoryManager, ModalView, MultiWorkspace, OpenMode, OpenOptions, OpenVisible, PathList,
50 SerializedWorkspaceLocation, Workspace, WorkspaceDb, WorkspaceId,
51 notifications::DetachAndPromptErr, with_active_or_new_workspace,
52};
53use zed_actions::{OpenDevContainer, OpenRecent, OpenRemote};
54
55actions!(
56 recent_projects,
57 [ToggleActionsMenu, RemoveSelected, AddToWorkspace,]
58);
59
60#[derive(Clone, Debug)]
61pub struct RecentProjectEntry {
62 pub name: SharedString,
63 pub full_path: SharedString,
64 pub paths: Vec<PathBuf>,
65 pub workspace_id: WorkspaceId,
66 pub timestamp: DateTime<Utc>,
67}
68
69#[derive(Clone, Debug)]
70struct OpenFolderEntry {
71 worktree_id: WorktreeId,
72 name: SharedString,
73 path: PathBuf,
74 branch: Option<SharedString>,
75 is_active: bool,
76}
77
78#[derive(Clone, Debug)]
79enum ProjectPickerEntry {
80 Header(SharedString),
81 OpenFolder { index: usize, positions: Vec<usize> },
82 OpenProject(StringMatch),
83 RecentProject(StringMatch),
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87enum ProjectPickerStyle {
88 Modal,
89 Popover,
90}
91
92pub async fn get_recent_projects(
93 current_workspace_id: Option<WorkspaceId>,
94 limit: Option<usize>,
95 fs: Arc<dyn fs::Fs>,
96 db: &WorkspaceDb,
97) -> Vec<RecentProjectEntry> {
98 let workspaces = db
99 .recent_workspaces_on_disk(fs.as_ref())
100 .await
101 .unwrap_or_default();
102
103 let entries: Vec<RecentProjectEntry> = workspaces
104 .into_iter()
105 .filter(|(id, _, _, _)| Some(*id) != current_workspace_id)
106 .filter(|(_, location, _, _)| matches!(location, SerializedWorkspaceLocation::Local))
107 .map(|(workspace_id, _, path_list, timestamp)| {
108 let paths: Vec<PathBuf> = path_list.paths().to_vec();
109 let ordered_paths: Vec<&PathBuf> = path_list.ordered_paths().collect();
110
111 let name = if ordered_paths.len() == 1 {
112 ordered_paths[0]
113 .file_name()
114 .map(|n| n.to_string_lossy().to_string())
115 .unwrap_or_else(|| ordered_paths[0].to_string_lossy().to_string())
116 } else {
117 ordered_paths
118 .iter()
119 .filter_map(|p| p.file_name())
120 .map(|n| n.to_string_lossy().to_string())
121 .collect::<Vec<_>>()
122 .join(", ")
123 };
124
125 let full_path = ordered_paths
126 .iter()
127 .map(|p| p.to_string_lossy().to_string())
128 .collect::<Vec<_>>()
129 .join("\n");
130
131 RecentProjectEntry {
132 name: SharedString::from(name),
133 full_path: SharedString::from(full_path),
134 paths,
135 workspace_id,
136 timestamp,
137 }
138 })
139 .collect();
140
141 match limit {
142 Some(n) => entries.into_iter().take(n).collect(),
143 None => entries,
144 }
145}
146
147pub async fn delete_recent_project(workspace_id: WorkspaceId, db: &WorkspaceDb) {
148 let _ = db.delete_workspace_by_id(workspace_id).await;
149}
150
151fn get_open_folders(workspace: &Workspace, cx: &App) -> Vec<OpenFolderEntry> {
152 let project = workspace.project().read(cx);
153 let visible_worktrees: Vec<_> = project.visible_worktrees(cx).collect();
154
155 if visible_worktrees.len() <= 1 {
156 return Vec::new();
157 }
158
159 let active_worktree_id = workspace.active_worktree_override().or_else(|| {
160 if let Some(repo) = project.active_repository(cx) {
161 let repo = repo.read(cx);
162 let repo_path = &repo.work_directory_abs_path;
163 for worktree in project.visible_worktrees(cx) {
164 let worktree_path = worktree.read(cx).abs_path();
165 if worktree_path == *repo_path || worktree_path.starts_with(repo_path.as_ref()) {
166 return Some(worktree.read(cx).id());
167 }
168 }
169 }
170 project
171 .visible_worktrees(cx)
172 .next()
173 .map(|wt| wt.read(cx).id())
174 });
175
176 let git_store = project.git_store().read(cx);
177 let repositories: Vec<_> = git_store.repositories().values().cloned().collect();
178
179 let mut entries: Vec<OpenFolderEntry> = visible_worktrees
180 .into_iter()
181 .map(|worktree| {
182 let worktree_ref = worktree.read(cx);
183 let worktree_id = worktree_ref.id();
184 let name = SharedString::from(worktree_ref.root_name().as_unix_str().to_string());
185 let path = worktree_ref.abs_path().to_path_buf();
186 let branch = get_branch_for_worktree(worktree_ref, &repositories, cx);
187 let is_active = active_worktree_id == Some(worktree_id);
188 OpenFolderEntry {
189 worktree_id,
190 name,
191 path,
192 branch,
193 is_active,
194 }
195 })
196 .collect();
197
198 entries.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
199 entries
200}
201
202fn get_branch_for_worktree(
203 worktree: &Worktree,
204 repositories: &[Entity<Repository>],
205 cx: &App,
206) -> Option<SharedString> {
207 let worktree_abs_path = worktree.abs_path();
208 repositories
209 .iter()
210 .filter(|repo| {
211 let repo_path = &repo.read(cx).work_directory_abs_path;
212 *repo_path == worktree_abs_path || worktree_abs_path.starts_with(repo_path.as_ref())
213 })
214 .max_by_key(|repo| repo.read(cx).work_directory_abs_path.as_os_str().len())
215 .and_then(|repo| {
216 repo.read(cx)
217 .branch
218 .as_ref()
219 .map(|branch| SharedString::from(branch.name().to_string()))
220 })
221}
222
223pub fn init(cx: &mut App) {
224 #[cfg(target_os = "windows")]
225 cx.on_action(|open_wsl: &zed_actions::wsl_actions::OpenFolderInWsl, cx| {
226 let create_new_window = open_wsl.create_new_window;
227 with_active_or_new_workspace(cx, move |workspace, window, cx| {
228 use gpui::PathPromptOptions;
229 use project::DirectoryLister;
230
231 let paths = workspace.prompt_for_open_path(
232 PathPromptOptions {
233 files: true,
234 directories: true,
235 multiple: false,
236 prompt: None,
237 },
238 DirectoryLister::Local(
239 workspace.project().clone(),
240 workspace.app_state().fs.clone(),
241 ),
242 window,
243 cx,
244 );
245
246 let app_state = workspace.app_state().clone();
247 let window_handle = window.window_handle().downcast::<MultiWorkspace>();
248
249 cx.spawn_in(window, async move |workspace, cx| {
250 use util::paths::SanitizedPath;
251
252 let Some(paths) = paths.await.log_err().flatten() else {
253 return;
254 };
255
256 let wsl_path = paths
257 .iter()
258 .find_map(util::paths::WslPath::from_path);
259
260 if let Some(util::paths::WslPath { distro, path }) = wsl_path {
261 use remote::WslConnectionOptions;
262
263 let connection_options = RemoteConnectionOptions::Wsl(WslConnectionOptions {
264 distro_name: distro.to_string(),
265 user: None,
266 });
267
268 let requesting_window = match create_new_window {
269 false => window_handle,
270 true => None,
271 };
272
273 let open_options = workspace::OpenOptions {
274 requesting_window,
275 ..Default::default()
276 };
277
278 open_remote_project(connection_options, vec![path.into()], app_state, open_options, cx).await.log_err();
279 return;
280 }
281
282 let paths = paths
283 .into_iter()
284 .filter_map(|path| SanitizedPath::new(&path).local_to_wsl())
285 .collect::<Vec<_>>();
286
287 if paths.is_empty() {
288 let message = indoc::indoc! { r#"
289 Invalid path specified when trying to open a folder inside WSL.
290
291 Please note that Zed currently does not support opening network share folders inside wsl.
292 "#};
293
294 let _ = cx.prompt(gpui::PromptLevel::Critical, "Invalid path", Some(&message), &["Ok"]).await;
295 return;
296 }
297
298 workspace.update_in(cx, |workspace, window, cx| {
299 workspace.toggle_modal(window, cx, |window, cx| {
300 crate::wsl_picker::WslOpenModal::new(paths, create_new_window, window, cx)
301 });
302 }).log_err();
303 })
304 .detach();
305 });
306 });
307
308 #[cfg(target_os = "windows")]
309 cx.on_action(|open_wsl: &zed_actions::wsl_actions::OpenWsl, cx| {
310 let create_new_window = open_wsl.create_new_window;
311 with_active_or_new_workspace(cx, move |workspace, window, cx| {
312 let handle = cx.entity().downgrade();
313 let fs = workspace.project().read(cx).fs().clone();
314 workspace.toggle_modal(window, cx, |window, cx| {
315 RemoteServerProjects::wsl(create_new_window, fs, window, handle, cx)
316 });
317 });
318 });
319
320 #[cfg(target_os = "windows")]
321 cx.on_action(|open_wsl: &remote::OpenWslPath, cx| {
322 let open_wsl = open_wsl.clone();
323 with_active_or_new_workspace(cx, move |workspace, window, cx| {
324 let fs = workspace.project().read(cx).fs().clone();
325 add_wsl_distro(fs, &open_wsl.distro, cx);
326 let open_options = OpenOptions {
327 requesting_window: window.window_handle().downcast::<MultiWorkspace>(),
328 ..Default::default()
329 };
330
331 let app_state = workspace.app_state().clone();
332
333 cx.spawn_in(window, async move |_, cx| {
334 open_remote_project(
335 RemoteConnectionOptions::Wsl(open_wsl.distro.clone()),
336 open_wsl.paths,
337 app_state,
338 open_options,
339 cx,
340 )
341 .await
342 })
343 .detach();
344 });
345 });
346
347 cx.on_action(|open_recent: &OpenRecent, cx| {
348 let create_new_window = open_recent.create_new_window;
349
350 match cx
351 .active_window()
352 .and_then(|w| w.downcast::<MultiWorkspace>())
353 {
354 Some(multi_workspace) => {
355 cx.defer(move |cx| {
356 multi_workspace
357 .update(cx, |multi_workspace, window, cx| {
358 let sibling_workspace_ids: HashSet<WorkspaceId> = multi_workspace
359 .workspaces()
360 .filter_map(|ws| ws.read(cx).database_id())
361 .collect();
362
363 let workspace = multi_workspace.workspace().clone();
364 workspace.update(cx, |workspace, cx| {
365 let Some(recent_projects) =
366 workspace.active_modal::<RecentProjects>(cx)
367 else {
368 let focus_handle = workspace.focus_handle(cx);
369 RecentProjects::open(
370 workspace,
371 create_new_window,
372 sibling_workspace_ids,
373 window,
374 focus_handle,
375 cx,
376 );
377 return;
378 };
379
380 recent_projects.update(cx, |recent_projects, cx| {
381 recent_projects
382 .picker
383 .update(cx, |picker, cx| picker.cycle_selection(window, cx))
384 });
385 });
386 })
387 .log_err();
388 });
389 }
390 None => {
391 with_active_or_new_workspace(cx, move |workspace, window, cx| {
392 let Some(recent_projects) = workspace.active_modal::<RecentProjects>(cx) else {
393 let focus_handle = workspace.focus_handle(cx);
394 RecentProjects::open(
395 workspace,
396 create_new_window,
397 HashSet::new(),
398 window,
399 focus_handle,
400 cx,
401 );
402 return;
403 };
404
405 recent_projects.update(cx, |recent_projects, cx| {
406 recent_projects
407 .picker
408 .update(cx, |picker, cx| picker.cycle_selection(window, cx))
409 });
410 });
411 }
412 }
413 });
414 cx.on_action(|open_remote: &OpenRemote, cx| {
415 let from_existing_connection = open_remote.from_existing_connection;
416 let create_new_window = open_remote.create_new_window;
417 with_active_or_new_workspace(cx, move |workspace, window, cx| {
418 if from_existing_connection {
419 cx.propagate();
420 return;
421 }
422 let handle = cx.entity().downgrade();
423 let fs = workspace.project().read(cx).fs().clone();
424 workspace.toggle_modal(window, cx, |window, cx| {
425 RemoteServerProjects::new(create_new_window, fs, window, handle, cx)
426 })
427 });
428 });
429
430 cx.observe_new(DisconnectedOverlay::register).detach();
431
432 cx.on_action(|_: &OpenDevContainer, cx| {
433 with_active_or_new_workspace(cx, move |workspace, window, cx| {
434 if !workspace.project().read(cx).is_local() {
435 cx.spawn_in(window, async move |_, cx| {
436 cx.prompt(
437 gpui::PromptLevel::Critical,
438 "Cannot open Dev Container from remote project",
439 None,
440 &["Ok"],
441 )
442 .await
443 .ok();
444 })
445 .detach();
446 return;
447 }
448
449 let fs = workspace.project().read(cx).fs().clone();
450 let configs = find_devcontainer_configs(workspace, cx);
451 let app_state = workspace.app_state().clone();
452 let dev_container_context = DevContainerContext::from_workspace(workspace, cx);
453 let handle = cx.entity().downgrade();
454 workspace.toggle_modal(window, cx, |window, cx| {
455 RemoteServerProjects::new_dev_container(
456 fs,
457 configs,
458 app_state,
459 dev_container_context,
460 window,
461 handle,
462 cx,
463 )
464 });
465 });
466 });
467
468 // Subscribe to worktree additions to suggest opening the project in a dev container
469 cx.observe_new(
470 |workspace: &mut Workspace, window: Option<&mut Window>, cx: &mut Context<Workspace>| {
471 let Some(window) = window else {
472 return;
473 };
474 cx.subscribe_in(
475 workspace.project(),
476 window,
477 move |workspace, project, event, window, cx| {
478 if let project::Event::WorktreeUpdatedEntries(worktree_id, updated_entries) =
479 event
480 {
481 dev_container_suggest::suggest_on_worktree_updated(
482 workspace,
483 *worktree_id,
484 updated_entries,
485 project,
486 window,
487 cx,
488 );
489 }
490 },
491 )
492 .detach();
493 },
494 )
495 .detach();
496}
497
498#[cfg(target_os = "windows")]
499pub fn add_wsl_distro(
500 fs: Arc<dyn project::Fs>,
501 connection_options: &remote::WslConnectionOptions,
502 cx: &App,
503) {
504 use gpui::ReadGlobal;
505 use settings::SettingsStore;
506
507 let distro_name = connection_options.distro_name.clone();
508 let user = connection_options.user.clone();
509 SettingsStore::global(cx).update_settings_file(fs, move |setting, _| {
510 let connections = setting
511 .remote
512 .wsl_connections
513 .get_or_insert(Default::default());
514
515 if !connections
516 .iter()
517 .any(|conn| conn.distro_name == distro_name && conn.user == user)
518 {
519 use std::collections::BTreeSet;
520
521 connections.push(settings::WslConnection {
522 distro_name,
523 user,
524 projects: BTreeSet::new(),
525 })
526 }
527 });
528}
529
530pub struct RecentProjects {
531 pub picker: Entity<Picker<RecentProjectsDelegate>>,
532 rem_width: f32,
533 _subscriptions: Vec<Subscription>,
534}
535
536impl ModalView for RecentProjects {
537 fn on_before_dismiss(
538 &mut self,
539 window: &mut Window,
540 cx: &mut Context<Self>,
541 ) -> workspace::DismissDecision {
542 let submenu_focused = self.picker.update(cx, |picker, cx| {
543 picker.delegate.actions_menu_handle.is_focused(window, cx)
544 });
545 workspace::DismissDecision::Dismiss(!submenu_focused)
546 }
547}
548
549impl RecentProjects {
550 fn new(
551 delegate: RecentProjectsDelegate,
552 fs: Option<Arc<dyn Fs>>,
553 rem_width: f32,
554 window: &mut Window,
555 cx: &mut Context<Self>,
556 ) -> Self {
557 let style = delegate.style;
558 let picker = cx.new(|cx| {
559 Picker::list(delegate, window, cx)
560 .list_measure_all()
561 .show_scrollbar(true)
562 });
563
564 let picker_focus_handle = picker.focus_handle(cx);
565 picker.update(cx, |picker, _| {
566 picker.delegate.focus_handle = picker_focus_handle;
567 });
568
569 let mut subscriptions = vec![cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent))];
570
571 if style == ProjectPickerStyle::Popover {
572 let picker_focus = picker.focus_handle(cx);
573 subscriptions.push(
574 cx.on_focus_out(&picker_focus, window, |this, _, window, cx| {
575 let submenu_focused = this.picker.update(cx, |picker, cx| {
576 picker.delegate.actions_menu_handle.is_focused(window, cx)
577 });
578 if !submenu_focused {
579 cx.emit(DismissEvent);
580 }
581 }),
582 );
583 }
584 // We do not want to block the UI on a potentially lengthy call to DB, so we're gonna swap
585 // out workspace locations once the future runs to completion.
586 let db = WorkspaceDb::global(cx);
587 cx.spawn_in(window, async move |this, cx| {
588 let Some(fs) = fs else { return };
589 let workspaces = db
590 .recent_workspaces_on_disk(fs.as_ref())
591 .await
592 .log_err()
593 .unwrap_or_default();
594 let workspaces = workspace::resolve_worktree_workspaces(workspaces, fs.as_ref()).await;
595 this.update_in(cx, move |this, window, cx| {
596 this.picker.update(cx, move |picker, cx| {
597 picker.delegate.set_workspaces(workspaces);
598 picker.update_matches(picker.query(cx), window, cx)
599 })
600 })
601 .ok();
602 })
603 .detach();
604 Self {
605 picker,
606 rem_width,
607 _subscriptions: subscriptions,
608 }
609 }
610
611 pub fn open(
612 workspace: &mut Workspace,
613 create_new_window: bool,
614 sibling_workspace_ids: HashSet<WorkspaceId>,
615 window: &mut Window,
616 focus_handle: FocusHandle,
617 cx: &mut Context<Workspace>,
618 ) {
619 let weak = cx.entity().downgrade();
620 let open_folders = get_open_folders(workspace, cx);
621 let project_connection_options = workspace.project().read(cx).remote_connection_options(cx);
622 let fs = Some(workspace.app_state().fs.clone());
623
624 workspace.toggle_modal(window, cx, |window, cx| {
625 let delegate = RecentProjectsDelegate::new(
626 weak,
627 create_new_window,
628 focus_handle,
629 open_folders,
630 sibling_workspace_ids,
631 project_connection_options,
632 ProjectPickerStyle::Modal,
633 );
634
635 Self::new(delegate, fs, 34., window, cx)
636 })
637 }
638
639 pub fn popover(
640 workspace: WeakEntity<Workspace>,
641 sibling_workspace_ids: HashSet<WorkspaceId>,
642 create_new_window: bool,
643 focus_handle: FocusHandle,
644 window: &mut Window,
645 cx: &mut App,
646 ) -> Entity<Self> {
647 let (open_folders, project_connection_options, fs) = workspace
648 .upgrade()
649 .map(|workspace| {
650 let workspace = workspace.read(cx);
651 (
652 get_open_folders(workspace, cx),
653 workspace.project().read(cx).remote_connection_options(cx),
654 Some(workspace.app_state().fs.clone()),
655 )
656 })
657 .unwrap_or_else(|| (Vec::new(), None, None));
658
659 cx.new(|cx| {
660 let delegate = RecentProjectsDelegate::new(
661 workspace,
662 create_new_window,
663 focus_handle,
664 open_folders,
665 sibling_workspace_ids,
666 project_connection_options,
667 ProjectPickerStyle::Popover,
668 );
669 let list = Self::new(delegate, fs, 20., window, cx);
670 list.picker.focus_handle(cx).focus(window, cx);
671 list
672 })
673 }
674
675 fn handle_toggle_open_menu(
676 &mut self,
677 _: &ToggleActionsMenu,
678 window: &mut Window,
679 cx: &mut Context<Self>,
680 ) {
681 self.picker.update(cx, |picker, cx| {
682 let menu_handle = &picker.delegate.actions_menu_handle;
683 if menu_handle.is_deployed() {
684 menu_handle.hide(cx);
685 } else {
686 menu_handle.show(window, cx);
687 }
688 });
689 }
690
691 fn handle_remove_selected(
692 &mut self,
693 _: &RemoveSelected,
694 window: &mut Window,
695 cx: &mut Context<Self>,
696 ) {
697 self.picker.update(cx, |picker, cx| {
698 let ix = picker.delegate.selected_index;
699
700 match picker.delegate.filtered_entries.get(ix) {
701 Some(ProjectPickerEntry::OpenFolder { index, .. }) => {
702 if let Some(folder) = picker.delegate.open_folders.get(*index) {
703 let worktree_id = folder.worktree_id;
704 let Some(workspace) = picker.delegate.workspace.upgrade() else {
705 return;
706 };
707 workspace.update(cx, |workspace, cx| {
708 let project = workspace.project().clone();
709 project.update(cx, |project, cx| {
710 project.remove_worktree(worktree_id, cx);
711 });
712 });
713 picker.delegate.open_folders = get_open_folders(workspace.read(cx), cx);
714 let query = picker.query(cx);
715 picker.update_matches(query, window, cx);
716 }
717 }
718 Some(ProjectPickerEntry::OpenProject(hit)) => {
719 if let Some((workspace_id, ..)) =
720 picker.delegate.workspaces.get(hit.candidate_id)
721 {
722 let workspace_id = *workspace_id;
723 picker
724 .delegate
725 .remove_sibling_workspace(workspace_id, window, cx);
726 let query = picker.query(cx);
727 picker.update_matches(query, window, cx);
728 }
729 }
730 Some(ProjectPickerEntry::RecentProject(_)) => {
731 picker.delegate.delete_recent_project(ix, window, cx);
732 }
733 _ => {}
734 }
735 });
736 }
737
738 fn handle_add_to_workspace(
739 &mut self,
740 _: &AddToWorkspace,
741 window: &mut Window,
742 cx: &mut Context<Self>,
743 ) {
744 self.picker.update(cx, |picker, cx| {
745 let ix = picker.delegate.selected_index;
746
747 if let Some(ProjectPickerEntry::RecentProject(hit)) =
748 picker.delegate.filtered_entries.get(ix)
749 {
750 if let Some((_, location, paths, _)) =
751 picker.delegate.workspaces.get(hit.candidate_id)
752 {
753 if matches!(location, SerializedWorkspaceLocation::Local) {
754 let paths_to_add = paths.paths().to_vec();
755 picker
756 .delegate
757 .add_project_to_workspace(paths_to_add, window, cx);
758 }
759 }
760 }
761 });
762 }
763}
764
765impl EventEmitter<DismissEvent> for RecentProjects {}
766
767impl Focusable for RecentProjects {
768 fn focus_handle(&self, cx: &App) -> FocusHandle {
769 self.picker.focus_handle(cx)
770 }
771}
772
773impl Render for RecentProjects {
774 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
775 v_flex()
776 .key_context("RecentProjects")
777 .on_action(cx.listener(Self::handle_toggle_open_menu))
778 .on_action(cx.listener(Self::handle_remove_selected))
779 .on_action(cx.listener(Self::handle_add_to_workspace))
780 .w(rems(self.rem_width))
781 .child(self.picker.clone())
782 }
783}
784
785pub struct RecentProjectsDelegate {
786 workspace: WeakEntity<Workspace>,
787 open_folders: Vec<OpenFolderEntry>,
788 sibling_workspace_ids: HashSet<WorkspaceId>,
789 workspaces: Vec<(
790 WorkspaceId,
791 SerializedWorkspaceLocation,
792 PathList,
793 DateTime<Utc>,
794 )>,
795 filtered_entries: Vec<ProjectPickerEntry>,
796 selected_index: usize,
797 render_paths: bool,
798 create_new_window: bool,
799 // Flag to reset index when there is a new query vs not reset index when user delete an item
800 reset_selected_match_index: bool,
801 has_any_non_local_projects: bool,
802 project_connection_options: Option<RemoteConnectionOptions>,
803 focus_handle: FocusHandle,
804 style: ProjectPickerStyle,
805 actions_menu_handle: PopoverMenuHandle<ContextMenu>,
806}
807
808impl RecentProjectsDelegate {
809 fn new(
810 workspace: WeakEntity<Workspace>,
811 create_new_window: bool,
812 focus_handle: FocusHandle,
813 open_folders: Vec<OpenFolderEntry>,
814 sibling_workspace_ids: HashSet<WorkspaceId>,
815 project_connection_options: Option<RemoteConnectionOptions>,
816 style: ProjectPickerStyle,
817 ) -> Self {
818 let render_paths = style == ProjectPickerStyle::Modal;
819 Self {
820 workspace,
821 open_folders,
822 sibling_workspace_ids,
823 workspaces: Vec::new(),
824 filtered_entries: Vec::new(),
825 selected_index: 0,
826 create_new_window,
827 render_paths,
828 reset_selected_match_index: true,
829 has_any_non_local_projects: project_connection_options.is_some(),
830 project_connection_options,
831 focus_handle,
832 style,
833 actions_menu_handle: PopoverMenuHandle::default(),
834 }
835 }
836
837 pub fn set_workspaces(
838 &mut self,
839 workspaces: Vec<(
840 WorkspaceId,
841 SerializedWorkspaceLocation,
842 PathList,
843 DateTime<Utc>,
844 )>,
845 ) {
846 self.workspaces = workspaces;
847 let has_non_local_recent = !self
848 .workspaces
849 .iter()
850 .all(|(_, location, _, _)| matches!(location, SerializedWorkspaceLocation::Local));
851 self.has_any_non_local_projects =
852 self.project_connection_options.is_some() || has_non_local_recent;
853 }
854}
855impl EventEmitter<DismissEvent> for RecentProjectsDelegate {}
856impl PickerDelegate for RecentProjectsDelegate {
857 type ListItem = AnyElement;
858
859 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
860 "Search projects…".into()
861 }
862
863 fn render_editor(
864 &self,
865 editor: &Arc<dyn ErasedEditor>,
866 window: &mut Window,
867 cx: &mut Context<Picker<Self>>,
868 ) -> Div {
869 h_flex()
870 .flex_none()
871 .h_9()
872 .px_2p5()
873 .justify_between()
874 .border_b_1()
875 .border_color(cx.theme().colors().border_variant)
876 .child(editor.render(window, cx))
877 }
878
879 fn match_count(&self) -> usize {
880 self.filtered_entries.len()
881 }
882
883 fn selected_index(&self) -> usize {
884 self.selected_index
885 }
886
887 fn set_selected_index(
888 &mut self,
889 ix: usize,
890 _window: &mut Window,
891 _cx: &mut Context<Picker<Self>>,
892 ) {
893 self.selected_index = ix;
894 }
895
896 fn can_select(&self, ix: usize, _window: &mut Window, _cx: &mut Context<Picker<Self>>) -> bool {
897 matches!(
898 self.filtered_entries.get(ix),
899 Some(
900 ProjectPickerEntry::OpenFolder { .. }
901 | ProjectPickerEntry::OpenProject(_)
902 | ProjectPickerEntry::RecentProject(_)
903 )
904 )
905 }
906
907 fn update_matches(
908 &mut self,
909 query: String,
910 _: &mut Window,
911 cx: &mut Context<Picker<Self>>,
912 ) -> gpui::Task<()> {
913 let query = query.trim_start();
914 let smart_case = query.chars().any(|c| c.is_uppercase());
915 let is_empty_query = query.is_empty();
916
917 let folder_matches = if self.open_folders.is_empty() {
918 Vec::new()
919 } else {
920 let candidates: Vec<_> = self
921 .open_folders
922 .iter()
923 .enumerate()
924 .map(|(id, folder)| StringMatchCandidate::new(id, folder.name.as_ref()))
925 .collect();
926
927 smol::block_on(fuzzy::match_strings(
928 &candidates,
929 query,
930 smart_case,
931 true,
932 100,
933 &Default::default(),
934 cx.background_executor().clone(),
935 ))
936 };
937
938 let sibling_candidates: Vec<_> = self
939 .workspaces
940 .iter()
941 .enumerate()
942 .filter(|(_, (id, _, _, _))| self.is_sibling_workspace(*id, cx))
943 .map(|(id, (_, _, paths, _))| {
944 let combined_string = paths
945 .ordered_paths()
946 .map(|path| path.compact().to_string_lossy().into_owned())
947 .collect::<Vec<_>>()
948 .join("");
949 StringMatchCandidate::new(id, &combined_string)
950 })
951 .collect();
952
953 let mut sibling_matches = smol::block_on(fuzzy::match_strings(
954 &sibling_candidates,
955 query,
956 smart_case,
957 true,
958 100,
959 &Default::default(),
960 cx.background_executor().clone(),
961 ));
962 sibling_matches.sort_unstable_by(|a, b| {
963 b.score
964 .partial_cmp(&a.score)
965 .unwrap_or(std::cmp::Ordering::Equal)
966 .then_with(|| a.candidate_id.cmp(&b.candidate_id))
967 });
968
969 // Build candidates for recent projects (not current, not sibling, not open folder)
970 let recent_candidates: Vec<_> = self
971 .workspaces
972 .iter()
973 .enumerate()
974 .filter(|(_, (id, _, paths, _))| self.is_valid_recent_candidate(*id, paths, cx))
975 .map(|(id, (_, _, paths, _))| {
976 let combined_string = paths
977 .ordered_paths()
978 .map(|path| path.compact().to_string_lossy().into_owned())
979 .collect::<Vec<_>>()
980 .join("");
981 StringMatchCandidate::new(id, &combined_string)
982 })
983 .collect();
984
985 let mut recent_matches = smol::block_on(fuzzy::match_strings(
986 &recent_candidates,
987 query,
988 smart_case,
989 true,
990 100,
991 &Default::default(),
992 cx.background_executor().clone(),
993 ));
994 recent_matches.sort_unstable_by(|a, b| {
995 b.score
996 .partial_cmp(&a.score)
997 .unwrap_or(std::cmp::Ordering::Equal)
998 .then_with(|| a.candidate_id.cmp(&b.candidate_id))
999 });
1000
1001 let mut entries = Vec::new();
1002
1003 if !self.open_folders.is_empty() {
1004 let matched_folders: Vec<_> = if is_empty_query {
1005 (0..self.open_folders.len())
1006 .map(|i| (i, Vec::new()))
1007 .collect()
1008 } else {
1009 folder_matches
1010 .iter()
1011 .map(|m| (m.candidate_id, m.positions.clone()))
1012 .collect()
1013 };
1014
1015 for (index, positions) in matched_folders {
1016 entries.push(ProjectPickerEntry::OpenFolder { index, positions });
1017 }
1018 }
1019
1020 let has_siblings_to_show = if is_empty_query {
1021 !sibling_candidates.is_empty()
1022 } else {
1023 !sibling_matches.is_empty()
1024 };
1025
1026 if has_siblings_to_show {
1027 entries.push(ProjectPickerEntry::Header("This Window".into()));
1028
1029 if is_empty_query {
1030 for (id, (workspace_id, _, _, _)) in self.workspaces.iter().enumerate() {
1031 if self.is_sibling_workspace(*workspace_id, cx) {
1032 entries.push(ProjectPickerEntry::OpenProject(StringMatch {
1033 candidate_id: id,
1034 score: 0.0,
1035 positions: Vec::new(),
1036 string: String::new(),
1037 }));
1038 }
1039 }
1040 } else {
1041 for m in sibling_matches {
1042 entries.push(ProjectPickerEntry::OpenProject(m));
1043 }
1044 }
1045 }
1046
1047 let has_recent_to_show = if is_empty_query {
1048 !recent_candidates.is_empty()
1049 } else {
1050 !recent_matches.is_empty()
1051 };
1052
1053 if has_recent_to_show {
1054 entries.push(ProjectPickerEntry::Header("Recent Projects".into()));
1055
1056 if is_empty_query {
1057 for (id, (workspace_id, _, paths, _)) in self.workspaces.iter().enumerate() {
1058 if self.is_valid_recent_candidate(*workspace_id, paths, cx) {
1059 entries.push(ProjectPickerEntry::RecentProject(StringMatch {
1060 candidate_id: id,
1061 score: 0.0,
1062 positions: Vec::new(),
1063 string: String::new(),
1064 }));
1065 }
1066 }
1067 } else {
1068 for m in recent_matches {
1069 entries.push(ProjectPickerEntry::RecentProject(m));
1070 }
1071 }
1072 }
1073
1074 self.filtered_entries = entries;
1075
1076 if self.reset_selected_match_index {
1077 self.selected_index = self
1078 .filtered_entries
1079 .iter()
1080 .position(|e| !matches!(e, ProjectPickerEntry::Header(_)))
1081 .unwrap_or(0);
1082 }
1083 self.reset_selected_match_index = true;
1084 Task::ready(())
1085 }
1086
1087 fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1088 match self.filtered_entries.get(self.selected_index) {
1089 Some(ProjectPickerEntry::OpenFolder { index, .. }) => {
1090 let Some(folder) = self.open_folders.get(*index) else {
1091 return;
1092 };
1093 let worktree_id = folder.worktree_id;
1094 if let Some(workspace) = self.workspace.upgrade() {
1095 workspace.update(cx, |workspace, cx| {
1096 workspace.set_active_worktree_override(Some(worktree_id), cx);
1097 });
1098 }
1099 cx.emit(DismissEvent);
1100 }
1101 Some(ProjectPickerEntry::OpenProject(selected_match)) => {
1102 let Some((workspace_id, _, _, _)) =
1103 self.workspaces.get(selected_match.candidate_id)
1104 else {
1105 return;
1106 };
1107 let workspace_id = *workspace_id;
1108
1109 if let Some(handle) = window.window_handle().downcast::<MultiWorkspace>() {
1110 cx.defer(move |cx| {
1111 handle
1112 .update(cx, |multi_workspace, window, cx| {
1113 let workspace = multi_workspace
1114 .workspaces()
1115 .find(|ws| ws.read(cx).database_id() == Some(workspace_id));
1116 if let Some(workspace) = workspace {
1117 multi_workspace.activate(workspace, window, cx);
1118 }
1119 })
1120 .log_err();
1121 });
1122 }
1123 cx.emit(DismissEvent);
1124 }
1125 Some(ProjectPickerEntry::RecentProject(selected_match)) => {
1126 let Some(workspace) = self.workspace.upgrade() else {
1127 return;
1128 };
1129 let Some((
1130 candidate_workspace_id,
1131 candidate_workspace_location,
1132 candidate_workspace_paths,
1133 _,
1134 )) = self.workspaces.get(selected_match.candidate_id)
1135 else {
1136 return;
1137 };
1138
1139 let replace_current_window = self.create_new_window == secondary;
1140 let candidate_workspace_id = *candidate_workspace_id;
1141 let candidate_workspace_location = candidate_workspace_location.clone();
1142 let candidate_workspace_paths = candidate_workspace_paths.clone();
1143
1144 workspace.update(cx, |workspace, cx| {
1145 if workspace.database_id() == Some(candidate_workspace_id) {
1146 return;
1147 }
1148 match candidate_workspace_location {
1149 SerializedWorkspaceLocation::Local => {
1150 let paths = candidate_workspace_paths.paths().to_vec();
1151 if replace_current_window {
1152 if let Some(handle) =
1153 window.window_handle().downcast::<MultiWorkspace>()
1154 {
1155 cx.defer(move |cx| {
1156 if let Some(task) = handle
1157 .update(cx, |multi_workspace, window, cx| {
1158 multi_workspace.open_project(
1159 paths,
1160 OpenMode::Replace,
1161 window,
1162 cx,
1163 )
1164 })
1165 .log_err()
1166 {
1167 task.detach_and_log_err(cx);
1168 }
1169 });
1170 }
1171 return;
1172 } else {
1173 workspace
1174 .open_workspace_for_paths(
1175 OpenMode::NewWindow,
1176 paths,
1177 window,
1178 cx,
1179 )
1180 .detach_and_prompt_err(
1181 "Failed to open project",
1182 window,
1183 cx,
1184 |_, _, _| None,
1185 );
1186 }
1187 }
1188 SerializedWorkspaceLocation::Remote(mut connection) => {
1189 let app_state = workspace.app_state().clone();
1190 let replace_window = if replace_current_window {
1191 window.window_handle().downcast::<MultiWorkspace>()
1192 } else {
1193 None
1194 };
1195 let open_options = OpenOptions {
1196 requesting_window: replace_window,
1197 ..Default::default()
1198 };
1199 if let RemoteConnectionOptions::Ssh(connection) = &mut connection {
1200 RemoteSettings::get_global(cx)
1201 .fill_connection_options_from_settings(connection);
1202 };
1203 let paths = candidate_workspace_paths.paths().to_vec();
1204 cx.spawn_in(window, async move |_, cx| {
1205 open_remote_project(
1206 connection.clone(),
1207 paths,
1208 app_state,
1209 open_options,
1210 cx,
1211 )
1212 .await
1213 })
1214 .detach_and_prompt_err(
1215 "Failed to open project",
1216 window,
1217 cx,
1218 |_, _, _| None,
1219 );
1220 }
1221 }
1222 });
1223 cx.emit(DismissEvent);
1224 }
1225 _ => {}
1226 }
1227 }
1228
1229 fn dismissed(&mut self, _window: &mut Window, _: &mut Context<Picker<Self>>) {}
1230
1231 fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
1232 let text = if self.workspaces.is_empty() && self.open_folders.is_empty() {
1233 "Recently opened projects will show up here".into()
1234 } else {
1235 "No matches".into()
1236 };
1237 Some(text)
1238 }
1239
1240 fn render_match(
1241 &self,
1242 ix: usize,
1243 selected: bool,
1244 window: &mut Window,
1245 cx: &mut Context<Picker<Self>>,
1246 ) -> Option<Self::ListItem> {
1247 match self.filtered_entries.get(ix)? {
1248 ProjectPickerEntry::Header(title) => Some(
1249 v_flex()
1250 .w_full()
1251 .gap_1()
1252 .when(ix > 0, |this| this.mt_1().child(Divider::horizontal()))
1253 .child(ListSubHeader::new(title.clone()).inset(true))
1254 .into_any_element(),
1255 ),
1256 ProjectPickerEntry::OpenFolder { index, positions } => {
1257 let folder = self.open_folders.get(*index)?;
1258 let name = folder.name.clone();
1259 let path = folder.path.compact();
1260 let branch = folder.branch.clone();
1261 let is_active = folder.is_active;
1262 let worktree_id = folder.worktree_id;
1263 let positions = positions.clone();
1264 let show_path = self.style == ProjectPickerStyle::Modal;
1265
1266 let secondary_actions = h_flex()
1267 .gap_1()
1268 .child(
1269 IconButton::new(("remove-folder", worktree_id.to_usize()), IconName::Close)
1270 .icon_size(IconSize::Small)
1271 .tooltip(Tooltip::text("Remove Folder from Workspace"))
1272 .on_click(cx.listener(move |picker, _, window, cx| {
1273 let Some(workspace) = picker.delegate.workspace.upgrade() else {
1274 return;
1275 };
1276 workspace.update(cx, |workspace, cx| {
1277 let project = workspace.project().clone();
1278 project.update(cx, |project, cx| {
1279 project.remove_worktree(worktree_id, cx);
1280 });
1281 });
1282 picker.delegate.open_folders =
1283 get_open_folders(workspace.read(cx), cx);
1284 let query = picker.query(cx);
1285 picker.update_matches(query, window, cx);
1286 })),
1287 )
1288 .into_any_element();
1289
1290 let icon = icon_for_remote_connection(self.project_connection_options.as_ref());
1291
1292 Some(
1293 ListItem::new(ix)
1294 .toggle_state(selected)
1295 .inset(true)
1296 .spacing(ListItemSpacing::Sparse)
1297 .child(
1298 h_flex()
1299 .id("open_folder_item")
1300 .gap_3()
1301 .flex_grow()
1302 .when(self.has_any_non_local_projects, |this| {
1303 this.child(Icon::new(icon).color(Color::Muted))
1304 })
1305 .child(
1306 v_flex()
1307 .child(
1308 h_flex()
1309 .gap_1()
1310 .child({
1311 let highlighted = HighlightedMatch {
1312 text: name.to_string(),
1313 highlight_positions: positions,
1314 color: Color::Default,
1315 };
1316 highlighted.render(window, cx)
1317 })
1318 .when_some(branch, |this, branch| {
1319 this.child(
1320 Label::new(branch).color(Color::Muted),
1321 )
1322 })
1323 .when(is_active, |this| {
1324 this.child(
1325 Icon::new(IconName::Check)
1326 .size(IconSize::Small)
1327 .color(Color::Accent),
1328 )
1329 }),
1330 )
1331 .when(show_path, |this| {
1332 this.child(
1333 Label::new(path.to_string_lossy().to_string())
1334 .size(LabelSize::Small)
1335 .color(Color::Muted),
1336 )
1337 }),
1338 )
1339 .when(!show_path, |this| {
1340 this.tooltip(Tooltip::text(path.to_string_lossy().to_string()))
1341 }),
1342 )
1343 .end_slot(secondary_actions)
1344 .show_end_slot_on_hover()
1345 .into_any_element(),
1346 )
1347 }
1348 ProjectPickerEntry::OpenProject(hit) => {
1349 let (workspace_id, location, paths, _) = self.workspaces.get(hit.candidate_id)?;
1350 let workspace_id = *workspace_id;
1351 let ordered_paths: Vec<_> = paths
1352 .ordered_paths()
1353 .map(|p| p.compact().to_string_lossy().to_string())
1354 .collect();
1355 let tooltip_path: SharedString = match &location {
1356 SerializedWorkspaceLocation::Remote(options) => {
1357 let host = options.display_name();
1358 if ordered_paths.len() == 1 {
1359 format!("{} ({})", ordered_paths[0], host).into()
1360 } else {
1361 format!("{}\n({})", ordered_paths.join("\n"), host).into()
1362 }
1363 }
1364 _ => ordered_paths.join("\n").into(),
1365 };
1366
1367 let mut path_start_offset = 0;
1368 let (match_labels, paths): (Vec<_>, Vec<_>) = paths
1369 .ordered_paths()
1370 .map(|p| p.compact())
1371 .map(|path| {
1372 let highlighted_text =
1373 highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
1374 path_start_offset += highlighted_text.1.text.len();
1375 highlighted_text
1376 })
1377 .unzip();
1378
1379 let prefix = match &location {
1380 SerializedWorkspaceLocation::Remote(options) => {
1381 Some(SharedString::from(options.display_name()))
1382 }
1383 _ => None,
1384 };
1385
1386 let highlighted_match = HighlightedMatchWithPaths {
1387 prefix,
1388 match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "),
1389 paths,
1390 };
1391
1392 let icon = icon_for_remote_connection(match location {
1393 SerializedWorkspaceLocation::Local => None,
1394 SerializedWorkspaceLocation::Remote(options) => Some(options),
1395 });
1396
1397 let secondary_actions = h_flex()
1398 .gap_1()
1399 .child(
1400 IconButton::new("remove_open_project", IconName::Close)
1401 .icon_size(IconSize::Small)
1402 .tooltip(Tooltip::text("Remove Project from Window"))
1403 .on_click(cx.listener(move |picker, _, window, cx| {
1404 cx.stop_propagation();
1405 window.prevent_default();
1406 picker
1407 .delegate
1408 .remove_sibling_workspace(workspace_id, window, cx);
1409 let query = picker.query(cx);
1410 picker.update_matches(query, window, cx);
1411 })),
1412 )
1413 .into_any_element();
1414
1415 Some(
1416 ListItem::new(ix)
1417 .toggle_state(selected)
1418 .inset(true)
1419 .spacing(ListItemSpacing::Sparse)
1420 .child(
1421 h_flex()
1422 .id("open_project_info_container")
1423 .gap_3()
1424 .flex_grow()
1425 .when(self.has_any_non_local_projects, |this| {
1426 this.child(Icon::new(icon).color(Color::Muted))
1427 })
1428 .child({
1429 let mut highlighted = highlighted_match;
1430 if !self.render_paths {
1431 highlighted.paths.clear();
1432 }
1433 highlighted.render(window, cx)
1434 })
1435 .tooltip(Tooltip::text(tooltip_path)),
1436 )
1437 .end_slot(secondary_actions)
1438 .show_end_slot_on_hover()
1439 .into_any_element(),
1440 )
1441 }
1442 ProjectPickerEntry::RecentProject(hit) => {
1443 let (_, location, paths, _) = self.workspaces.get(hit.candidate_id)?;
1444 let is_local = matches!(location, SerializedWorkspaceLocation::Local);
1445 let paths_to_add = paths.paths().to_vec();
1446 let ordered_paths: Vec<_> = paths
1447 .ordered_paths()
1448 .map(|p| p.compact().to_string_lossy().to_string())
1449 .collect();
1450 let tooltip_path: SharedString = match &location {
1451 SerializedWorkspaceLocation::Remote(options) => {
1452 let host = options.display_name();
1453 if ordered_paths.len() == 1 {
1454 format!("{} ({})", ordered_paths[0], host).into()
1455 } else {
1456 format!("{}\n({})", ordered_paths.join("\n"), host).into()
1457 }
1458 }
1459 _ => ordered_paths.join("\n").into(),
1460 };
1461
1462 let mut path_start_offset = 0;
1463 let (match_labels, paths): (Vec<_>, Vec<_>) = paths
1464 .ordered_paths()
1465 .map(|p| p.compact())
1466 .map(|path| {
1467 let highlighted_text =
1468 highlights_for_path(path.as_ref(), &hit.positions, path_start_offset);
1469 path_start_offset += highlighted_text.1.text.len();
1470 highlighted_text
1471 })
1472 .unzip();
1473
1474 let prefix = match &location {
1475 SerializedWorkspaceLocation::Remote(options) => {
1476 Some(SharedString::from(options.display_name()))
1477 }
1478 _ => None,
1479 };
1480
1481 let highlighted_match = HighlightedMatchWithPaths {
1482 prefix,
1483 match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "),
1484 paths,
1485 };
1486
1487 let focus_handle = self.focus_handle.clone();
1488
1489 let secondary_actions = h_flex()
1490 .gap_px()
1491 .when(is_local, |this| {
1492 this.child(
1493 IconButton::new("add_to_workspace", IconName::FolderPlus)
1494 .icon_size(IconSize::Small)
1495 .tooltip(Tooltip::text("Add Project to this Workspace"))
1496 .on_click({
1497 let paths_to_add = paths_to_add.clone();
1498 cx.listener(move |picker, _event, window, cx| {
1499 cx.stop_propagation();
1500 window.prevent_default();
1501 picker.delegate.add_project_to_workspace(
1502 paths_to_add.clone(),
1503 window,
1504 cx,
1505 );
1506 })
1507 }),
1508 )
1509 })
1510 .child(
1511 IconButton::new("open_new_window", IconName::ArrowUpRight)
1512 .icon_size(IconSize::XSmall)
1513 .tooltip({
1514 move |_, cx| {
1515 Tooltip::for_action_in(
1516 "Open Project in New Window",
1517 &menu::SecondaryConfirm,
1518 &focus_handle,
1519 cx,
1520 )
1521 }
1522 })
1523 .on_click(cx.listener(move |this, _event, window, cx| {
1524 cx.stop_propagation();
1525 window.prevent_default();
1526 this.delegate.set_selected_index(ix, window, cx);
1527 this.delegate.confirm(true, window, cx);
1528 })),
1529 )
1530 .child(
1531 IconButton::new("delete", IconName::Close)
1532 .icon_size(IconSize::Small)
1533 .tooltip(Tooltip::text("Delete from Recent Projects"))
1534 .on_click(cx.listener(move |this, _event, window, cx| {
1535 cx.stop_propagation();
1536 window.prevent_default();
1537 this.delegate.delete_recent_project(ix, window, cx)
1538 })),
1539 )
1540 .into_any_element();
1541
1542 let icon = icon_for_remote_connection(match location {
1543 SerializedWorkspaceLocation::Local => None,
1544 SerializedWorkspaceLocation::Remote(options) => Some(options),
1545 });
1546
1547 Some(
1548 ListItem::new(ix)
1549 .toggle_state(selected)
1550 .inset(true)
1551 .spacing(ListItemSpacing::Sparse)
1552 .child(
1553 h_flex()
1554 .id("project_info_container")
1555 .gap_3()
1556 .flex_grow()
1557 .when(self.has_any_non_local_projects, |this| {
1558 this.child(Icon::new(icon).color(Color::Muted))
1559 })
1560 .child({
1561 let mut highlighted = highlighted_match;
1562 if !self.render_paths {
1563 highlighted.paths.clear();
1564 }
1565 highlighted.render(window, cx)
1566 })
1567 .tooltip(Tooltip::text(tooltip_path)),
1568 )
1569 .end_slot(secondary_actions)
1570 .show_end_slot_on_hover()
1571 .into_any_element(),
1572 )
1573 }
1574 }
1575 }
1576
1577 fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
1578 let focus_handle = self.focus_handle.clone();
1579 let popover_style = matches!(self.style, ProjectPickerStyle::Popover);
1580 let is_already_open_entry = matches!(
1581 self.filtered_entries.get(self.selected_index),
1582 Some(ProjectPickerEntry::OpenFolder { .. } | ProjectPickerEntry::OpenProject(_))
1583 );
1584
1585 if popover_style {
1586 return Some(
1587 v_flex()
1588 .flex_1()
1589 .p_1p5()
1590 .gap_1()
1591 .border_t_1()
1592 .border_color(cx.theme().colors().border_variant)
1593 .child({
1594 let open_action = workspace::Open::default();
1595 Button::new("open_local_folder", "Open Local Project")
1596 .key_binding(KeyBinding::for_action_in(&open_action, &focus_handle, cx))
1597 .on_click(move |_, window, cx| {
1598 window.dispatch_action(open_action.boxed_clone(), cx)
1599 })
1600 })
1601 .child(
1602 Button::new("open_remote_folder", "Open Remote Project")
1603 .key_binding(KeyBinding::for_action(
1604 &OpenRemote {
1605 from_existing_connection: false,
1606 create_new_window: false,
1607 },
1608 cx,
1609 ))
1610 .on_click(|_, window, cx| {
1611 window.dispatch_action(
1612 OpenRemote {
1613 from_existing_connection: false,
1614 create_new_window: false,
1615 }
1616 .boxed_clone(),
1617 cx,
1618 )
1619 }),
1620 )
1621 .into_any(),
1622 );
1623 }
1624
1625 let selected_entry = self.filtered_entries.get(self.selected_index);
1626
1627 let secondary_footer_actions: Option<AnyElement> = match selected_entry {
1628 Some(ProjectPickerEntry::OpenFolder { .. } | ProjectPickerEntry::OpenProject(_)) => {
1629 let label = if matches!(selected_entry, Some(ProjectPickerEntry::OpenFolder { .. }))
1630 {
1631 "Remove Folder"
1632 } else {
1633 "Remove from Window"
1634 };
1635 Some(
1636 Button::new("remove_selected", label)
1637 .key_binding(KeyBinding::for_action_in(
1638 &RemoveSelected,
1639 &focus_handle,
1640 cx,
1641 ))
1642 .on_click(|_, window, cx| {
1643 window.dispatch_action(RemoveSelected.boxed_clone(), cx)
1644 })
1645 .into_any_element(),
1646 )
1647 }
1648 Some(ProjectPickerEntry::RecentProject(_)) => Some(
1649 Button::new("delete_recent", "Delete")
1650 .key_binding(KeyBinding::for_action_in(
1651 &RemoveSelected,
1652 &focus_handle,
1653 cx,
1654 ))
1655 .on_click(|_, window, cx| {
1656 window.dispatch_action(RemoveSelected.boxed_clone(), cx)
1657 })
1658 .into_any_element(),
1659 ),
1660 _ => None,
1661 };
1662
1663 Some(
1664 h_flex()
1665 .flex_1()
1666 .p_1p5()
1667 .gap_1()
1668 .justify_end()
1669 .border_t_1()
1670 .border_color(cx.theme().colors().border_variant)
1671 .when_some(secondary_footer_actions, |this, actions| {
1672 this.child(actions)
1673 })
1674 .map(|this| {
1675 if is_already_open_entry {
1676 this.child(
1677 Button::new("activate", "Activate")
1678 .key_binding(KeyBinding::for_action_in(
1679 &menu::Confirm,
1680 &focus_handle,
1681 cx,
1682 ))
1683 .on_click(|_, window, cx| {
1684 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1685 }),
1686 )
1687 } else {
1688 this.child(
1689 Button::new("open_new_window", "New Window")
1690 .key_binding(KeyBinding::for_action_in(
1691 &menu::SecondaryConfirm,
1692 &focus_handle,
1693 cx,
1694 ))
1695 .on_click(|_, window, cx| {
1696 window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx)
1697 }),
1698 )
1699 .child(
1700 Button::new("open_here", "Open")
1701 .key_binding(KeyBinding::for_action_in(
1702 &menu::Confirm,
1703 &focus_handle,
1704 cx,
1705 ))
1706 .on_click(|_, window, cx| {
1707 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
1708 }),
1709 )
1710 }
1711 })
1712 .child(Divider::vertical())
1713 .child(
1714 PopoverMenu::new("actions-menu-popover")
1715 .with_handle(self.actions_menu_handle.clone())
1716 .anchor(gpui::Corner::BottomRight)
1717 .offset(gpui::Point {
1718 x: px(0.0),
1719 y: px(-2.0),
1720 })
1721 .trigger(
1722 Button::new("actions-trigger", "Actions")
1723 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
1724 .key_binding(KeyBinding::for_action_in(
1725 &ToggleActionsMenu,
1726 &focus_handle,
1727 cx,
1728 )),
1729 )
1730 .menu({
1731 let focus_handle = focus_handle.clone();
1732 let show_add_to_workspace = match selected_entry {
1733 Some(ProjectPickerEntry::RecentProject(hit)) => self
1734 .workspaces
1735 .get(hit.candidate_id)
1736 .map(|(_, loc, ..)| {
1737 matches!(loc, SerializedWorkspaceLocation::Local)
1738 })
1739 .unwrap_or(false),
1740 _ => false,
1741 };
1742
1743 move |window, cx| {
1744 Some(ContextMenu::build(window, cx, {
1745 let focus_handle = focus_handle.clone();
1746 move |menu, _, _| {
1747 menu.context(focus_handle)
1748 .when(show_add_to_workspace, |menu| {
1749 menu.action(
1750 "Add to Workspace",
1751 AddToWorkspace.boxed_clone(),
1752 )
1753 .separator()
1754 })
1755 .action(
1756 "Open Local Project",
1757 workspace::Open::default().boxed_clone(),
1758 )
1759 .action(
1760 "Open Remote Project",
1761 OpenRemote {
1762 from_existing_connection: false,
1763 create_new_window: false,
1764 }
1765 .boxed_clone(),
1766 )
1767 }
1768 }))
1769 }
1770 }),
1771 )
1772 .into_any(),
1773 )
1774 }
1775}
1776
1777pub(crate) fn icon_for_remote_connection(options: Option<&RemoteConnectionOptions>) -> IconName {
1778 match options {
1779 None => IconName::Screen,
1780 Some(options) => match options {
1781 RemoteConnectionOptions::Ssh(_) => IconName::Server,
1782 RemoteConnectionOptions::Wsl(_) => IconName::Linux,
1783 RemoteConnectionOptions::Docker(_) => IconName::Box,
1784 #[cfg(any(test, feature = "test-support"))]
1785 RemoteConnectionOptions::Mock(_) => IconName::Server,
1786 },
1787 }
1788}
1789
1790// Compute the highlighted text for the name and path
1791pub(crate) fn highlights_for_path(
1792 path: &Path,
1793 match_positions: &Vec<usize>,
1794 path_start_offset: usize,
1795) -> (Option<HighlightedMatch>, HighlightedMatch) {
1796 let path_string = path.to_string_lossy();
1797 let path_text = path_string.to_string();
1798 let path_byte_len = path_text.len();
1799 // Get the subset of match highlight positions that line up with the given path.
1800 // Also adjusts them to start at the path start
1801 let path_positions = match_positions
1802 .iter()
1803 .copied()
1804 .skip_while(|position| *position < path_start_offset)
1805 .take_while(|position| *position < path_start_offset + path_byte_len)
1806 .map(|position| position - path_start_offset)
1807 .collect::<Vec<_>>();
1808
1809 // Again subset the highlight positions to just those that line up with the file_name
1810 // again adjusted to the start of the file_name
1811 let file_name_text_and_positions = path.file_name().map(|file_name| {
1812 let file_name_text = file_name.to_string_lossy().into_owned();
1813 let file_name_start_byte = path_byte_len - file_name_text.len();
1814 let highlight_positions = path_positions
1815 .iter()
1816 .copied()
1817 .skip_while(|position| *position < file_name_start_byte)
1818 .take_while(|position| *position < file_name_start_byte + file_name_text.len())
1819 .map(|position| position - file_name_start_byte)
1820 .collect::<Vec<_>>();
1821 HighlightedMatch {
1822 text: file_name_text,
1823 highlight_positions,
1824 color: Color::Default,
1825 }
1826 });
1827
1828 (
1829 file_name_text_and_positions,
1830 HighlightedMatch {
1831 text: path_text,
1832 highlight_positions: path_positions,
1833 color: Color::Default,
1834 },
1835 )
1836}
1837impl RecentProjectsDelegate {
1838 fn add_project_to_workspace(
1839 &mut self,
1840 paths: Vec<PathBuf>,
1841 window: &mut Window,
1842 cx: &mut Context<Picker<Self>>,
1843 ) {
1844 let Some(workspace) = self.workspace.upgrade() else {
1845 return;
1846 };
1847 let open_paths_task = workspace.update(cx, |workspace, cx| {
1848 workspace.open_paths(
1849 paths,
1850 OpenOptions {
1851 visible: Some(OpenVisible::All),
1852 ..Default::default()
1853 },
1854 None,
1855 window,
1856 cx,
1857 )
1858 });
1859 cx.spawn_in(window, async move |picker, cx| {
1860 let _result = open_paths_task.await;
1861 picker
1862 .update_in(cx, |picker, window, cx| {
1863 let Some(workspace) = picker.delegate.workspace.upgrade() else {
1864 return;
1865 };
1866 picker.delegate.open_folders = get_open_folders(workspace.read(cx), cx);
1867 let query = picker.query(cx);
1868 picker.update_matches(query, window, cx);
1869 })
1870 .ok();
1871 })
1872 .detach();
1873 }
1874
1875 fn delete_recent_project(
1876 &self,
1877 ix: usize,
1878 window: &mut Window,
1879 cx: &mut Context<Picker<Self>>,
1880 ) {
1881 if let Some(ProjectPickerEntry::RecentProject(selected_match)) =
1882 self.filtered_entries.get(ix)
1883 {
1884 let (workspace_id, _, _, _) = &self.workspaces[selected_match.candidate_id];
1885 let workspace_id = *workspace_id;
1886 let fs = self
1887 .workspace
1888 .upgrade()
1889 .map(|ws| ws.read(cx).app_state().fs.clone());
1890 let db = WorkspaceDb::global(cx);
1891 cx.spawn_in(window, async move |this, cx| {
1892 db.delete_workspace_by_id(workspace_id).await.log_err();
1893 let Some(fs) = fs else { return };
1894 let workspaces = db
1895 .recent_workspaces_on_disk(fs.as_ref())
1896 .await
1897 .unwrap_or_default();
1898 let workspaces =
1899 workspace::resolve_worktree_workspaces(workspaces, fs.as_ref()).await;
1900 this.update_in(cx, move |picker, window, cx| {
1901 picker.delegate.set_workspaces(workspaces);
1902 picker
1903 .delegate
1904 .set_selected_index(ix.saturating_sub(1), window, cx);
1905 picker.delegate.reset_selected_match_index = false;
1906 picker.update_matches(picker.query(cx), window, cx);
1907 // After deleting a project, we want to update the history manager to reflect the change.
1908 // But we do not emit a update event when user opens a project, because it's handled in `workspace::load_workspace`.
1909 if let Some(history_manager) = HistoryManager::global(cx) {
1910 history_manager
1911 .update(cx, |this, cx| this.delete_history(workspace_id, cx));
1912 }
1913 })
1914 .ok();
1915 })
1916 .detach();
1917 }
1918 }
1919
1920 fn remove_sibling_workspace(
1921 &mut self,
1922 workspace_id: WorkspaceId,
1923 window: &mut Window,
1924 cx: &mut Context<Picker<Self>>,
1925 ) {
1926 if let Some(handle) = window.window_handle().downcast::<MultiWorkspace>() {
1927 cx.defer(move |cx| {
1928 handle
1929 .update(cx, |multi_workspace, window, cx| {
1930 let workspace = multi_workspace
1931 .workspaces()
1932 .find(|ws| ws.read(cx).database_id() == Some(workspace_id));
1933 if let Some(workspace) = workspace {
1934 multi_workspace
1935 .remove_group_containing_workspace(&workspace, window, cx);
1936 }
1937 })
1938 .log_err();
1939 });
1940 }
1941
1942 self.sibling_workspace_ids.remove(&workspace_id);
1943 }
1944
1945 fn is_current_workspace(
1946 &self,
1947 workspace_id: WorkspaceId,
1948 cx: &mut Context<Picker<Self>>,
1949 ) -> bool {
1950 if let Some(workspace) = self.workspace.upgrade() {
1951 let workspace = workspace.read(cx);
1952 if Some(workspace_id) == workspace.database_id() {
1953 return true;
1954 }
1955 }
1956
1957 false
1958 }
1959
1960 fn is_sibling_workspace(
1961 &self,
1962 workspace_id: WorkspaceId,
1963 cx: &mut Context<Picker<Self>>,
1964 ) -> bool {
1965 self.sibling_workspace_ids.contains(&workspace_id)
1966 && !self.is_current_workspace(workspace_id, cx)
1967 }
1968
1969 fn is_open_folder(&self, paths: &PathList) -> bool {
1970 if self.open_folders.is_empty() {
1971 return false;
1972 }
1973
1974 for workspace_path in paths.paths() {
1975 for open_folder in &self.open_folders {
1976 if workspace_path == &open_folder.path {
1977 return true;
1978 }
1979 }
1980 }
1981
1982 false
1983 }
1984
1985 fn is_valid_recent_candidate(
1986 &self,
1987 workspace_id: WorkspaceId,
1988 paths: &PathList,
1989 cx: &mut Context<Picker<Self>>,
1990 ) -> bool {
1991 !self.is_current_workspace(workspace_id, cx)
1992 && !self.is_sibling_workspace(workspace_id, cx)
1993 && !self.is_open_folder(paths)
1994 }
1995}
1996
1997#[cfg(test)]
1998mod tests {
1999 use std::path::PathBuf;
2000
2001 use editor::Editor;
2002 use gpui::{TestAppContext, UpdateGlobal, WindowHandle};
2003
2004 use serde_json::json;
2005 use settings::SettingsStore;
2006 use util::path;
2007 use workspace::{AppState, open_paths};
2008
2009 use super::*;
2010
2011 #[gpui::test]
2012 async fn test_dirty_workspace_replaced_when_opening_recent_project(cx: &mut TestAppContext) {
2013 let app_state = init_test(cx);
2014
2015 cx.update(|cx| {
2016 SettingsStore::update_global(cx, |store, cx| {
2017 store.update_user_settings(cx, |settings| {
2018 settings
2019 .session
2020 .get_or_insert_default()
2021 .restore_unsaved_buffers = Some(false)
2022 });
2023 });
2024 });
2025
2026 app_state
2027 .fs
2028 .as_fake()
2029 .insert_tree(
2030 path!("/dir"),
2031 json!({
2032 "main.ts": "a"
2033 }),
2034 )
2035 .await;
2036 app_state
2037 .fs
2038 .as_fake()
2039 .insert_tree(path!("/test/path"), json!({}))
2040 .await;
2041 cx.update(|cx| {
2042 open_paths(
2043 &[PathBuf::from(path!("/dir/main.ts"))],
2044 app_state,
2045 workspace::OpenOptions::default(),
2046 cx,
2047 )
2048 })
2049 .await
2050 .unwrap();
2051 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
2052
2053 let multi_workspace = cx.update(|cx| cx.windows()[0].downcast::<MultiWorkspace>().unwrap());
2054 multi_workspace
2055 .update(cx, |multi_workspace, _, cx| {
2056 assert!(!multi_workspace.workspace().read(cx).is_edited())
2057 })
2058 .unwrap();
2059
2060 let editor = multi_workspace
2061 .read_with(cx, |multi_workspace, cx| {
2062 multi_workspace
2063 .workspace()
2064 .read(cx)
2065 .active_item(cx)
2066 .unwrap()
2067 .downcast::<Editor>()
2068 .unwrap()
2069 })
2070 .unwrap();
2071 multi_workspace
2072 .update(cx, |_, window, cx| {
2073 editor.update(cx, |editor, cx| editor.insert("EDIT", window, cx));
2074 })
2075 .unwrap();
2076 multi_workspace
2077 .update(cx, |multi_workspace, _, cx| {
2078 assert!(
2079 multi_workspace.workspace().read(cx).is_edited(),
2080 "After inserting more text into the editor without saving, we should have a dirty project"
2081 )
2082 })
2083 .unwrap();
2084
2085 let recent_projects_picker = open_recent_projects(&multi_workspace, cx);
2086 multi_workspace
2087 .update(cx, |_, _, cx| {
2088 recent_projects_picker.update(cx, |picker, cx| {
2089 assert_eq!(picker.query(cx), "");
2090 let delegate = &mut picker.delegate;
2091 delegate.set_workspaces(vec![(
2092 WorkspaceId::default(),
2093 SerializedWorkspaceLocation::Local,
2094 PathList::new(&[path!("/test/path")]),
2095 Utc::now(),
2096 )]);
2097 delegate.filtered_entries =
2098 vec![ProjectPickerEntry::RecentProject(StringMatch {
2099 candidate_id: 0,
2100 score: 1.0,
2101 positions: Vec::new(),
2102 string: "fake candidate".to_string(),
2103 })];
2104 });
2105 })
2106 .unwrap();
2107
2108 assert!(
2109 !cx.has_pending_prompt(),
2110 "Should have no pending prompt on dirty project before opening the new recent project"
2111 );
2112 let dirty_workspace = multi_workspace
2113 .read_with(cx, |multi_workspace, _cx| {
2114 multi_workspace.workspace().clone()
2115 })
2116 .unwrap();
2117
2118 cx.dispatch_action(*multi_workspace, menu::Confirm);
2119 cx.run_until_parked();
2120
2121 // prepare_to_close triggers a save prompt for the dirty buffer.
2122 // Choose "Don't Save" (index 2) to discard and continue replacing.
2123 assert!(
2124 cx.has_pending_prompt(),
2125 "Should prompt to save dirty buffer before replacing workspace"
2126 );
2127 cx.simulate_prompt_answer("Don't Save");
2128 cx.run_until_parked();
2129
2130 multi_workspace
2131 .update(cx, |multi_workspace, _, cx| {
2132 assert!(
2133 multi_workspace
2134 .workspace()
2135 .read(cx)
2136 .active_modal::<RecentProjects>(cx)
2137 .is_none(),
2138 "Should remove the modal after selecting new recent project"
2139 );
2140
2141 assert!(
2142 !multi_workspace
2143 .workspaces()
2144 .any(|workspace| workspace == dirty_workspace),
2145 "The original dirty workspace should have been replaced"
2146 );
2147
2148 assert!(
2149 !multi_workspace.workspace().read(cx).is_edited(),
2150 "The active workspace should be the freshly opened one, not dirty"
2151 );
2152 })
2153 .unwrap();
2154 }
2155
2156 fn open_recent_projects(
2157 multi_workspace: &WindowHandle<MultiWorkspace>,
2158 cx: &mut TestAppContext,
2159 ) -> Entity<Picker<RecentProjectsDelegate>> {
2160 cx.dispatch_action(
2161 (*multi_workspace).into(),
2162 OpenRecent {
2163 create_new_window: false,
2164 },
2165 );
2166 multi_workspace
2167 .update(cx, |multi_workspace, _, cx| {
2168 multi_workspace
2169 .workspace()
2170 .read(cx)
2171 .active_modal::<RecentProjects>(cx)
2172 .unwrap()
2173 .read(cx)
2174 .picker
2175 .clone()
2176 })
2177 .unwrap()
2178 }
2179
2180 #[gpui::test]
2181 async fn test_open_dev_container_action_with_single_config(cx: &mut TestAppContext) {
2182 let app_state = init_test(cx);
2183
2184 app_state
2185 .fs
2186 .as_fake()
2187 .insert_tree(
2188 path!("/project"),
2189 json!({
2190 ".devcontainer": {
2191 "devcontainer.json": "{}"
2192 },
2193 "src": {
2194 "main.rs": "fn main() {}"
2195 }
2196 }),
2197 )
2198 .await;
2199
2200 // Open a file path (not a directory) so that the worktree root is a
2201 // file. This means `active_project_directory` returns `None`, which
2202 // causes `DevContainerContext::from_workspace` to return `None`,
2203 // preventing `open_dev_container` from spawning real I/O (docker
2204 // commands, shell environment loading) that is incompatible with the
2205 // test scheduler. The modal is still created and the re-entrancy
2206 // guard that this test validates is still exercised.
2207 cx.update(|cx| {
2208 open_paths(
2209 &[PathBuf::from(path!("/project/src/main.rs"))],
2210 app_state,
2211 workspace::OpenOptions::default(),
2212 cx,
2213 )
2214 })
2215 .await
2216 .unwrap();
2217
2218 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
2219 let multi_workspace = cx.update(|cx| cx.windows()[0].downcast::<MultiWorkspace>().unwrap());
2220
2221 cx.run_until_parked();
2222
2223 // This dispatch triggers with_active_or_new_workspace -> MultiWorkspace::update
2224 // -> Workspace::update -> toggle_modal -> new_dev_container.
2225 // Before the fix, this panicked with "cannot read workspace::Workspace while
2226 // it is already being updated" because new_dev_container and open_dev_container
2227 // tried to read the Workspace entity through a WeakEntity handle while it was
2228 // already leased by the outer update.
2229 cx.dispatch_action(*multi_workspace, OpenDevContainer);
2230
2231 multi_workspace
2232 .update(cx, |multi_workspace, _, cx| {
2233 let modal = multi_workspace
2234 .workspace()
2235 .read(cx)
2236 .active_modal::<RemoteServerProjects>(cx);
2237 assert!(
2238 modal.is_some(),
2239 "Dev container modal should be open after dispatching OpenDevContainer"
2240 );
2241 })
2242 .unwrap();
2243 }
2244
2245 #[gpui::test]
2246 async fn test_open_dev_container_action_with_multiple_configs(cx: &mut TestAppContext) {
2247 let app_state = init_test(cx);
2248
2249 app_state
2250 .fs
2251 .as_fake()
2252 .insert_tree(
2253 path!("/project"),
2254 json!({
2255 ".devcontainer": {
2256 "rust": {
2257 "devcontainer.json": "{}"
2258 },
2259 "python": {
2260 "devcontainer.json": "{}"
2261 }
2262 },
2263 "src": {
2264 "main.rs": "fn main() {}"
2265 }
2266 }),
2267 )
2268 .await;
2269
2270 cx.update(|cx| {
2271 open_paths(
2272 &[PathBuf::from(path!("/project"))],
2273 app_state,
2274 workspace::OpenOptions::default(),
2275 cx,
2276 )
2277 })
2278 .await
2279 .unwrap();
2280
2281 assert_eq!(cx.update(|cx| cx.windows().len()), 1);
2282 let multi_workspace = cx.update(|cx| cx.windows()[0].downcast::<MultiWorkspace>().unwrap());
2283
2284 cx.run_until_parked();
2285
2286 cx.dispatch_action(*multi_workspace, OpenDevContainer);
2287
2288 multi_workspace
2289 .update(cx, |multi_workspace, _, cx| {
2290 let modal = multi_workspace
2291 .workspace()
2292 .read(cx)
2293 .active_modal::<RemoteServerProjects>(cx);
2294 assert!(
2295 modal.is_some(),
2296 "Dev container modal should be open after dispatching OpenDevContainer with multiple configs"
2297 );
2298 })
2299 .unwrap();
2300 }
2301
2302 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
2303 cx.update(|cx| {
2304 let state = AppState::test(cx);
2305 crate::init(cx);
2306 editor::init(cx);
2307 state
2308 })
2309 }
2310}